Concepts / Representing Categorical Variables

Representing Categorical Variables

Machine learning algorithms need categorical variables encoded as numbers, and one-hot encoding gives each category its own position so no false ordering is implied.

  • Programming

Why Models Need Numbers

A machine learning algorithm does not look at a spreadsheet the way a person does. It works with numbers arranged in a consistent layout, and the way those numbers are arranged can decide whether the algorithm learns anything useful at all. Many real datasets contain columns that hold categories rather than measurements: a color such as red, green, or blue, a city name, or a product type. Those columns cannot be fed to an algorithm as they are, because the algorithm's arithmetic needs numbers.

This article follows one idea. The data you feed a model must be represented in a form that suits the algorithm, and the features you choose must match the method you plan to use. The source makes a practical point that is easy to underestimate: the features that are used, and how well they match the chosen method, is often the most important factor in whether a machine learning approach works well. Before worrying about which algorithm is the most sophisticated, it helps to ask whether the inputs are shaped the right way.

Tracing One-Hot Encoding Step by Step

The standard way to convert a categorical column into numbers is one-hot encoding. The idea is to give each possible category its own position in a vector. For a given data point, the position that belongs to its category is set to 1, and every other position is set to 0. Only one position is hot at a time, which is where the name comes from.

Before any encoding can happen, you fix the order of the categories, because the position of each 1 depends on that order. Suppose a dataset has a color column with three possible categories, listed in the order red, green, blue. The vector for any value therefore has three positions: the first belongs to red, the second to green, and the third to blue. A red value puts its 1 in the first position, a green value in the second, and a blue value in the third.

red1green0blue0
For a red value, which vector position is set to 1, and how does that position map back to the category label?

The diagram above shows the vector for a red value. Each position is labeled with the category it belongs to, so reading the vector back is a lookup: the position holding the 1 names the category. The vector length equals the number of categories, so this encoding grows wider as the number of categories grows.

The encoding does not need any library. A small function can build the vector for any single value by comparing that value against each category in turn. The code below does exactly that, and then applies the same function to every row of a short column.

python
Output (expected)
red [1, 0, 0]
blue [0, 0, 1]
green [0, 1, 0]
red [1, 0, 0]
Notes on the code
  • The categories list fixes the order, so position 0 is red, position 1 is green, and position 2 is blue.
  • The loop compares the value with each category in turn and appends a 1 only for the match.
  • The two red rows produce identical vectors, because the same category always produces the same vector.

Read the output rows against the category order. The first and last rows are both red, and both carry a 1 in the first position, which is why they match. The single text column has been replaced by a block of numeric columns, and each row is now a vector the algorithm can use.

Why Integer Codes Mislead a Model

A tempting shortcut is to assign each category a single number: red becomes 0, green becomes 1, and blue becomes 2. This produces one column instead of three, but it introduces a problem. If you simply assign the numbers 0, 1, and 2 to red, green, and blue, the model could read those numbers as an ordering or as distances, even though the colors have no such order. A model that sees blue as 2 and red as 0 may treat blue as being twice as far from the start as green is.

red to green: 1integer codesred to green: equalone-hot vectorsred to blue: 2integer codesred to blue: equalone-hot vectors
How does the distance between category codes differ between integer labels and one-hot vectors, and what ordering does each one imply?

One-hot encoding avoids this. It keeps each category separate, so no category is numerically treated as lying between two others. In the one-hot vectors, every pair of different categories differs in exactly two positions, so no pair looks closer than another. The model is not told that green sits between red and blue.

Binning a Continuous Measurement

Feature engineering creates new features from existing data, and the chapter names three techniques: binning, adding polynomials, and adding interactions. Binning takes a continuous measurement and converts it into interval-based categories. Each interval becomes an indicator column that is 1 when the value falls inside it and 0 otherwise. The result is a set of bin indicators in place of one raw number.

age 27raw valueunder 18: 0bin indicator18 to 34: 1bin indicator35 to 54: 0bin indicator55 and over: 0bin indicator
How does a continuous value change from one raw number into a set of bin indicators, and where do the bin boundaries fall?
Worked example

Turning one age into a bin indicator

A dataset has a continuous age column. We want binned features using the illustrative boundaries 18, 35, and 55. Convert an age of 27 into bin indicator columns.

  1. 1
    Identify the bins

    The boundaries 18, 35, and 55 create four intervals: under 18, 18 to 34, 35 to 54, and 55 and over.

  2. 2
    Locate the value

    An age of 27 is greater than or equal to 18 and less than 35, so it falls in the 18 to 34 interval.

  3. 3
    Set the indicators

    The 18 to 34 indicator becomes 1, and the other three indicators become 0.

  4. 4
    Keep the original

    The raw age column of 27 is still available. The bin indicators are added alongside it, not in place of it.

