
Encoding Categories as 1, 2, 3 Invents an Order That Isn't There
- كاتب موثّق
- scikit-learn 1.9
محتويات المقال
city column, so someone maps each city to an integer, Alexandria = 0 through Luxor = 4, and fits a linear regression. The mean absolute error comes out at 9.7 minutes; a model that always predicts the average is off by 9.8. The team concludes that linear models are too weak for the job and reaches for something bigger. The model wasn't the problem. The column was.
The common misconception
Models need numbers, and one integer per category is the smallest encoding there is: one column in, one column out. It's one line of code: LabelEncoder, pandas'cat.codesorfactorize. Plenty of tutorials do exactly that.With tree-based models it often seems to work, and scikit-learn's own gradient boosting example says ordinal codes may work well for features with few categories. In application code an integer ID is harmless. Nobody adds two user_idvalues, so the number feels like a label.
What actually happens
A code brings an order and a distance
One weight can't describe five cities
city column, that weight is a slope: each step along the codes adds the same number of minutes. In the script below, the five cities average 30, 55, 25, 45 and 35 minutes, in alphabetical order. No straight line fits that zigzag.
import numpy as npimport pandas as pdfrom sklearn.dummy import DummyRegressorfrom sklearn.linear_model import LinearRegressionfrom sklearn.model_selection import cross_val_scorefrom sklearn.preprocessing import OrdinalEncoderrng = np.random.default_rng(0)avg = {"Alexandria": 30, "Aswan": 55, "Cairo": 25, "Giza": 45, "Luxor": 35}city = pd.DataFrame({"city": rng.choice(list(avg), size=1000)})minutes = city["city"].map(avg) + rng.normal(0, 5, size=1000)X = OrdinalEncoder().fit_transform(city) # Alexandria=0, Aswan=1 ... Luxor=4slope = LinearRegression().fit(X, minutes).coef_[0]print(f"{slope:+.2f} min per step along the alphabet") # +0.34for model in [LinearRegression(), DummyRegressor()]: # Dummy: always the mean mae = -cross_val_score(model, X, minutes, cv=5, scoring="neg_mean_absolute_error").mean() print(f"{type(model).__name__:<16} MAE {mae:.1f} min")# LinearRegression MAE 9.7 min# DummyRegressor MAE 9.8 minimport numpy as npimport pandas as pdfrom sklearn.ensemble import HistGradientBoostingRegressorfrom sklearn.linear_model import LinearRegressionfrom sklearn.model_selection import cross_val_scorefrom sklearn.pipeline import make_pipelinefrom sklearn.preprocessing import OneHotEncoderrng = np.random.default_rng(0)avg = {"Alexandria": 30, "Aswan": 55, "Cairo": 25, "Giza": 45, "Luxor": 35}city = pd.DataFrame({"city": rng.choice(list(avg), size=1000)})minutes = city["city"].map(avg) + rng.normal(0, 5, size=1000)one_hot = make_pipeline(OneHotEncoder(handle_unknown="ignore"), LinearRegression()) # one weight per citynative = HistGradientBoostingRegressor(categorical_features="from_dtype")for name, model, X in [("one-hot + linear", one_hot, city), ("native categories", native, city.astype("category"))]: mae = -cross_val_score(model, X, minutes, cv=5, scoring="neg_mean_absolute_error").mean() print(f"{name:<17} MAE {mae:.1f} min")# one-hot + linear MAE 3.9 min# native categories MAE 3.9 minDummyRegressor, the that always predicts the average. The information is in the data; the encoding hid it.
One-hot: one switch per category
LinearRegression drops to 3.9 minutes, close to the floor set by the random noise in the data. The model didn't change; changed what it can express.
Trees cope, at a cost
HistGradientBoostingRegressor has that native support. It treats pandas category columns as unordered groups, the default behavior since scikit-learn 1.6, and in the script it matches one-hot at 3.9 minutes with no encoder at all. Each such feature can have at most 255 categories.
Thousands of categories
min_frequency or max_categories, or use TargetEncoder, which the user guide recommends for high-cardinality features like zip codes. It replaces each category with a smoothed average of the target; call fit_transform on training data, which cross-fits so a row's own target doesn't leak into its encoding.
LabelEncoder, cat.codes) | LabelEncoder is meant for targets | |
OrdinalEncoder with explicit categories | ||
OneHotEncoder | ||
HistGradientBoosting*) | ||
TargetEncoder | fit_transform on training data only |
How to apply it in your project
Find the disguised categories Look for LabelEncoder,cat.codesorfactorizeapplied to features, and for IDs that were never encoded because they were already numbers: store IDs, zip codes, product codes. Ask whether "bigger" means anything.Decide if the order is real Sizes and levels have one; cities, colors and payment methods don't. Real order: OrdinalEncoderwith explicit categories. No order: treat it as unordered.Match the encoding to the model One-hot for linear models, k-nearest neighbors, SVMs and neural networks. Native categorical support for HistGradientBoostingmodels.Plan for rare and unseen values Set handle_unknownandmin_frequencybefore deployment, and switch toTargetEncoderwhen the column has thousands of values.Measure against a baseline Cross-validate the model with the old and new encoding, next to a DummyRegressororDummyClassifier, inside one pipeline.
Key takeaways
An integer code tells the model that categories are ordered and evenly spaced, even when the order is the alphabet. On codes, a linear model fits one slope across arbitrary categories: 9.7 minutes of error, against 9.8 for guessing the average and 3.9 with one-hot encoding. Trees tolerate codes but need extra splits; gradient boosting's native categorical support avoids them. Use integer codes only for categories with a real order, and pass that order explicitly.
التعليقات (0)