Sub topic 12
Mixing numeric and categorical columns
This chapter assumes you can fit a LinearRegression, build a Pipeline, and explain why scaling is fitted on training data only. It covers how to feed a table that has both numbers and category labels into one linear model.
Why categories need encoding
A linear model computes y = Xw + b, so every input must be a number. A column such as city holds labels like "a" and "b". Mapping them to 0, 1, 2 would tell the model that city c is twice city b, which is false.
OneHotEncoder avoids this. It creates one 0/1 column per category. Each category then gets its own coefficient, which acts as an adjustment to the prediction when that category is present.
Applying different steps to different columns
Numeric columns need scaling. Categorical columns need encoding. ColumnTransformer applies a separate transformer to each named group of columns and joins the results side by side.
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
df = pd.DataFrame({
"area": [50, 80, 120, 65, 95, 150, 70, 110],
"city": ["a", "b", "a", "c", "b", "c", "a", "b"],
"price": [150, 260, 330, 190, 300, 420, 200, 340],
})
X = df[["area", "city"]]
y = df["price"]
pre = ColumnTransformer([
("num", StandardScaler(), ["area"]),
("cat", OneHotEncoder(handle_unknown="ignore"), ["city"]),
])
model = make_pipeline(pre, LinearRegression())
model.fit(X, y)
print(model.predict(pd.DataFrame({"area": [100], "city": ["b"]})))Each entry in the list is a tuple of a name, a transformer, and the columns it applies to. The pipeline passes the raw DataFrame in, so you predict on raw rows with the same column names.
Common errors
- Unseen categories at predict time. By default,
OneHotEncoderraises an error if it meets a label it did not see duringfit. Settinghandle_unknown="ignore"encodes that row as all zeros instead. - Leakage. Fit the
ColumnTransformerinside the pipeline. Then cross-validation refits the scaler and the encoder on each training fold only. - Wrong column names.
ColumnTransformerselects by name from a DataFrame. A typo or a renamed column fails atfittime. - Dropped columns. Columns not listed are dropped by default (
remainder="drop"). Useremainder="passthrough"to keep them untouched.
The dummy variable trap
With an intercept, one-hot columns for all categories always sum to 1. That makes them perfectly correlated with the intercept, which is a form of multicollinearity. Plain OLS in scikit-learn still runs, because it uses a least-squares solver that tolerates this. The individual coefficients are then not uniquely interpretable. To get a baseline category, use OneHotEncoder(drop="first"). Each remaining coefficient then reads as the difference from the dropped category. Ridge also handles the issue, because regularization makes the solution unique.
Exercise
A pipeline with OneHotEncoder() (default settings) is fitted on rows where city is a, b or c. At prediction time a row has city = "d". What happens, and how do you make the pipeline return a prediction?
Show answer
The encoder raises a ValueError because "d" was not seen during fit. Create the encoder with handle_unknown="ignore" so the row is encoded as all zeros. The prediction then uses only the numeric features and the intercept.