Result

The age 27 is represented as the indicator vector [0, 1, 0, 0] across the four bins, with the original value of 27 kept as well.

The bin boundaries in this example were chosen only for illustration. In a real project they would come from knowledge of the problem, which is the kind of expert input the source describes. Choosing boundaries that have no real meaning for the problem gives the model intervals that carry no useful information.

Polynomial Terms and Interactions

A polynomial term is a new column built from one existing feature by raising it to a power, such as the square of $x_{1}$, written $x_{1}^{2}$. An interaction feature is a new column built by multiplying two existing features together, such as $x_{1} x_{2}$. Both techniques create columns that did not exist in the raw data, and both are derived entirely from columns that did.

x1original featurex1 squaredpolynomial termx2original featurex1 times x2interaction termsquaremultiplymultiply
Which original features are combined to produce each new feature column, and how do squared and product terms relate to the source features?

The diagram shows that the squared term draws only on x1, while the interaction term draws on both x1 and x2. The engineered columns are added alongside the originals, and the combined set is what the model receives. The originals are not discarded.

Matching Features to the Model

The chapter's central warning is that the right feature set depends on the model. Feature choices are not universal. A feature that rescues one kind of model may add nothing to another, which is why the match between the chosen features and the chosen method is often the most important factor in making a machine learning approach work well.

Model typeBenefit from binning, polynomial terms, and interactionsReason given in the source
Linear modelsLikely to benefit greatlyA straight-line model cannot bend a relationship on its own, so the generated features supply nonlinear structure.
Complex nonlinear models such as random forests and SVMsMay not need explicit expansionThe source says they might learn complex tasks without the feature space being expanded explicitly.

Matching feature engineering to model type, as described in the source

The practical rule that follows is to ask which model you plan to use before deciding how much feature engineering to do. A linear model is a good candidate for explicit binning, polynomial terms, and interactions. A more complex nonlinear model may already learn those patterns, so expanding the feature space by hand may add effort without adding benefit.

Mistakes Beginners Make with Encoding

Most errors in this topic come from treating the encoding as a simple relabeling. The following mistakes come up often when learners first convert categories into numbers.

  • Common mistake

    Assigning 0, 1, 2 to categories and assuming the model will treat them as unordered.

    What it looks like

    Encoding red as 0, green as 1, and blue as 2 in one column.

    Why it fails

    The model can read those numbers as an ordering or as distances, even though the colors have no such order.

    Do this instead

    Use one-hot encoding so that each category has its own position and no category lies numerically between two others.

  • Common mistake

    Changing the category order between encodings and comparing the vectors directly.

    Why it fails

    The position of each 1 depends on the order of the categories, so a different order produces different vectors for the same value.

    Do this instead

    Fix the category order once and reuse it for every row and every later encoding.

  • Common mistake

    Replacing the original features with the engineered ones.

    Why it fails

    The engineered features are added alongside the originals, and the combined set is what the model receives.

    Do this instead

    Keep the raw columns and append the new bin, polynomial, or interaction columns.

  • Common mistake

    Choosing bin boundaries arbitrarily instead of from knowledge of the problem.

  • Common mistake

    Adding polynomial and interaction features to every model without checking whether the model needs them.

Predicting an Encoded Vector

What do you think happens?

Using the category order red, green, blue, what vector does one_hot return for the value blue?

  • [1, 0, 0]

  • [0, 1, 0]

  • [0, 0, 1]

  • [0, 0, 2]

Reveal answer
Answer:

[0, 0, 1]

Blue is the third category in the fixed order, so only the third position is set to 1 and the other positions are 0. The integer 2 would be an ordering, which one-hot encoding avoids.

EASY

Extend the one_hot function to a fourth category, yellow, appended at the end of the category list. Predict the new length of every vector and the vector for a yellow value before running the code. Then check that the two red rows still produce identical vectors.

Hints
  • The vector length equals the number of categories, so adding yellow adds one position.
  • Append yellow to the end of the list so the existing positions do not move.

Key Takeaways

  • Machine learning algorithms need categorical variables encoded as numbers, because they compute with numeric arrangements of data.
  • One-hot encoding gives each category its own position in a vector, sets that position to 1 for a matching value and 0 elsewhere, and so implies no false ordering.
  • Binning, polynomial terms, and interactions create new features from existing data, and they are added alongside the original columns.
  • Linear models tend to benefit from engineered features, while complex nonlinear models such as random forests and SVMs may learn complex tasks without explicit expansion.
  • The match between the chosen features and the chosen method is often the most important factor in whether a machine learning approach works well.

Related concepts

More concepts starting with R