Sub topic 16
Keeping training and serving consistent
This chapter assumes you can build a scikit-learn Pipeline with a ColumnTransformer, and that you know why transformations must be fitted only on training data. Here the question is what happens after training, when the model runs on live data.
What train-serving skew is
Train-serving skew is a difference between the features a model saw during training and the features it receives in production. The model code can be unchanged and still give worse predictions, often with no error message.
Common causes:
- Duplicated logic. Analysts compute features in a notebook, and engineers rewrite them in another language for the service. Small differences, such as rounding or how a missing value is handled, creep in.
- Different fitted values. The service recomputes a mean or a category list from recent data instead of reusing the values learned at training time.
- Different data sources. Training reads a cleaned warehouse table. Serving reads raw events.
- Time effects. A feature such as "purchases in the last 30 days" is computed with information that was not available at prediction time.
- Library changes. A new scikit-learn or pandas version changes a default.
Reduce skew with one artifact
The pipeline from the earlier chapter stores the imputer medians, scaler means and encoder categories inside its fitted steps. If you save the whole fitted pipeline, serving applies exactly those values.
import joblib
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
train = pd.DataFrame({
"age": [25, 32, None, 51, 44, 29],
"income": [40000, 52000, 61000, None, 75000, 38000],
"city": ["Oslo", "Rome", None, "Oslo", "Rome", "Oslo"],
"bought": [0, 1, 1, 0, 1, 0],
})
X, y = train.drop(columns="bought"), train["bought"]
preprocess = ColumnTransformer([
("num", Pipeline([
("impute", SimpleImputer(strategy="median")),
("scale", StandardScaler()),
]), ["age", "income"]),
("cat", Pipeline([
("impute", SimpleImputer(strategy="most_frequent")),
("onehot", OneHotEncoder(handle_unknown="ignore")),
]), ["city"]),
])
model = Pipeline([("prep", preprocess), ("clf", LogisticRegression(max_iter=1000))])
model.fit(X, y)
joblib.dump(model, "model.joblib")
# In the serving process
served = joblib.load("model.joblib")
request = pd.DataFrame([{"age": None, "income": 58000, "city": "Paris"}])
print(served.predict_proba(request))The request has a missing age and a city never seen in training. The saved imputer fills the age with the training median, and handle_unknown="ignore" encodes "Paris" as all zeros instead of raising an error.
Practices that keep the two sides aligned
- Share code. Put feature logic in the pipeline, not in a separate script for each side. Use
FunctionTransformerfor custom steps. - Version everything. Store the artifact, library versions and the list of expected input columns together.
- Validate inputs. Check column names, types and ranges at the service boundary, and log values outside the training range.
- Compare distributions. Periodically compare serving feature statistics with training statistics. A shifted mean or a new share of missing values is an early warning.
- Log serving features. Save the exact features used for each prediction. You can then replay them and check that offline and online outputs match.
- Use point-in-time data. When building training sets, compute each feature as it would have been known at the prediction moment.
Reproducibility
Set random_state on models and splitters, pin dependency versions, and keep the training data snapshot or its identifier. Then you can rebuild a past model and explain a past prediction.
Exercise
A service recomputes the mean of "income" from the last hour of requests and uses it to standardize each request. Why is this train-serving skew, and what is the fix?
Show answer
The model was trained on features scaled with the training-set mean and standard deviation. Recomputing them from a small, recent sample gives different scaled values for the same input, so the model sees a different distribution than it learned from. The fix is to save the fitted StandardScaler inside the pipeline and apply its stored values at serving time.