Concepts / One-Hot Encoding for Categorical Features

One-Hot Encoding for Categorical Features

The storage format and the semantics are two separate questions. An integer column can represent categories, because the storage type says nothing reliable about whether a feature is a quantity. The answer to one question does not settle the other.

  • Programming

A Column of Numbers That Are Not Quantities

Many datasets are full of numbers that were never meant to be measured. A column might hold 0, 1, 2, and so on, while the thing it describes is a set of named options such as a job type, a country, or a survey answer. Once the labels have been replaced by digits, the table looks like it contains quantities, and it is easy to forget what the digits stand for.

This article follows one question through to the end: how do you decide what kind of feature an integer column really is, and what has to happen before a model can use it? The answer begins with a common assumption that is worth examining first, because it is the one most likely to cause trouble.

Storage Type Versus Meaning

A common assumption goes like this: if a column contains integers, then its values are counts or measurements, so the column is continuous and the numbers can be compared, averaged, and fed to a model as ordinary magnitudes. This belief treats the data type of the stored value as if it revealed the meaning of the feature.

Key point

The storage format and the semantics are two separate questions. An integer column can represent categories, because the storage type says nothing reliable about whether a feature is a quantity. The answer to one question does not settle the other.

Categorical data is often stored as integers for practical reasons: integers are easier to store, or the way the data was collected produced numeric codes. In the adult dataset, a variable such as workclass was stored as text strings like Private. Text clearly marks a variable as categorical, but it has a drawback, because spelling errors become possible. Storing the same information as integers avoids spelling errors but removes the visible signal that the column is categorical.

In the real world

Imagine a census questionnaire where each workclass answer was recorded by position: 0 for the first box ticked, 1 for the second, 2 for the third, and so on up to 8. The column now holds numbers from 0 to 8 instead of readable strings. Someone scanning the table cannot tell from the numbers alone whether the variable should be treated as continuous or categorical. The digits look like the same kind of thing as an age or an income, even though they describe a choice among options.

What resolves the ambiguity is knowing what the numbers mean. Once you know that the codes indicate employment status, it becomes clear that these are distinct states that should not be modeled by a single continuous variable. The integer type is a fact about storage. The category is a fact about meaning, and only the meaning should guide how the feature is modeled.

When a Binned Feature Becomes Categorical

Imagine a single continuous measurement, such as a number that can take any value along a range. Sometimes it helps a model to chop that range into intervals, called bins, and then record only which bin each data point falls into. The result is no longer a measurement. It is a label: data point A is in bin 3, data point B is in bin 7, and so on. That label is a categorical feature.

Definition

A categorical feature is a feature whose values are labels naming a state or group, rather than amounts. A binned continuous feature becomes a categorical feature, and one-hot encoding converts that categorical feature into numbers a scikit-learn model can use.

Checking Order in a New Column

The central question for any integer feature is whether the encoded values have an ordering. Ordering means that moving from one code to another corresponds to a real, meaningful step along some scale. When no such ordering exists between the encoded semantics, the feature must be treated as discrete, and in practice it is typically one-hot encoded so that each state gets its own indicator.

Work through the checks in order. First ask whether the integers are real amounts, such as counts or measurements, where a difference of 2 means the same kind of gap anywhere on the scale. If they are, the column is a quantity and can usually stay as a single numeric column. If they are not, ask whether the codes name options that lie along a meaningful scale. If they do, the column is an ordered category. If the codes name options with no scale between them, the column is an unordered category and should be treated as discrete. The workclass example falls into the last group, since its codes name employment statuses that do not lie along any scale.

New integer columnDo the values measurean amount?Quantity: keep as anumeric columnOrdered category:encoding depends ontask and algorithmDo the codes liealong a meaningfulscale?Unordered category:treat as discrete andone-hot encodeinspect meaningyesnoyesno
Given a new integer column, which sequence of checks decides whether it is a quantity, an ordered category, or an unordered category?

