Sub topic 8
Prevention: One Transformation, Used in Both Paths
Assume you know basic Python and pandas, understand supervised learning, and have seen a model deployed behind an API or batch job. The goal is to make training and serving apply the same feature transformation.
Why one transformation matters
Training-serving skew occurs when training and production compute different values from the same raw input. The model may still return predictions, so ordinary error monitoring might not detect the problem.
For example, training might replace a missing age with the training median, while an API replaces it with 0. The model learned one meaning for the feature and receives another meaning in production.
The safest design has one transformation definition:
- Fit the transformation using training data only.
- Save the fitted transformation.
- Apply that same fitted object during batch prediction and online serving.
- Keep raw input validation separate from feature transformation.
Bundle preprocessing with the model
A scikit-learn Pipeline stores preprocessing and prediction as one object. The fit step learns values such as numeric medians, scaling statistics, and category vocabularies. The predict step reuses those learned values.
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
X_train = pd.DataFrame({
"age": [25, 40, None, 55, 31, 48],
"income": [35_000, 60_000, 52_000, None, 42_000, 80_000],
"country": ["US", "CA", "US", "GB", "CA", "US"],
})
y_train = [0, 1, 1, 0, 0, 1]
numeric = Pipeline([
("impute", SimpleImputer(strategy="median")),
("scale", StandardScaler()),
])
preprocess = ColumnTransformer([
("numeric", numeric, ["age", "income"]),
("country", OneHotEncoder(handle_unknown="ignore"), ["country"]),
])
model = Pipeline([
("preprocess", preprocess),
("classifier", LogisticRegression()),
])
model.fit(X_train, y_train)
request_df = pd.DataFrame([{
"age": None,
"income": 58_000,
"country": "AU", # An unseen category is handled safely.
}])
probability = model.predict_proba(request_df)[0, 1]
print(f"Churn probability: {probability:.3f}")The serving process must load this fitted pipeline rather than recreate the preprocessing rules. The handle_unknown="ignore" setting prevents a new country from causing a category-encoding error. It does not mean every input is valid. Schema checks should still reject missing columns, wrong types, or impossible values.
What must be shared
| Transformation concern | Shared rule |
|---|---|
| Missing numeric values | Same fitted imputer and statistic |
| Numeric scale | Same fitted means and standard deviations |
| Categories | Same vocabulary and unknown-category policy |
| Column meaning | Same names, types, and units |
A shared library function can work when the transformation is simple. A bundled pipeline is usually safer because its fit-time state travels with the model artifact. A feature store can also provide one feature definition for batch and online access, but it adds operational cost.
Exercise
Why should the serving code load the fitted pipeline instead of writing an equivalent imputation function?
Show answer
The fitted pipeline preserves the exact training statistics and category rules, preventing small implementation differences from changing feature values.