Sub topic 3
The problem with arbitrary integer codes
This chapter assumes you know basic pandas, what a feature matrix is, and how a model is fitted and used to predict. It builds on the earlier chapters about categorical features and the nominal/ordinal distinction.
The tempting shortcut
Models need numbers, and a category column holds text. The quickest fix is to give each category an integer: Berlin becomes 0, Paris becomes 1, Rome becomes 2. The column is now numeric, the code runs, and no error appears. That is the problem. The model cannot tell that the integers are labels and not quantities.
What the model assumes
Linear models, k-nearest neighbors, support vector machines and neural networks all treat a numeric column as a quantity. An integer code therefore adds three claims that nobody checked:
- Order: Rome (2) is "more" than Paris (1), and Paris is "more" than Berlin (0).
- Distance: Berlin and Rome are twice as far apart as Berlin and Paris.
- Proportional effect: each step up in the code changes the prediction by the same amount.
For nominal categories none of these claims is true. The code order is also an accident of the encoder. Scikit-learn's OrdinalEncoder sorts categories alphabetically, so renaming "Berlin" to "Zurich" would change every code and every prediction.
A concrete failure
Suppose Paris listings cost 300 and Berlin and Rome listings cost 100. Paris sits in the middle of the code range, so a straight line through the codes cannot fit this pattern. The code below fits one model on integer codes and one on one-hot columns.
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import OneHotEncoder, OrdinalEncoder
df = pd.DataFrame({
"city": ["Berlin", "Paris", "Rome"] * 2,
"price": [100, 300, 100] * 2,
})
cities = pd.DataFrame({"city": ["Berlin", "Paris", "Rome"]})
# Integer codes: Berlin=0, Paris=1, Rome=2
codes = OrdinalEncoder()
X_codes = codes.fit_transform(df[["city"]])
model = LinearRegression().fit(X_codes, df["price"])
print(np.round(model.predict(codes.transform(cities)), 1))
# One-hot columns: one indicator per city
onehot = OneHotEncoder(sparse_output=False)
X_onehot = onehot.fit_transform(df[["city"]])
model = LinearRegression().fit(X_onehot, df["price"])
print(np.round(model.predict(onehot.transform(cities)), 1))The first model prints [166.7 166.7 166.7]. The best straight line through codes 0, 1, 2 is flat, so it predicts the average price for every city. The second prints [100. 300. 100.]. Each city gets its own column and therefore its own weight, so the model can treat Paris differently from the other two.
Not only a linear problem
Tree-based models can split on a code several times and recover some structure, so they hurt less. They still need extra splits to isolate one category, and the arbitrary order can still shape which groups the splits form. Distance-based and linear models have no such workaround.
When integer codes are correct
Integer codes are fine when the categories have a real order and the spacing is a reasonable approximation. Examples are small < medium < large or survey answers from "never" to "always". This is the ordinal case from the previous chapter. Even then, you should choose the codes yourself, in meaningful order, instead of accepting alphabetical order. Otherwise large would get a lower code than small.
For nominal categories, the fix is to give each category its own indicator column. That representation is the subject of the next chapter.
Exercise
A column "department" holds the values Sales, Support and Legal. You encode it as Legal=0, Sales=1, Support=2 and fit a linear regression. Name two assumptions the model makes about this column that are not true, and say what changes if you add a department named "Accounting".
Show answer
The model assumes the departments are ordered (Support is "more" than Sales, which is "more" than Legal) and that the gaps between them are equal. It also assumes each step in the code changes the prediction by the same amount. Adding "Accounting" sorts first alphabetically, so it would get code 0 and shift every other code by one, which changes all predictions for no real reason.