Sub topic 1
Categorical features and why models need numbers
A categorical feature takes its value from a fixed set of labels, such as a color, a city, or a payment method. Most scikit-learn models are built on arithmetic: they multiply, add and compare numbers. This chapter explains why labels have to be converted to numbers first and how to spot the columns that need it. Later chapters cover the encoding itself.
Prerequisites
This chapter assumes you know the following:
- Basic Python and pandas DataFrames
- NumPy arrays and what a feature matrix is (rows are samples, columns are features)
- The idea of a training set and a test set
What counts as a categorical feature
A categorical feature has a limited set of distinct values, called categories. The values name a group. They do not measure an amount.
Typical examples:
- A
citycolumn with values likeParis,BerlinandRome - A
browsercolumn withfirefox,chromeandsafari - A
sizecolumn withsmall,mediumandlarge
In pandas, these columns usually have a text dtype (object, string or category). Numeric columns can also be categorical. A zip_code column stores integers, but adding two zip codes means nothing.
The code below lists the non-numeric columns of a DataFrame and counts their distinct values:
import pandas as pd
df = pd.DataFrame({
"city": ["Paris", "Berlin", "Paris", "Rome"],
"age": [25, 32, 47, 51],
"plan": ["free", "pro", "free", "pro"],
})
categorical = df.select_dtypes(exclude="number")
print(categorical.columns.tolist())
print(categorical.nunique())Selecting by exclude="number" works across pandas versions, because the default text dtype differs between them. The count of distinct values per column matters later, when you decide how to encode it.
Why models need numbers
A model such as linear regression computes a weighted sum of the features. Logistic regression, support vector machines and neural networks also depend on distances, dot products or gradients. None of these operations is defined for the string "Paris".
scikit-learn checks this when you call fit. The following example shows the failure:
import pandas as pd
from sklearn.linear_model import LogisticRegression
X = pd.DataFrame({
"color": ["red", "green", "blue", "green"],
"age": [25, 32, 47, 51],
})
y = [0, 1, 0, 1]
try:
LogisticRegression().fit(X, y)
except ValueError as err:
print(type(err).__name__)
print(err)The error says the model could not convert a string to a float. The error is useful, because it stops you from continuing with an unprepared column.
Some tree-based estimators, such as HistGradientBoostingClassifier, can handle categorical columns natively when configured to. Most other models cannot, so the usual approach is to turn categories into numbers before training.
The encoding step in the workflow
Encoding sits between the raw table and the model. The model only ever sees the numeric output.
Why the choice of numbers matters
The simplest fix is to assign each label an integer: red=0, green=1, blue=2. This removes the error, but it also makes a claim the data does not support. The model now sees blue as "twice" green and red as "less than" green. For labels with no natural order, that is misleading. The next chapters explain which categories have a real order and how one-hot encoding avoids the false ordering.
Summary
- Categorical features take values from a fixed set of labels, and they can be stored as text or as integers.
- Most scikit-learn models need numeric input, and
fitraises aValueErrorwhen it meets strings. - The way you assign numbers changes what the model can learn, so encoding is a modeling decision.
Exercise
A DataFrame has a numeric column zip_code containing values like 10115 and 75001. Should you treat it as a categorical feature? Explain why.
Show answer
Yes, usually. A zip code identifies a region and has no meaningful size. A model that treats 75001 as larger than 10115 would learn from a difference that does not exist, so the column should be encoded as categories.