Sub topic 10
Redundant columns and the drop option
This chapter assumes you can run OneHotEncoder and pd.get_dummies, and that you know what a feature matrix is. It also assumes a basic idea of linear regression with an intercept. The chapter covers why a full set of indicator columns carries one column too many, when that matters, and how the drop option removes it.
Why one-hot columns are redundant
A full one-hot encoding gives every row exactly one 1 across the indicator columns of a feature. For a size feature with the categories large, medium and small, every row satisfies this identity:
size_large + size_medium + size_small = 1If you know any two columns, you can compute the third. The third column adds no information. Statisticians call this perfect multicollinearity, and the textbook name for the resulting problem is the dummy variable trap.
The trap appears when the model also has an intercept. The intercept is a column of ones in the design matrix, and the sum of the indicator columns equals that same column of ones. One column is therefore an exact linear combination of the others.
You can confirm this with matrix rank. The rank is the number of linearly independent columns.
import numpy as np
# Columns: size_large, size_medium, size_small
# Rows: small, medium, large, medium
full = np.array([
[0, 0, 1],
[0, 1, 0],
[1, 0, 0],
[0, 1, 0],
])
intercept = np.ones((4, 1))
with_all = np.hstack([intercept, full])
with_two = np.hstack([intercept, full[:, 1:]])
print(with_all.shape[1], np.linalg.matrix_rank(with_all))
print(with_two.shape[1], np.linalg.matrix_rank(with_two))The first line prints 4 3: four columns but only three independent ones. The second prints 3 3, so every column is independent once one indicator is removed.
What goes wrong, and for which models
When columns are perfectly redundant, ordinary least squares has no unique solution. Infinitely many coefficient vectors produce identical predictions. In practice the symptoms depend on the library:
- Statistics packages such as
statsmodelsmay warn about a singular matrix or report enormous standard errors. - scikit-learn's
LinearRegressiondoes not fail. It uses a least-squares solver that returns the minimum-norm solution. Predictions are fine, but individual coefficients are arbitrary and hard to interpret. - Anything that inverts the matrix, such as a hand-written normal-equations solver, can fail or return numerical garbage.
Other models are affected much less:
| Model type | Needs `drop`? | Reason |
|---|---|---|
| Unregularized linear or generalized linear model | Usually yes | The design matrix is rank deficient. Coefficients are not unique. |
| Ridge, Lasso, elastic net, default `LogisticRegression` | No | The penalty makes the solution unique. Dropping changes which category the penalty treats as the baseline. |
| Decision trees, random forests, gradient boosting | No | Trees split on single columns, so redundancy does no harm. |
| Neural networks, k-nearest neighbors | No | There is no matrix inversion. For k-nearest neighbors, dropping slightly changes distances. |
A regularized model works with or without drop, but the two choices are not identical. With a full encoding, a ridge penalty shares weight among all categories. With a dropped column, the penalty shrinks each remaining category toward the baseline you dropped. Choose the baseline deliberately in that case.
The drop option in OneHotEncoder
OneHotEncoder accepts a drop parameter. The common values are:
None(the default) keeps every column."first"drops the first category of every feature."if_binary"drops one column only for features with exactly two categories.- An array-like names the category to drop for each feature.
"First" means first in the encoder's sorted category order, which is alphabetical for strings. It does not mean the first value in your data.
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
df = pd.DataFrame({"size": ["small", "medium", "large", "medium"]})
enc = OneHotEncoder(drop="first", sparse_output=False)
print(enc.fit_transform(df))
print(enc.get_feature_names_out())The sorted categories are large, medium, small, so large is dropped. The output is:
[[0. 1.]
[1. 0.]
[0. 0.]
[1. 0.]]
['size_medium' 'size_small']The third row, large, is the all-zero row. You can see which category was dropped in the fitted encoder's drop_idx_ attribute, which stores the index of the dropped category for each feature.
Choosing the baseline yourself
The alphabetical default rarely gives the most meaningful baseline. In a linear model, each remaining coefficient measures the difference from the dropped category. A baseline such as "most common category" or "standard plan" makes the coefficients easier to read. Pass the category to drop for each feature:
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
df = pd.DataFrame({"size": ["small", "medium", "large", "medium"]})
enc = OneHotEncoder(drop=["medium"], sparse_output=False)
print(enc.fit_transform(df))
print(enc.get_feature_names_out())The list has one entry per feature. This encoder has a single feature, so it has one entry. The columns are now size_large and size_small, and medium is the baseline.
Dropping only binary columns
A binary feature such as smoker with values yes and no needs only one column. Multi-category features are often better left in full, especially with regularized models. drop="if_binary" handles both cases in one step:
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
df = pd.DataFrame({
"smoker": ["yes", "no", "no", "yes"],
"city": ["Paris", "Berlin", "Rome", "Paris"],
})
enc = OneHotEncoder(drop="if_binary", sparse_output=False)
enc.fit(df)
print(enc.get_feature_names_out())The output is ['smoker_yes' 'city_Berlin' 'city_Paris' 'city_Rome']. The binary feature keeps one column, and the three-category feature keeps all three.
The pandas equivalent
pd.get_dummies has drop_first=True, which drops the first category of each encoded column:
import pandas as pd
df = pd.DataFrame({"size": ["small", "medium", "large", "medium"]})
print(pd.get_dummies(df, columns=["size"], drop_first=True, dtype=int))This produces size_medium and size_small. It has no per-feature baseline option and no if_binary mode. As in earlier chapters, get_dummies also learns its categories from whatever frame you give it. Do not use it on test data separately from training data when you need consistent columns.
Seeing that predictions do not change
For an unregularized linear model, the full and dropped encodings give the same predictions. Only the coefficients differ.
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import OneHotEncoder
X = pd.DataFrame({"size": ["small", "medium", "large", "medium"]})
y = np.array([1.0, 5.0, 9.0, 7.0])
full = OneHotEncoder(sparse_output=False).fit_transform(X)
dropped = OneHotEncoder(drop="first", sparse_output=False).fit_transform(X)
m_full = LinearRegression().fit(full, y)
m_drop = LinearRegression().fit(dropped, y)
print(np.allclose(m_full.predict(full), m_drop.predict(dropped)))
print(round(m_drop.intercept_, 2), np.round(m_drop.coef_, 2))The first line prints True. The second prints the intercept 9.0, which is the mean of the dropped large group, and the coefficients [-3. -8.]. These are the differences of medium and small from large. The full encoding fits equally well, but its intercept and coefficients are one arbitrary choice among many, so they cannot be read this way.
Interaction with unknown categories
drop combines awkwardly with handle_unknown="ignore". An unknown category at prediction time is encoded as all zeros. After dropping a column, all zeros is also how the dropped category looks. The model then treats unknown values as if they were the baseline.
That may be acceptable if the baseline is the most common category. It can be misleading otherwise, because no column distinguishes "baseline" from "never seen". Without drop, an unknown row is all zeros while every known row has exactly one 1, so the difference stays visible. Consider this trade-off when you choose both options together.
Deciding whether to drop
Some practical rules:
- For trees and boosting, leave
drop=None. It is the simplest setting, and the extra column does not hurt. - For unregularized linear models, drop one column per feature, and name the baseline when you will read the coefficients.
- For regularized linear models, either works. Use
"if_binary"as a compromise that removes the pointless second column of binary features. - Keep the setting identical between training and prediction. Put it inside the encoder in a pipeline so that it is.
Common mistakes
- Dropping one column across all features by hand. Remove one column per original feature, not one overall. Use the
dropoption, which does this for you. - Dropping after splitting. Choose the baseline from the training data. Let the encoder do it during
fit, not a manualdf.dropon each split. - Forgetting the baseline when interpreting. A coefficient of
-3forsize_mediummeans "3 lower than the dropped category", not "3 lower than average". - Expecting
dropto fix other multicollinearity. It removes only the redundancy among one feature's indicators. Correlation between different features is a separate issue.
Exercise
You fit an unregularized linear regression on a one-hot encoded plan column with the categories basic, premium and standard. The data has an intercept. How many indicator columns does drop="first" leave, and which category becomes the baseline? Which drop value would make "standard" the baseline instead?
Show answer
It leaves two columns, plan_premium and plan_standard, because the categories sort alphabetically and basic is first, so basic becomes the baseline. To make standard the baseline, pass drop=["standard"], which leaves plan_basic and plan_premium.
Exercise
A colleague trains a random forest on a full one-hot encoding with drop=None and asks whether the redundant columns will make the model unstable. What do you tell them, and what would change if they switched to unregularized linear regression?
Show answer
The forest is unaffected, because trees split on one column at a time and do not invert a matrix, so the redundancy causes no instability. With unregularized linear regression and an intercept, the design matrix would be rank deficient, so they should drop one indicator per feature, for example with drop="first" or a chosen baseline.