الانتقال إلى المحتوى
Machine LearningFeature Engineering· 7 دقائق للقراءة

Encoding Categories as 1, 2, 3 Invents an Order That Isn't There

A model reads an integer code as a quantity. Give unordered categories one column each, or a model that understands categories.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • scikit-learn 1.9
محتويات المقال

A delivery app wants to predict how long an order takes. The data has a 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

Many developers map each category to an integer and move on. It looks reasonable for good reasons:

  • 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.codes or factorize. 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_id values, so the number feels like a label.

The half-truth: an integer is a perfectly good name for a category. The problem is that a model doesn't read it as a name. It reads a quantity.

What actually happens

To a model, every feature is a number on a scale, and the encoding decides what that scale says.

A code brings an order and a distance

With Alexandria = 0, Aswan = 1, Cairo = 2, Giza = 3 and Luxor = 4, the data now claims that Cairo sits between Aswan and Giza, that Luxor is twice Cairo, and that Alexandria is as far from Aswan as Giza is from Luxor. None of it is true; the order is just the alphabet. The scikit-learn user guide says it directly: estimators expect continuous input, so they would interpret integer-coded categories as ordered, which is often not what you want. Google's Machine Learning Crash Course makes the same point with colors: stored as index numbers, they're treated as floating-point values, and purple becomes six times orange.

One weight can't describe five cities

A linear model learns one weight per column. With a single 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.

Python
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 min

The slope comes out at +0.34 minutes per step: the model learned that cities later in the alphabet are slightly slower, which means nothing. Its cross-validated error, 9.7 minutes, is barely better than the 9.8 of DummyRegressor, the that always predicts the average. The information is in the data; the encoding hid it.

One-hot: one switch per category

gives each category its own column, set to 1 for that category and 0 for all the others. Five cities become five columns, and the linear model learns five independent weights with no order between them. The same 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

A decision tree splits on thresholds, so it can cut one city out of the codes with two splits. That's why integer codes often look fine with tree models. scikit-learn's gradient boosting example on the Ames housing data agrees that ordinal codes may work for low-cardinality features, but notes that meaningful splits need deeper trees as the number of categories grows. Its illustration: if the best way to split categories A to F is ACF against BDE, ordinal codes need 4 splits, one-hot needs 3, and native categorical handling needs 1.

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

One-hot has its own limit. The Crash Course calls it usually a bad choice when the number of categories is high, such as roughly 42,000 US postal codes, and suggests embeddings instead. In scikit-learn you can merge rare categories into one column with 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.

EncodingUse it forWatch out for
Integer codes (LabelEncoder, cat.codes)Nothing as model input; LabelEncoder is meant for targetsInvents an order and distances
OrdinalEncoder with explicit categoriesCategories with a real order: sizes, levels, ratingsThe default order is sorted, not meaningful
OneHotEncoderUnordered categories in linear, distance-based and neural modelsOne column per category
Native categorical supportGradient-boosted trees (HistGradientBoosting*)At most 255 categories per feature
TargetEncoderHigh-cardinality columns such as zip codesFit with fit_transform on training data only

How to apply it in your project

  1. Find the disguised categoriesLook for LabelEncoder, cat.codes or factorize applied 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.
  2. Decide if the order is realSizes and levels have one; cities, colors and payment methods don't. Real order: OrdinalEncoder with explicit categories. No order: treat it as unordered.
  3. Match the encoding to the modelOne-hot for linear models, k-nearest neighbors, SVMs and neural networks. Native categorical support for HistGradientBoosting models.
  4. Plan for rare and unseen valuesSet handle_unknown and min_frequency before deployment, and switch to TargetEncoder when the column has thousands of values.
  5. Measure against a baselineCross-validate the model with the old and new encoding, next to a DummyRegressor or DummyClassifier, 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.

📚 المصادر

  1. Categorical data: One-hot encoding — Google Machine Learning Crash Course
  2. Preprocessing data: Encoding categorical features — scikit-learn User Guide
  3. Categorical Feature Support in Gradient Boosting — scikit-learn examples
  4. OneHotEncoder — scikit-learn API Reference

التعليقات (0)