Sub topic 4
How one-hot encoding works
This chapter explains the representation itself: what a one-hot vector is, why it fits many models, and what it costs. It assumes you know basic Python, NumPy arrays and the idea of a feature matrix. Library details such as get_dummies and OneHotEncoder come in later chapters. Here we build the encoding by hand so you can see exactly what those tools produce.
The core idea
A categorical feature takes values from a fixed set of labels, such as red, green and blue. One-hot encoding replaces that single column with one binary column per label. In each row, exactly one of those columns holds 1 (the column for that row's label). All the others hold 0.
Take the colors red, green, blue, green. The distinct labels, in alphabetical order, are blue, green, red. The encoding is:
| original | blue | green | red |
|---|---|---|---|
| red | 0 | 0 | 1 |
| green | 0 | 1 | 0 |
| blue | 1 | 0 | 0 |
| green | 0 | 1 | 0 |
The name comes from digital electronics. Of a group of wires, one is "hot" (on) and the rest are off. Each row of the table is a one-hot vector. Each new column is an indicator (or dummy) variable that answers one yes/no question: "is this row's color blue?"
Building it by hand
The encoding takes three steps:
- Collect the distinct labels and fix their order. This list is the vocabulary.
- Map each label to its position in the vocabulary.
- Turn each position into a vector of zeros with a 1 at that position.
NumPy's identity matrix does step 3 directly. Row i of np.eye(k) is the one-hot vector for position i, so indexing the matrix with an array of positions builds the whole encoding at once.
import numpy as np
colors = ["red", "green", "blue", "green"]
categories = sorted(set(colors))
index = {label: i for i, label in enumerate(categories)}
codes = np.array([index[label] for label in colors])
one_hot = np.eye(len(categories), dtype=int)[codes]
print(categories)
print(codes)
print(one_hot)The output is:
['blue', 'green', 'red']
[2 1 0 1]
[[0 0 1]
[0 1 0]
[1 0 0]
[0 1 0]]The codes array is the integer coding from the previous chapter. One-hot encoding is a second step on top of it. It turns each arbitrary integer into a vector that carries no order.
Why the representation works
Each category gets its own weight
Many models, including linear and logistic regression and neural networks, compute a weighted sum of the input columns. With one-hot columns, that sum has a useful property. Because only one column is 1, the dot product with the weight vector picks out exactly one weight.
import numpy as np
one_hot = np.array([
[0, 0, 1],
[0, 1, 0],
[1, 0, 0],
[0, 1, 0],
])
weights = np.array([1.0, 3.0, 5.0])
intercept = 10.0
print(intercept + one_hot @ weights)This prints [15. 13. 11. 13.]. The weight for blue is 1, for green is 3 and for red is 5. A linear model can learn any value for each color independently. It is not forced to place the colors on a line.
Compare that with feeding the integer codes (blue = 0, green = 1, red = 2) to the same kind of model. The model has one weight w for the column, so its contribution is 0, w and 2w. The model must treat green as exactly halfway between blue and red. If the true effect of green is higher than both, no choice of w can express that.
Every pair of categories is equally far apart
In one-hot space, any two different categories differ in exactly two positions. Their Euclidean distance is always the square root of 2, and no pair is closer than another.
import numpy as np
blue, green, red = np.eye(3)
print(round(float(np.linalg.norm(blue - green)), 3))
print(round(float(np.linalg.norm(blue - red)), 3))
print(round(float(np.linalg.norm(green - red)), 3))All three lines print 1.414. With integer codes, blue and red would be 2 apart while blue and green would be 1 apart. This claims a similarity that the data may not support. Distance-based models such as k-nearest neighbors and models that use a kernel see this directly. One-hot encoding says "these labels are all different, and none is more different than another."
Trees see each category as a yes/no question
A decision tree splits on one column at a time. With a one-hot column, a split such as color_red <= 0.5 asks "is this row red or not?" That works, but it isolates one category per split. A tree that wants to group red and blue against green needs several splits. Some tree libraries handle categories natively and avoid this cost. The final chapter of this tutorial returns to that point.
Shape, cost and sparsity
A column with k distinct values becomes k columns. For a whole dataset, the width of the encoded feature matrix grows by the sum of the cardinalities of the categorical columns.
| Feature | Distinct values | Columns after encoding |
|---|---|---|
| weekday | 7 | 7 |
| country | 195 | 195 |
| ZIP code | about 40,000 | about 40,000 |
Each row still has only one 1 per original column, so almost every entry is zero. A matrix with this property is sparse. Libraries can store only the nonzero entries, which saves memory. A dense matrix of 1,000,000 rows and 40,000 columns of 8-byte numbers would need about 320 GB. A sparse version stores roughly one value per row for that feature.
The width problem also affects training. More columns mean more weights to learn, slower fitting and a higher risk of overfitting when many categories have few examples. Later chapters cover rare categories and high cardinality in detail.
Properties to keep in mind
The following facts hold for any correct one-hot encoding. They are also the source of the common bugs covered later.
- The vocabulary is part of the model. The columns exist because those labels appeared when the vocabulary was built. Prediction-time data must use the same vocabulary in the same order. If the column order changes, the weights attach to the wrong colors and the predictions silently become wrong.
- A new label has no column. If
purpleappears after the vocabulary is fixed, no column represents it. Either the encoder raises an error, or it produces a row of all zeros. A row of all zeros is the only case where the "exactly one 1" rule breaks. - A missing value is not a category unless you make it one.
NaNhas no position in the vocabulary. You must choose to encode it as its own column or to fill it in beforehand. - The columns sum to 1. For each original feature, the indicator columns add up to 1 in every row. Together with a model intercept, this makes one column redundant. Linear models without regularization can then be unstable, and the
dropoption exists to handle that. - Order information is lost. One-hot encoding deliberately discards any ordering. If your labels are
small,mediumandlarge, the encoded columns no longer say thatmediumsits between the others. A model can learn that pattern from data, but it must spend weights to do so.
When one-hot encoding fits
One-hot encoding is a good default when all of these hold:
- The feature is nominal, meaning its labels have no natural order.
- The number of distinct values is small to moderate, roughly tens rather than thousands.
- The model benefits from separate weights per category, as linear models, neural networks and k-nearest neighbors do.
It is a poor fit when a feature is ordinal and the order matters, when cardinality is very large, or when the model can already handle categories natively. The last chapter compares the alternatives.
A complete worked check
The following script puts the pieces together. It builds a vocabulary from a training list, encodes a test list with it, and shows both the normal case and the all-zeros case for an unseen label.
import numpy as np
train = ["red", "green", "blue", "green"]
test = ["green", "purple", "red"]
vocabulary = sorted(set(train))
position = {label: i for i, label in enumerate(vocabulary)}
def encode(labels):
matrix = np.zeros((len(labels), len(vocabulary)), dtype=int)
for row, label in enumerate(labels):
if label in position:
matrix[row, position[label]] = 1
return matrix
print(vocabulary)
print(encode(test))
print(encode(test).sum(axis=1))The output is:
['blue', 'green', 'red']
[[0 1 0]
[0 0 0]
[0 0 1]]
[1 0 1]The row sums show the invariant. Every known label gives a sum of 1. The unseen purple gives 0, so the encoding itself tells you the label was not in the vocabulary.
Exercise
A dataset has two categorical columns: city with 4 distinct values in the training data and plan with 3. It also has 2 numeric columns. After one-hot encoding both categorical columns, how many columns does the feature matrix have, and what is the sum of the indicator columns for city in any single training row?
Show answer
The matrix has 4 + 3 + 2 = 9 columns. The city indicator columns sum to 1 in every training row, because exactly one city column is 1 and the others are 0.
Exercise
A model uses the integer codes blue = 0, green = 1, red = 2 as one numeric feature in a linear model. The true average target is 10 for blue, 30 for green and 20 for red. Why can the model not fit these averages exactly, and how does one-hot encoding fix it?
Show answer
With one weight w and an intercept b, predictions are b, b + w and b + 2w, which lie on a straight line in the code. The targets 10, 30, 20 do not lie on a line, so no b and w fit them. One-hot encoding gives each color its own weight, so the model can set the prediction for each color independently and reproduce 10, 30 and 20 exactly.