Sub topic 3
The problem with arbitrary integer codes
This chapter assumes you can work with pandas DataFrames and NumPy arrays, and that you know what a feature matrix and a train/test split are. It also assumes you have met the idea that a model needs numeric input and that categorical columns hold labels such as city names or colors. Here you will see why the most obvious fix, replacing each label with an integer, often produces a worse model. You will also see the bugs it can hide.
The tempting shortcut
A model cannot multiply a weight by the string "Paris", so the quickest conversion is to number the categories. Pandas and scikit-learn both offer this. pd.factorize and Series.cat.codes do it in pandas, and OrdinalEncoder does it in scikit-learn. The result is a single numeric column that looks like any other feature.
import pandas as pd
df = pd.DataFrame({
"city": ["Berlin", "Berlin", "Paris", "Paris", "Rome", "Rome"],
"price": [10, 10, 30, 30, 10, 10],
})
codes, uniques = pd.factorize(df["city"], sort=True)
df["city_code"] = codes
print(list(uniques))
print(df["city_code"].tolist())The output is ['Berlin', 'Paris', 'Rome'] followed by [0, 0, 1, 1, 2, 2]. The column now has numbers in it, and nothing has failed. The trouble is in what those numbers say.
What an integer code claims
A number carries more information than a label. When a model reads city_code, it can use three properties of integers that your categories do not have.
- Order. Rome (2) is "greater than" Paris (1), which is "greater than" Berlin (0).
- Distance. The gap between Berlin and Paris is 1. The gap between Berlin and Rome is 2. Rome is treated as twice as far from Berlin as Paris is.
- Arithmetic. The average of Berlin and Rome is (0 + 2) / 2 = 1, which is Paris.
None of this is true of cities. The codes were assigned alphabetically, so the order reflects spelling and not anything about the data. If you had sorted by country or by first appearance, you would get different numbers and a different model, from the same information.
The ordering of codes is arbitrary, and a model fitted to them is not. Any change to the code assignment is a change to the features.
A concrete failure with a linear model
A linear model fits one slope per feature. With a single city_code column it can only draw a straight line through the codes. It can say "higher code, higher price" or "higher code, lower price". It cannot say "Paris is expensive, and both Berlin and Rome are cheap."
In the data above, Paris prices are 30 and the other two cities are 10. That pattern rises and then falls, so no straight line fits it.
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import OneHotEncoder
df = pd.DataFrame({
"city": ["Berlin", "Berlin", "Paris", "Paris", "Rome", "Rome"],
"price": [10, 10, 30, 30, 10, 10],
})
df["city_code"] = pd.factorize(df["city"], sort=True)[0]
coded = LinearRegression().fit(df[["city_code"]], df["price"])
print(np.round(coded.predict(df[["city_code"]]), 2))
enc = OneHotEncoder(sparse_output=False)
X_onehot = enc.fit_transform(df[["city"]])
onehot = LinearRegression().fit(X_onehot, df["price"])
print(np.round(onehot.predict(X_onehot), 2))The first line prints [16.67 16.67 16.67 16.67 16.67 16.67]. The slope on city_code comes out as zero, because the rising half and the falling half cancel. The model learned nothing about cities and predicts the overall mean for every row.
The second line prints [10. 10. 30. 30. 10. 10.]. Giving each city its own column lets the model assign each city its own level. The next chapter explains how that representation works. For now, notice that the same model class, on the same rows, goes from useless to exact only because the encoding changed.
This failure does not need extreme data. Any time the true effect of a category is not monotonic in your arbitrary order, a linear or logistic model cannot represent it. With more than a few categories, an arbitrary order is almost never monotonic.
Which models are affected
The damage depends on how the model uses the feature.
| Model family | How integer codes hurt | Severity |
|---|---|---|
| Linear and logistic regression | One slope forces a straight-line effect across the arbitrary order | High |
| k-nearest neighbors, SVM with RBF kernel | Distances between codes are used directly, so "Berlin is closer to Paris than to Rome" is baked in | High |
| Neural networks | The input is scaled and combined linearly in the first layer, so the false order is the starting point | High |
| Decision trees, random forests, gradient boosting | Splits like `code <= 0.5` can isolate a category, but separating one in the middle of the order needs two splits | Moderate |
Trees are the partial exception. A tree can isolate Paris with the splits code <= 0.5 and code <= 1.5. This works, but it spends depth, and the trees must discover the grouping through a search that the arbitrary order makes harder. With dozens of categories, the number of splits needed grows and the model can overfit. Some libraries handle categories natively, so check what your library does before assuming you must encode. Plain integer codes passed to a library that is unaware they are categories are still just numbers.
Codes that disagree between datasets
Order and distance are not the only problem. Integer coding done carelessly can also give different numbers to the same label in different places. Suppose you factorize the training and test sets separately.
import pandas as pd
train = pd.Series(["red", "green", "blue", "green"])
test = pd.Series(["green", "red"])
train_codes, train_labels = pd.factorize(train)
test_codes, test_labels = pd.factorize(test)
print(dict(zip(train_labels, range(len(train_labels)))))
print(dict(zip(test_labels, range(len(test_labels)))))This prints {'red': 0, 'green': 1, 'blue': 2} and then {'green': 0, 'red': 1}. By default factorize numbers labels in order of first appearance. So "green" is 1 in training and 0 at test time. A model trained on one mapping and scored with the other gets wrong inputs, and no error is raised. The predictions are just worse, and the cause is hard to spot.
The fix is to learn the mapping once, on the training data, and reuse it. That is the "fit on training data" discipline covered later in this tutorial. For now, remember that a separate encoding call per dataset breaks consistency.
Missing values become a real number
Integer coders usually have to put missing values somewhere. In pandas, both pd.factorize and Series.cat.codes return -1 for NaN.
import numpy as np
import pandas as pd
s = pd.Series(["a", "b", np.nan, "a"])
codes, uniques = pd.factorize(s)
print(codes.tolist())The output is [0, 1, -1, 0]. The missing row now holds -1, a value lower than every real category. A linear model treats "missing" as "slightly below category a", which is meaningless. If you keep integer codes, handle missing values explicitly before encoding, for example by turning them into their own category. Missing values are covered in their own chapter.
When integer codes are acceptable
Integer coding is not always wrong. It is correct when the categories really are ordered, and when treating the steps as equal is a reasonable approximation. Examples are "low" < "medium" < "high", shirt sizes, or survey scales from "strongly disagree" to "strongly agree". The chapter on nominal and ordinal categories covers this distinction.
Even then, you must choose the order yourself, so that "low" gets the smallest number. Alphabetical order would put "high" before "low" and break the meaning. You are also asserting that the gap from low to medium equals the gap from medium to high. If that is doubtful, one-hot encoding is the safer default, at the price of more columns.
A quick decision guide
- Do the categories have a meaningful order (low, medium, high)? If not, do not use integer codes with linear, distance-based or neural models.
- If they do, are the spacings between levels roughly comparable? If yes, integer codes with an explicit order are reasonable.
- If the order exists but the spacing is unclear, consider one-hot encoding anyway, or an encoding that learns a value per level.
- In every case, learn the mapping once on training data and reuse it, and decide what happens to missing values.
Exercise
A dataset has a column fruit with values "apple", "banana", "cherry". You code them alphabetically as 0, 1, 2 and fit a linear regression to predict price. The true mean prices are apple 5, banana 20, cherry 5. What does the model learn about the slope on the code, and what does it predict for banana? Why does a separate column per fruit avoid the problem?
Show answer
The prices rise from apple to banana and fall back at cherry, so the best straight line has a slope of zero. The model predicts the overall mean, 10, for every fruit, including banana, which is off by 10. A straight line cannot represent a peak in the middle of an arbitrary order. With one indicator column per fruit, each fruit gets its own coefficient, so the model can predict 5, 20 and 5 separately. No order or distance between fruits is assumed.
Exercise
You run pd.factorize on your training set and again on your test set, then score a model trained on the training codes. Why can accuracy drop with no error message, and what is the correct approach?
Show answer
Without a fixed mapping, factorize numbers labels by first appearance in each dataset, so the same label can get different codes in training and test. The model then receives wrong inputs. The correct approach is to learn the category-to-number mapping once, from the training data only, and apply that same mapping to every later dataset.