Not every integer feature is clearly categorical. A five-star rating has a natural order: four stars is higher than two. That ordering means the feature is not simply a set of unrelated labels. Even so, the choice is not fixed. For a case like five-star ratings, the better encoding depends on the particular task and data, and on which machine learning algorithm is used. There is no single correct answer that applies everywhere. So an ordered integer column is a case where you must make a context-dependent decision rather than apply a rule mechanically.

Why Linear Models Need Numbers With Care

A categorical feature is still a problem for a scikit-learn model, because the model needs numbers to do arithmetic on. Writing bin 7 as the number 7 would quietly tell the model that bin 7 is seven times bin 1, which is not what the bins mean. A single integer column implies a numeric ordering and spacing: the gap between codes 1 and 2 looks the same as the gap between 2 and 3, and code 7 looks like seven times code 1. A linear model would use those implied distances, even though the categories have no such distances.

One-hot encoding is the standard way out. It replaces each label with a vector of zeros and ones, one position per category, so that no category is treated as bigger or smaller than another. Each category sits in its own column, and every pair of different categories is equally different from the model's point of view.

Single integercolumnCode 7 is seven timescode 1Each category in itsown columnGap 1 to 2 equals gap2 to 3One-hot columnsNo category is biggeror smallerimpliesimpliesimpliesimplies
What does a model assume about distances between values when the categories are stored as one integer column, compared with one-hot columns?

Tracing the Fit and Transform Steps

OneHotEncoder works in two phases. During fit, the encoder reads the feature and records which distinct values appear in it. It stores that list of categories and does not yet change any data. During transform, the encoder uses the stored list to build the matrix: for each data point, it places a 1 in the column belonging to that point's category and a 0 everywhere else. Keeping these two phases apart is the key to debugging the encoder.

python
Output (expected)
[[1. 0. 0.]
 [0. 0. 1.]
 [1. 0. 0.]
 [0. 1. 0.]]
Notes on the code
  • The feature is a single column of integer bin labels, as the encoder requires for integer categories.
  • The fit line learns the distinct categories, here 1, 2 and 3. It does not produce the matrix you print.
  • The transform line uses the stored categories to build one binary row per data point.
  • toarray converts the encoder output into a readable grid for printing.
Label 1column 0Row for label 11 0 0Label 2column 1Row for label 30 0 1Label 3column 2Row for label 20 1 01 placed in column 01 placed in column 21 placed in column 1
For each integer label seen during fit, which column position does it map to, and where does the single 1 appear in its transformed row?
Worked example

Tracing one feature through fit and transform

A feature called which_bin holds the labels 1, 3, 1, 2 for four data points. Trace what fit records and what transform outputs.

  1. 1
    Read the distinct values

    The labels contain 1, 3, 1, 2. The distinct values are 1, 2 and 3, so the stored category list has three entries.

  2. 2
    Fit stores the categories

    fit records the list 1, 2, 3 and does not change the data. No matrix exists yet.

  3. 3
    Assign a column to each category

    Using the stored list, category 1 takes column 0, category 2 takes column 1, and category 3 takes column 2.

  4. 4
    Build row for label 1

    The first data point has label 1, so its row has a 1 in column 0 and 0 elsewhere: 1 0 0.

  5. 5
    Build row for label 3

    The second data point has label 3, so its row has a 1 in column 2 and 0 elsewhere: 0 0 1.

  6. 6
    Build rows for the rest

    The third row repeats label 1, giving 1 0 0. The fourth row has label 2, giving 0 1 0.

Result

A four-row matrix with three columns: [1,0,0], [0,0,1], [1,0,0], [0,1,0]. Each row has exactly one 1, and its position identifies the category.

Predicting the Output Width

The number of output columns equals the number of unique categories. This is why a feature with 10 specified bins produces 10 features. Before you look at the printed matrix, you can work out its width from the labels alone: count the distinct values, and that count is the number of columns.

Formula

In this expression, k is the number of output columns and C is the set of unique categories recorded during fit. Here the symbol for set size means the count of distinct labels.

