Week 03 · Feature pipelines and unseen categories
Apply training-time transforms consistently when an inference row looks new.
← Week 2 · Subject contents · Week 4 →
Apply training-time transforms consistently when an inference row looks new.
Work through the problem
A feature pipeline maps raw records to fixed-width numeric vectors. A training mean μ and standard deviation σ give z=(x−μ)/σ. For training values 2 and 6, μ=4 and population σ=2, so inference input 8 becomes z=2. Recomputing μ from an inference batch would change the model’s input meaning.
For category columns, learn the vocabulary from training data. This example encodes an unseen category as all zeroes. That keeps the schema stable and allows a prediction. Record unknown-category rates to see when the policy is being used often.
Run the Python lab
import numpy as np
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler, OneHotEncoder
X = np.array([[2,"air"],[6,"rail"],[None,"rail"]],dtype=object)
numeric = make_pipeline(SimpleImputer(),StandardScaler())
pipe = ColumnTransformer([("numeric",numeric,[0]),("route",OneHotEncoder(handle_unknown="ignore",sparse_output=False),[1])])
pipe.fit(X)
out = pipe.transform(np.array([[8,"road"],[None,"air"]],dtype=object))
print(pipe.get_feature_names_out().tolist())
print(out.round(3))
assert np.allclose(out[0,1:],0) and np.isclose(out[1,0],0)
Output from the lab
['numeric__x0', 'route__x1_air', 'route__x1_rail']
[[2.449 0. 0. ]
[0. 1. 0. ]]
Practice
- Why does the numerical output for 8 differ from the hand example?
Check your reasoning
- Imputation adds a third value of 4 before scaling. The mean stays 4 and the estimated standard deviation falls to √(8/3).