Sub topic 7
Turning columns into model inputs
This chapter assumes you can use pandas DataFrames and have read the earlier chapters on splitting data and leakage. Models in scikit-learn accept numbers, so every column must become a numeric feature first. This step is called feature engineering and encoding. How you do it affects accuracy and also decides whether training and prediction behave the same way.
What a model can accept
Most scikit-learn estimators take a two-dimensional numeric array. Text labels such as "Leeds" fail or are misread. Missing values break many estimators. Columns on very different scales, such as age (tens) and income (tens of thousands), can distort models that use distances or gradient-based fitting.
Treat each column by its type:
| Column type | Example | Typical treatment |
|---|---|---|
| Continuous number | income | Scale, sometimes transform |
| Unordered category | city | One-hot encoding |
| Ordered category | plan: basic, pro, premium | Ordinal encoding with explicit order |
| Date or time | signup date | Extract parts such as month or days since an event |
| Free text or ID | customer ID | Usually drop, or use specialised methods |
Encoding categories
One-hot encoding
One-hot encoding creates one 0/1 column per category value. A row with city = "York" gets 1 in city_York and 0 in the others. Use it when the categories have no order.
Do not replace cities with 0, 1, 2. A linear model would then treat Hull (2) as twice Leeds (1), which means nothing.
The main risks are these:
- Unseen categories. A new city appears at prediction time. Set
handle_unknown="ignore"so the encoder writes all zeros instead of raising an error. - High cardinality. A column with 50,000 distinct values creates 50,000 columns. Group rare values with
min_frequency, or use another approach such as target encoding. Target encoding must be fitted inside cross-validation, because it uses the target and can leak. - Dummy trap. For plain linear models without regularisation, one column per category is perfectly redundant.
LogisticRegressionis regularised by default, so this rarely matters. You can setdrop="first"if it does.
Ordinal encoding
If categories have a real order, map them to integers in that order. Pass the order explicitly. Otherwise scikit-learn sorts the values alphabetically, which would put "basic", "premium", "pro" in the wrong sequence.
Tree-based models can also work with integer-coded unordered categories, but linear models and distance-based models cannot.
Scaling numeric columns
StandardScaler subtracts the training mean and divides by the training standard deviation. This matters for logistic regression with regularisation, support vector machines, k-nearest neighbours and neural networks. Decision trees and random forests do not care, because they split on thresholds.
Two details are easy to miss:
- The mean and standard deviation come from the training rows only. Fitting a scaler on all rows is leakage, as shown in the leakage chapter.
- Scaling does not fix skew. For a column like income with a long right tail, apply a log transform first, for example
np.log1p.
Creating new features
Sometimes the signal is not in a single column but in a combination. Useful patterns include:
- Ratios: debt divided by income.
- Differences: days between signup and first purchase.
- Date parts: month, day of week, or hour.
- Counts and flags: whether a value is missing, whether a number is above a threshold.
Derive each new feature from the same row's own values. A feature that uses information from other rows, such as the mean income of all customers, must be fitted on the training rows only. Wrap it in a transformer so it follows that rule.
Putting it together with ColumnTransformer
ColumnTransformer applies a different transformer to each group of columns and joins the results. This example runs as shown. It fits on four training rows, then transforms a new row that contains a city the encoder never saw.
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder, OrdinalEncoder, StandardScaler
train = pd.DataFrame({
"age": [25, 32, 47, 51],
"income": [40000, 52000, 88000, 95000],
"city": ["Leeds", "York", "Leeds", "Hull"],
"plan": ["basic", "pro", "premium", "premium"],
})
new = pd.DataFrame({
"age": [38],
"income": [61000],
"city": ["Bath"], # never seen during fitting
"plan": ["pro"],
})
prep = ColumnTransformer([
("num", StandardScaler(), ["age", "income"]),
("plan", OrdinalEncoder(categories=[["basic", "pro", "premium"]]), ["plan"]),
("city", OneHotEncoder(handle_unknown="ignore"), ["city"]),
])
prep.set_output(transform="pandas")
prep.fit(train)
print(prep.transform(train))
print(prep.transform(new))set_output(transform="pandas") needs scikit-learn 1.2 or later. In the output for new, the three city_ columns are all 0 because Bath is unknown, and the model still receives a valid row. The column names tell you which feature is which, which helps when you inspect coefficients later.
Custom features inside a pipeline
Put hand-written features in a FunctionTransformer. Then the same code runs at training and at prediction time.
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import FunctionTransformer, StandardScaler
def add_features(df):
out = df.copy()
out["log_income"] = np.log1p(out["income"])
out["income_per_year_of_age"] = out["income"] / out["age"]
return out[["log_income", "income_per_year_of_age"]]
X = pd.DataFrame({
"age": [25, 32, 47, 51, 38, 29],
"income": [40000, 52000, 88000, 95000, 61000, 45000],
})
y = [0, 0, 1, 1, 1, 0]
model = Pipeline([
("features", ColumnTransformer([
("derived", Pipeline([
("make", FunctionTransformer(add_features)),
("scale", StandardScaler()),
]), ["age", "income"]),
])),
("clf", LogisticRegression()),
])
model.fit(X, y)
print(model.predict(pd.DataFrame({"age": [40], "income": [70000]})))The function uses only values from its own row, so it cannot leak. The scaler that follows is fitted on training data only.
Common errors
- Fitting the encoder on all data. Categories from the test set then leak into the feature list. Fit inside a pipeline so it only sees training rows.
- Different columns at prediction time. If you call
pd.get_dummiesseparately on the training and new data, the two results can have different columns. UseOneHotEncoderinside the pipeline instead, so the column set is fixed at fit time. - Column order or name mismatch.
ColumnTransformerselects columns by name from a DataFrame. A renamed or missing column raises an error, which is better than silently shifting values. - Wrongly ordered ordinal values. Leaving out
categories=gives alphabetical order. - Leaking through the target. Any feature computed from
y, such as target encoding or a group average of the label, must be fitted per training fold. - Dropping the remainder by accident.
ColumnTransformerdiscards columns you did not list. Setremainder="passthrough"only if you want the others kept as they are, and check that they are numeric.
Choosing what to do
Start simple: scale numbers, one-hot encode low-cardinality categories, and order ordinal columns explicitly. Add engineered features only when you have a reason, such as a domain relationship or a skewed distribution. Judge each addition against your baseline and cross-validated scores, not against the training score. A feature that only raises the training score is probably fitting noise.
Exercise
A column country has 3 values in the training data. At prediction time a row arrives with a fourth country. With OneHotEncoder() at its default settings, what happens, and how do you make the pipeline accept the row? Also state why StandardScaler should not be fitted on the full dataset before splitting.
Show answer
By default OneHotEncoder raises an error for the unknown category. Setting handle_unknown="ignore" makes it output all zeros for the country columns, so the row is accepted. A scaler fitted on the full dataset uses the mean and standard deviation of the test rows too, which leaks test information into training and inflates the evaluation. Fit it on training rows only, preferably inside a pipeline.