What do you think happens?

The labels 1, 3, 1, 2 are passed to OneHotEncoder. How many columns does the output matrix have?

  • 2

  • 3

  • 4

Reveal answer
Answer:

3

There are three distinct labels, 1, 2 and 3, so there are three output columns. The four data points give four rows, but repeated labels do not add columns.

Raw labels1 3 1 2fit records distinctvalues1, 2, 3Stored category list3 entriestransform: one columnper stored category3 columnsIs this label in thestored list?Place 1 in its columnNo stored column tohold a 1fitstoretransformeach rowyesno
Starting from the unique category count, what steps produce the output width, and at which step could an extra or missing column first appear?

Mistakes Beginners Make With Integer Labels

  • Common mistake

    Treating an integer column as continuous because its values are integers

    What it looks like

    A column of workclass codes 0 to 8 is averaged and fed to a linear model as if code 6 were six times code 1.

    Why it fails

    The storage type reveals nothing reliable about whether a feature is a quantity. The codes name options, so the implied distances and ratios have no meaning.

    Do this instead

    Decide from the meaning of the codes. If there is no ordering between the encoded semantics, treat the feature as discrete and one-hot encode it.

  • Common mistake

    Assuming every ordered integer column must be one-hot encoded, or that it must never be

    What it looks like

    A five-star rating is one-hot encoded automatically, or is kept as a single column without thought.

    Why it fails

    Ordered integer features do not have a single correct encoding. The choice depends on the task, the data, and the algorithm.

    Do this instead

    Make the encoding decision for the specific task and algorithm, and state the reason for the choice.

  • Common mistake

    Confusing fit with transform

    What it looks like

    Expecting the fit call to return the binary matrix and then wondering why the matrix is missing.

    Why it fails

    fit only records the distinct categories. The matrix is built by transform, which uses the stored list.

    Do this instead

    Check the stored categories after fit, then check the matrix produced by transform.

  • Common mistake

    Passing labels the encoder does not accept

    What it looks like

    Feeding a column of text strings directly to OneHotEncoder when the labels are not integers.

    Why it fails

    OneHotEncoder currently only accepts categorical variables that are integers, so the input does not meet the requirement.

    Do this instead

    Check the input type first when the output is wrong, and convert labels to integers before encoding.

  • Common mistake

    Reading the output width as the number of rows rather than the number of unique categories

Practice Predicting and Classifying

MEDIUM

A feature holds the codes 2, 4, 2, 9, 4, 7 for six survey respondents, where each code names one of four different survey answers. Predict the number of one-hot output columns, then state whether the feature should be treated as continuous or discrete, and justify your answer from the meaning of the codes.

Hints
  • Count the distinct codes first. The output width is the number of unique categories, not the number of rows.
  • Ask whether the codes name amounts or options. Do not decide from the fact that they are integers.
  • Here the survey answers are named options. If no scale lies between them, the feature is discrete.
EASY

Write one sentence explaining why the integer 7 in a categorical column does not mean the same thing as the integer 7 in an age column, then name the step in the encoder where that difference is handled.

Hints
  • Think about what each number stands for, not how it is stored.
  • The step that handles the categorical meaning is the one that replaces labels with binary vectors.

Key Takeaways

  • An integer column can represent categories. The storage type is a fact about storage, while the category is a fact about meaning, and only the meaning should guide modeling.
  • If the encoded values have no ordering, treat the feature as discrete and one-hot encode it. An ordered category such as a five-star rating may need a context-dependent encoding choice.
  • A single integer column implies numeric spacing that a linear model would wrongly use. One-hot encoding gives each category its own column, so no category is treated as bigger or smaller than another.
  • OneHotEncoder's fit step records the distinct categories and does not change the data. The transform step places a 1 in the column of each row's category, so the output width equals the number of unique categories.
  • When the matrix looks wrong, check the stored categories after fit first, then the matrix produced by transform, and confirm the labels are integers.

Related concepts

More concepts starting with O