Sub topic 7
Turning columns into model inputs
This chapter assumes you know pandas DataFrames, basic statistics, and what a supervised model is. It also assumes you have seen a train/test split and the idea of data leakage from earlier chapters.
Why models need numeric input
Most scikit-learn models accept only numbers. A column such as city holds text, and a column such as income holds values on a much larger scale than age. Feature engineering is the work of turning raw columns into numeric inputs a model can use well. The two most common jobs are encoding categories and scaling numbers.
Encoding categorical columns
One-hot encoding replaces a category column with one 0/1 column per category. A row with city = "Oslo" gets a 1 in city_Oslo and 0 in the others.
Avoid mapping categories to integers (Oslo=1, Rome=2, Lima=3) for nominal data. A linear model would treat Lima as "three times" Oslo, which has no meaning.
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
train = pd.DataFrame({"city": ["Oslo", "Rome", "Oslo", "Lima"]})
new = pd.DataFrame({"city": ["Rome", "Paris"]})
enc = OneHotEncoder(handle_unknown="ignore")
enc.fit(train)
print(enc.get_feature_names_out())
print(enc.transform(new).toarray())Paris never appeared in training. With handle_unknown="ignore", it becomes a row of all zeros instead of raising an error at prediction time.
Scaling numeric columns
Scaling puts numeric columns on a comparable range. StandardScaler subtracts the training mean and divides by the training standard deviation. This matters for logistic regression, k-nearest neighbors, and anything regularized or distance-based. Tree-based models do not need it.
Applying different steps to different columns
Real tables mix types, and each type needs its own steps. ColumnTransformer routes columns to the right transformer.
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder, StandardScaler
df = pd.DataFrame({
"age": [25, 40, 33, 51],
"income": [30000, 82000, 54000, 91000],
"plan": ["basic", "pro", "basic", "pro"],
})
prep = ColumnTransformer([
("num", StandardScaler(), ["age", "income"]),
("cat", OneHotEncoder(handle_unknown="ignore"), ["plan"]),
])
X = prep.fit_transform(df)
print(prep.get_feature_names_out())
print(X.round(2))Common errors
- Fitting on all the data. Calling
fit_transformbefore the split lets test-row statistics influence training. Fit on training rows only. - Integer codes for nominal categories. This invents an order that does not exist.
- Missing
handle_unknown. The first unseen category in production raises an error. - Scaling for tree models. It is harmless but unnecessary.
- High-cardinality columns. A column with thousands of distinct values, such as a user ID, creates thousands of one-hot columns. Group rare values or choose another encoding.
Exercise
A model is trained with OneHotEncoder() using default settings. In production, a row arrives with a plan value of "enterprise", which was not in the training data. What happens, and how do you prevent it?
Show answer
The encoder raises an error because the default is handle_unknown="error". Create it with OneHotEncoder(handle_unknown="ignore"), so the unseen value becomes all zeros in that column's one-hot features.