Sub topic 1
Categorical Features and Why Models Need Numbers
Prerequisites
This chapter assumes basic Python, pandas DataFrames, NumPy arrays, training and test splits, and the idea of a feature matrix. A categorical feature is a feature whose values represent groups or labels, such as color, city, or payment_method.
Many machine-learning models operate on numbers. They calculate distances, averages, weighted sums, or split points. A text value such as "red" has no direct numeric meaning for these operations, so categorical values must be represented numerically before training.
Nominal and Ordinal Categories
A nominal category is a label with no natural order. Colors, cities, and browser types are nominal. "red" is not greater than "blue".
An ordinal category has a meaningful order. Examples include "small", "medium", and "large", or ratings from one to five. The order matters, although the distance between levels may not be equal.
One-hot encoding usually fits nominal features. Ordinal features can use ordered numeric values when the model should use their order. The choice depends on the meaning of the feature and the model.
The Problem with Arbitrary Integer Codes
Suppose the colors are encoded as:
blue = 0green = 1red = 2
This representation invents an order. A linear model may treat red as twice blue, and a distance-based model may treat green as equally far from blue and red. Those relationships are artifacts of the encoding, not properties of the colors.
The same problem occurs when nominal categories are assigned IDs from a database. The IDs identify values, but they do not measure them.
How One-Hot Encoding Works
One-hot encoding creates one binary feature for each category. A binary feature contains 0 or 1.
| color | color_blue | color_green | color_red |
|---|---|---|---|
| red | 0 | 0 | 1 |
Each row activates exactly one column when the original value is a known single category.
import pandas as pd
df = pd.DataFrame({"color": ["red", "green", "blue", "green"]})
encoded = pd.get_dummies(df, columns=["color"], dtype=int)
print(encoded)The result lets a model learn a separate effect for each color without assigning a false numeric order. One-hot encoding increases the number of columns, so high-cardinality features may require a different strategy.
Exercise
Why is encoding city names as 1, 2, and 3 usually misleading?
Show answer
The numbers create an artificial order and distance between nominal categories. One-hot encoding represents each city with its own indicator column instead.