Sub topic 14
When Not to Use One-Hot Encoding
This chapter assumes you can fit a scikit-learn Pipeline, you know how OneHotEncoder and ColumnTransformer behave, and you have seen handle_unknown and min_frequency. The code uses scikit-learn 1.4 or newer.
One-hot encoding is a good default for nominal features with a modest number of categories. It is a poor fit in three situations: the categories have a meaningful order, the feature has thousands of distinct values, or the model can handle categories natively. This chapter helps you recognize each case and pick an alternative.
Where one-hot encoding breaks down
One-hot encoding creates one column per category. That causes problems in these situations:
| Situation | Problem with one-hot | Better option |
|---|---|---|
| Ordered categories such as "small < medium < large" | The order is discarded. The model must learn it from scratch. | Ordinal encoding with an explicit order |
| Thousands of categories such as user IDs or zip codes | Very wide matrices, slow training, overfitting on rare levels | Target encoding, hashing, frequency encoding |
| Gradient-boosted trees with many categories | Splits on single indicator columns are weak and the matrix is wide | Native categorical support |
| Streaming data with open-ended vocabularies | Categories seen later have no column | Hashing |
| Neural networks with huge vocabularies | A giant sparse input layer | Learned embeddings |
Dimensionality is the most common reason to look elsewhere. A column with 50,000 distinct values yields 50,000 binary columns. Sparse output keeps memory manageable, but linear models still get 50,000 weights to fit and most of them rest on very few rows.
Ordered categories: ordinal encoding
If a feature is ordinal, an integer code carries real information. The earlier warning about arbitrary integer codes applies to nominal data. For ordinal data the integers are appropriate, as long as the order is correct.
OrdinalEncoder sorts categories alphabetically by default. For "small", "medium" and "large" that gives large, medium, small, which is the wrong order. Always pass categories explicitly.
import pandas as pd
from sklearn.preprocessing import OrdinalEncoder
df = pd.DataFrame({"size": ["small", "large", "medium", "small"]})
enc = OrdinalEncoder(categories=[["small", "medium", "large"]])
print(enc.fit_transform(df))The output is 0.0 for small, 1.0 for medium and 2.0 for large. Each inner list in categories gives the order for one column.
Ordinal codes assume equal spacing. A linear model will treat the step from small to medium as equal to the step from medium to large. If that is false, either one-hot encode the feature anyway or use a tree-based model, which only needs the order and not the spacing.
For unseen values at prediction time, use handle_unknown="use_encoded_value" with an unknown_value such as -1 (or np.nan for models that accept missing values). The default raises an error.
Models that accept categories directly
Tree-based models split on thresholds. Integer codes for a nominal feature are therefore less harmful than they are for linear models, though arbitrary codes still force awkward splits. Scikit-learn's histogram-based gradient boosting goes further and handles categories natively. It considers partitions of categories into two groups at each split, so you do not need to widen the matrix.
import pandas as pd
from sklearn.ensemble import HistGradientBoostingClassifier
X = pd.DataFrame({
"city": pd.Categorical(["Paris", "Berlin", "Paris", "Rome", "Berlin", "Rome"] * 5),
"age": [25, 32, 47, 51, 38, 29] * 5,
})
y = [0, 1, 0, 1, 1, 0] * 5
clf = HistGradientBoostingClassifier(
categorical_features="from_dtype",
min_samples_leaf=2,
max_iter=20,
)
clf.fit(X, y)
print(clf.predict(X.head(6)))With categorical_features="from_dtype", any column with pandas category dtype is treated as categorical. Native handling has limits. Each categorical feature is limited by max_bins (255 by default), so a feature with more categories than that cannot be handled this way. Libraries such as LightGBM and CatBoost have their own native handling, with different details.
Random forests and plain decision trees in scikit-learn do not treat integer codes as categories. They still treat them as ordered numbers.
High cardinality: three compact encodings
When a feature has thousands of levels and the model is not natively categorical, you need an encoding that produces one column (or a handful) per feature.
Target encoding
Target encoding replaces each category with a statistic of the target for that category, usually the mean. Scikit-learn provides TargetEncoder.
import pandas as pd
from sklearn.preprocessing import TargetEncoder
X = pd.DataFrame({"city": ["Paris", "Berlin", "Paris", "Rome", "Berlin", "Rome", "Paris", "Berlin"]})
y = [1, 0, 1, 0, 0, 1, 1, 0]
enc = TargetEncoder(smooth="auto", target_type="binary", cv=2, random_state=0)
print(enc.fit_transform(X, y))
print(enc.transform(pd.DataFrame({"city": ["Paris", "Madrid"]})))Two details matter here:
fit_transformis not the same asfitfollowed bytransform. Duringfit_transform, the encoder uses cross-fitting. Each row is encoded with statistics computed on the other folds, so a row's own label does not leak into its feature. A separatefit(X, y).transform(X)encodes training rows with their own labels, which makes the feature look better than it will on new data. Inside aPipeline, scikit-learn callsfit_transformfor you.smoothshrinks the mean of rare categories toward the global mean. Without it, a category seen once would be encoded as exactly 0 or 1. Unseen categories such as "Madrid" are encoded with the global target mean.
Hashing
FeatureHasher maps each category string to one of a fixed number of columns using a hash function. It needs no fitting, no vocabulary and no memory of past categories.
from sklearn.feature_extraction import FeatureHasher
hasher = FeatureHasher(n_features=8, input_type="string", alternate_sign=False)
X = hasher.transform([["user=u1001"], ["user=u2002"], ["user=u1001"]])
print(X.toarray())The cost is collisions. Two different categories can land in the same column, and you cannot recover which category a column represents. Choose n_features as a power of two, large enough that collisions are rare for your data. Prefix each value with the feature name, as in user=u1001, so values from different features do not collide by construction.
Frequency or count encoding
Replace each category with how often it appears in the training data. This needs no target, so there is no label leakage. It works only if frequency is related to the outcome, and two categories with the same count become indistinguishable. In pandas, compute df["city"].map(df["city"].value_counts()) on the training data and reuse that mapping for test data.
Choosing an encoding
"Few" has no fixed threshold. As a rough guide, one-hot encoding is comfortable up to tens of levels, and above a few hundred you should have a reason for keeping it. Try min_frequency or max_categories first, since grouping rare levels may be enough.
Common errors
- Ordinal encoding a nominal feature for a linear model. The model reads city codes 0, 1, 2 as a quantity. Use one-hot or target encoding instead.
- Forgetting
categoriesinOrdinalEncoder. The order becomes alphabetical. - Fitting
TargetEncoderoutside the pipeline. Cross-validation scores become optimistic because validation labels influenced the encoding. - Using
fitthentransformon training data withTargetEncoder. This skips cross-fitting and leaks the training labels. - Too few hash columns. Collisions degrade accuracy without any warning.
- Assuming native categorical support in every tree model. Scikit-learn's
RandomForestClassifierdoes not have it in the wayHistGradientBoostingClassifierdoes. Check the documentation for your version. - Comparing encodings on a single split. Differences between encodings are often small. Compare with cross-validation.
Exercises
Exercise
A column "education" has the values "high school", "bachelor", "master" and "doctorate". You apply OrdinalEncoder() with no arguments. What codes does "master" and "bachelor" receive, and why is this a problem?
Show answer
The default order is alphabetical: bachelor=0, doctorate=1, high school=2, master=3. So "master" gets 3 and "bachelor" gets 0, and "doctorate" sits between them. The real order is high school < bachelor < master < doctorate. Pass categories=[["high school", "bachelor", "master", "doctorate"]] so the codes follow the true order.
Exercise
You build a model with TargetEncoder().fit(X_train, y_train) and then call transform(X_train) to get training features. Why will the training features be misleading, and what should you do instead?
Show answer
transform encodes each training row using statistics that include that row's own label, so the feature looks more predictive than it will on new data. Use fit_transform(X_train, y_train), which applies cross-fitting, or put the encoder in a Pipeline so that scikit-learn calls fit_transform on the training data. Then use transform only on validation and test data.
Exercise
A feature has 200,000 distinct customer IDs, and you are training a logistic regression. Name one encoding that keeps the number of columns fixed and state one drawback of it.
Show answer
Hashing with FeatureHasher (for example n_features=1024) keeps the column count fixed and needs no vocabulary. The drawback is collisions: different customers can share a column, and you cannot map a column back to a specific customer. Target encoding is another valid answer, with the drawback that it can leak labels if it is not fitted inside a cross-validated pipeline.