Sub topic 16
Keeping Training and Serving Consistent
This chapter assumes you know how to build a scikit-learn Pipeline with a ColumnTransformer, and you understand data leakage and cross-validation from earlier chapters. It covers the last step of the workflow: making sure the features your model sees in production match the features it saw in training.
What train-serving skew is
Train-serving skew is a difference between the features a model was trained on and the features it receives when it makes predictions in production. The model itself does not change, but its inputs do, so its accuracy falls. Often nothing crashes and no error appears. The predictions are just worse.
Skew is different from data drift. Drift means the real world changed after training, for example customers got older on average. Skew means the same real-world input produces different feature values in training and in serving because the code paths differ. Drift needs retraining. Skew is a bug you can fix.
How skew arises
Most skew comes from a small set of causes.
| Cause | Example | Effect |
|---|---|---|
| Two implementations of the same logic | A data scientist computes `hour` in pandas. An engineer re-implements it in Java. | Different time zones or rounding give different values. |
| Statistics recomputed at serving time | Scaling a single request with its own mean and standard deviation | Every request is scaled to zero, so the signal is lost. |
| Different missing-value handling | Training fills missing `age` with the median. The serving code passes `-1`. | The model sees a value it never saw in training. |
| Unseen categories | A new city appears in production. | The encoder fails, or a column is silently dropped. |
| Column order or schema changes | The serving payload lists fields in a different order. | Features go to the wrong model inputs. |
| Different data freshness | Training uses a nightly aggregate. Serving uses a live value. | The feature distribution shifts. |
The first two causes are the most common. Both come from fitting or applying preprocessing outside the object that holds the model.
The main defense: one fitted object
The earlier chapters built a single Pipeline that holds the preprocessing and the model. The same object should be used for training, evaluation and serving. When you call fit, every transformer learns its statistics from the training data only. When you call predict, those stored statistics are reused. Nothing is recomputed from the incoming request.
The example below builds a pipeline, fits it and saves it as one artifact. It also records the library versions and the expected input columns next to it.
import json
import joblib
import pandas as pd
import sklearn
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
numeric_cols = ["age", "income"]
categorical_cols = ["city"]
X = pd.DataFrame({
"age": [25, 32, None, 51, 46, 29, 38, 60],
"income": [40000, 52000, 61000, None, 85000, 43000, 58000, 91000],
"city": ["Paris", "Lyon", "Paris", None, "Nice", "Lyon", "Paris", "Nice"],
})
y = [0, 0, 1, 1, 1, 0, 0, 1]
preprocess = ColumnTransformer([
("num", Pipeline([
("impute", SimpleImputer(strategy="median")),
("scale", StandardScaler()),
]), numeric_cols),
("cat", Pipeline([
("impute", SimpleImputer(strategy="most_frequent")),
("onehot", OneHotEncoder(handle_unknown="ignore")),
]), categorical_cols),
])
model = Pipeline([
("prep", preprocess),
("clf", LogisticRegression(max_iter=1000)),
])
model.fit(X, y)
joblib.dump(model, "model.joblib")
metadata = {
"sklearn_version": sklearn.__version__,
"input_columns": numeric_cols + categorical_cols,
}
with open("model_metadata.json", "w") as f:
json.dump(metadata, f)At serving time you load the artifact and call predict_proba on raw rows:
import joblib
import pandas as pd
model = joblib.load("model.joblib")
request = pd.DataFrame([{"age": 41, "income": None, "city": "Marseille"}])
print(model.predict_proba(request))This request has a missing income and a city the model never saw. Both are handled by logic fitted at training time. The median fills the income, and handle_unknown="ignore" turns the unknown city into a row of zeros in the one-hot columns.
Failure modes inside a pipeline
A single pipeline removes most skew, but some problems remain.
Library version mismatch
A pickled or joblib-saved pipeline stores the internal state of its transformers. Loading it under a different scikit-learn version can fail, or worse, load and behave differently. Scikit-learn warns about this, but only if you do not suppress warnings. Pin the library version in your serving environment and store the training version with the artifact, as the metadata file above does.
Schema drift in the request
A ColumnTransformer selects columns by name when you give it a DataFrame. If a column is missing from the request, it raises an error. That is a good outcome, because the failure is loud. The dangerous case is selecting columns by position, for example with integer indices on a NumPy array. A reordered payload then goes through without complaint. Prefer names, and validate the incoming columns before calling the model.
import json
import pandas as pd
with open("model_metadata.json") as f:
expected = json.load(f)["input_columns"]
def validate(request: pd.DataFrame) -> pd.DataFrame:
missing = [c for c in expected if c not in request.columns]
if missing:
raise ValueError(f"Missing input columns: {missing}")
return request[expected]Unseen categories
OneHotEncoder(handle_unknown="ignore") avoids a crash, but it hides a signal. If a large share of requests contain unknown categories, the model is working with less information than you think. Count how often this happens and monitor it.
Custom code outside the pipeline
Feature code written as a standalone pandas function, such as the date-time features from earlier, is the usual source of skew. If you compute hour_sin in a notebook before the pipeline, the serving code must repeat it exactly. Wrap such logic in a FunctionTransformer so it travels with the model. The function must be importable in the serving environment, so keep it in a module and do not define it inside a notebook.
import numpy as np
import pandas as pd
from sklearn.preprocessing import FunctionTransformer
def add_hour_features(df: pd.DataFrame) -> pd.DataFrame:
ts = pd.to_datetime(df["ts"])
hour = ts.dt.hour
return pd.DataFrame({
"hour_sin": np.sin(2 * np.pi * hour / 24),
"hour_cos": np.cos(2 * np.pi * hour / 24),
})
time_features = FunctionTransformer(add_hour_features)
print(time_features.fit_transform(pd.DataFrame({"ts": ["2024-03-01 08:15:00"]})))Be careful with time zones here. If training timestamps are in UTC and serving timestamps arrive in local time, hour differs and the model sees shifted values. Decide on one convention and convert at the boundary.
Reproducibility
Reproducibility means that you can rebuild the same model and get the same features from the same data. It supports skew debugging, because you can tell whether a difference came from the code or from the data. A practical checklist:
- Set
random_stateon every component that uses randomness, including splitters, forests and selectors. - Version the training data, or store a snapshot or a query with its date.
- Pin library versions and record them with the model.
- Keep feature code in a version-controlled module, not in notebook cells.
- Save the whole pipeline, not only the final estimator.
Detecting skew
Even with a careful setup, check for skew directly. The simplest method is to log the features the model actually received in production and compare their distributions with the training features. Compare means, missing-value rates, category frequencies and ranges.
The diagram shows where to compare.
A second method is replay testing. Take a sample of recent production inputs and run them through both the training-time code and the serving code. The outputs should be identical. Any difference points to a code path that is not shared.
The following function checks one numeric feature with a standardized mean difference. It flags a feature when the serving mean is far from the training mean, measured in training standard deviations.
import numpy as np
def mean_shift(train_values, serve_values):
train = np.asarray(train_values, dtype=float)
serve = np.asarray(serve_values, dtype=float)
std = train.std()
if std == 0:
return 0.0
return abs(serve.mean() - train.mean()) / std
print(mean_shift([1, 2, 3, 4, 5], [4, 5, 6, 7, 8]))A shift above roughly 0.5 deserves a look, though the right threshold depends on the feature. This check cannot tell skew from drift. If the pipeline code is shared, a shift points toward drift, and if the code differs, toward skew.
Choosing a serving strategy
| Strategy | Benefit | Cost |
|---|---|---|
| Serve the saved scikit-learn pipeline in Python | No duplicate logic | Requires a Python runtime and pinned versions |
| Export to a portable format such as ONNX | Runs outside Python | Not every transformer converts, so you must test equivalence |
| Re-implement features in another language | Fits an existing stack | Highest skew risk, needs replay tests |
| Use a feature store | One definition for training and serving | Extra infrastructure to run |
If you must re-implement features, treat the original pipeline as the reference and test the new code against it on real samples.
Summary
Skew comes from two code paths, recomputed statistics, schema changes and environment differences. Keep preprocessing and model in one saved pipeline, validate inputs by name, pin versions, monitor feature distributions and test replayed inputs. These steps keep the performance you measured in cross-validation close to what you get in production.
Exercise
A teammate computes hour and hour_sin in a notebook, trains a model on those columns, and saves only the final LogisticRegression. The serving engineer re-implements the hour features in another language. Predictions in production are worse than in validation. List two likely causes and one change that would remove most of the risk.
Show answer
Likely causes: (1) the two implementations of the hour features differ, for example in time zone handling or in the cyclical formula; (2) the preprocessing statistics, if any, were not saved with the model, so serving code must guess them. The change is to wrap the feature code in a FunctionTransformer inside a Pipeline with a ColumnTransformer, fit and save the whole pipeline, and serve it with pinned library versions so training and serving share one code path.
Exercise
You see that 12% of production requests contain a city the model never saw, and no errors are logged. Which setting explains the silence, and what should you do about it?
Show answer
OneHotEncoder(handle_unknown="ignore") encodes unknown categories as all zeros instead of raising an error. Log and monitor the rate of unknown categories, and if it stays high, retrain on newer data or add a grouping such as an "other" category or a coarser location feature.