Sub topic 9
Prevention: Ship Preprocessing Inside the Model Artifact
This chapter assumes you can write Python and pandas, know the train/validate/predict workflow, and have a rough idea of how a model sits behind an API or batch job. It also assumes you have read the earlier chapters on code skew and fit-time state.
The problem this solves
A model is more than its learned weights. It also depends on everything that turns a raw record into the numbers the weights expect. That includes imputation values, scaling statistics, category vocabularies, and column order.
If you save only the weights, the serving team has to rebuild the rest from documentation or from a copy of the training notebook. Each rebuild is a chance for the two paths to disagree. The earlier chapters showed two failures of this kind. In one, a missing age became 40 in training and 0 in production. In the other, the fitted statistics were recomputed or guessed at serving time instead of reused.
The prevention in this chapter is simple to state. Treat the preprocessing and the estimator as one object. Fit them together, save them together, and load them together.
The bundled pipeline
In scikit-learn, a Pipeline chains transformers and a final estimator. A ColumnTransformer applies different transformers to different columns. When you call fit on the pipeline, each step is fitted in order on the training data. The fitted state lives inside the step objects:
SimpleImputerstores the median of each column.StandardScalerstores the mean and standard deviation of each column.OneHotEncoderstores the category vocabulary for each column.
Saving the pipeline saves all of that state with the weights.
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
X_train = pd.DataFrame({
"age": [30, 40, None, 50, 35, 45],
"income": [40000, 52000, 61000, None, 45000, 58000],
"country": ["DE", "FR", "DE", "US", "FR", "US"],
})
y_train = [0, 1, 0, 1, 0, 1]
preprocess = ColumnTransformer([
("num", Pipeline([
("impute", SimpleImputer(strategy="median")),
("scale", StandardScaler()),
]), ["age", "income"]),
("cat", OneHotEncoder(handle_unknown="ignore"), ["country"]),
])
model = Pipeline([("preprocess", preprocess), ("clf", LogisticRegression())])
model.fit(X_train, y_train)
joblib.dump(model, "model.joblib")
# In the serving process:
model = joblib.load("model.joblib")
request_df = pd.DataFrame([{"age": None, "income": 50000, "country": "BR"}])
print(model.predict_proba(request_df))The request has a missing age and a country the model never saw. The serving code contains no imputation logic and no vocabulary. The median age comes from the saved imputer. The unknown country becomes an all-zero one-hot row because of handle_unknown="ignore".
The serving path now has nothing to get wrong, because it has no preprocessing code of its own. It builds a DataFrame with the right column names and calls the pipeline.
What fitting once means
Fit the whole pipeline on the training split only. Do not fit the preprocessing on the full dataset before splitting, because validation rows would then influence the medians and scaling. The pipeline makes the right behavior easy:
- Split the data into train and validation sets.
- Call
model.fit(X_train, y_train). All fitted state comes from the training rows. - Call
model.predict(X_valid)ormodel.score(X_valid, y_valid). The validation rows are transformed with the training statistics, which is the same thing that happens to a production request.
Cross-validation works the same way when you pass the whole pipeline to cross_val_score. Each fold refits the preprocessing on that fold's training rows. If you preprocess first and cross-validate only the classifier, you leak information from the held-out fold.
The diagram below shows the flow.
What belongs in the artifact
Put in the artifact everything that is a function of the training data or that must match it exactly:
- Imputation values, scaling parameters, and category vocabularies.
- The expected input column names and their order.
- Text processing such as a tokenizer or vocabulary.
- Feature selection results, such as which columns survived a variance filter.
- Custom transformations, written once as a class with
fitandtransformmethods.
Some things should stay outside the artifact. Business rules that change independently of the model, such as a list of blocked users, are better handled in separate code with their own tests. Heavy lookups against live systems also belong outside, because a frozen copy would become stale.
Custom transformations
Built-in transformers do not cover every feature. Write custom steps as classes that follow the scikit-learn interface, so they can be fitted, saved, and reused like any other step.
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
class LogIncome(BaseEstimator, TransformerMixin):
"""Adds log1p(income) and clips negative values to zero first."""
def fit(self, X, y=None):
return self
def transform(self, X):
X = X.copy()
X["log_income"] = np.log1p(X["income"].clip(lower=0))
return X
df = pd.DataFrame({"income": [0, 100, -5]})
print(LogIncome().fit_transform(df))Because LogIncome inherits from BaseEstimator, it works with clone and grid search. It is saved as part of the pipeline.
Gotchas and limits
Bundling removes one cause of skew, but it leaves others. Check each of these.
- Library versions. A pickle or joblib file records class names and internal attributes, not the library's logic. Loading it under a different scikit-learn version can warn, fail, or silently change behavior. Pin the same versions of scikit-learn, NumPy, and pandas in training and serving, and record them next to the artifact.
- Unpickling is code execution. Loading a pickle from an untrusted source can run arbitrary code. Load artifacts only from storage your own pipeline controls.
- Custom classes must be importable. A pipeline that contains
LogIncomecan only be loaded where that class can be imported under the same module path. Package such classes in a library that both the training job and the server install. - Column names and dtypes. The pipeline expects the columns it was fitted on. A renamed column raises an error, which is good. A column that arrives as a string instead of a number may be converted without a clear error. Validate inputs at the boundary, which the schema validation chapter covers.
- Features that need history. A rolling count of logins over 30 days cannot be computed from one request. It must come from a data store, and that value can still differ between paths. The point-in-time and feature store chapters address this.
- Different runtimes. If the model is exported to another format, such as ONNX, or served from a non-Python service, check that every preprocessing step was exported too. Exporting only the classifier brings back the original problem.
Verifying the bundle
Bundling reduces the risk. It does not prove the two paths agree, so add a round-trip test. Fit a pipeline, save it, load it in a fresh process or at least a fresh object, and compare predictions on the same rows.
import joblib
import numpy as np
def test_roundtrip(model, sample_df, path="model_test.joblib"):
expected = model.predict_proba(sample_df)
joblib.dump(model, path)
reloaded = joblib.load(path)
actual = reloaded.predict_proba(sample_df)
np.testing.assert_allclose(expected, actual, rtol=1e-9)Include rows with missing values and unseen categories in sample_df, since those are where preprocessing differences show up. The next chapters build on this with offline/online parity tests that run the real serving code.
Choosing this approach
| Situation | Bundled pipeline fits well | Consider something else |
|---|---|---|
| Features computed from the request alone | Yes | |
| Features that need history or joins | Partly | Feature store or lookup service |
| Training in Python, serving in Python | Yes | |
| Serving in another language | Only if exported completely | Shared transformation spec or service |
| Many models sharing the same features | Possible, with duplication | Shared feature definitions |
A bundled pipeline is the cheapest prevention with the largest effect for single-model, request-based systems. Start there, and add a feature store when features need history or must be shared across models.
Exercise
A team saves only the trained classifier with joblib. The serving code reimplements median imputation by hardcoding the training median of 38 for age. Six months later the model is retrained on new data with a median of 41, and the team forgets to update the hardcoded number. Which kind of skew occurs, and how does bundling prevent it?
Show answer
This is fit-time state skew, combined with duplicated logic. The model is trained with a median of 41 but served with 38. Bundling the imputer inside the pipeline stores the median in the artifact on every fit, so retraining produces a new artifact that carries the new median, and the serving code has no number to forget to update.
Exercise
You preprocess the full dataset with StandardScaler, split it into train and validation sets, and then fit a classifier on the train set. Validation accuracy looks good. Why is this evaluation misleading, and what is the fix?
Show answer
The scaler's mean and standard deviation were computed using the validation rows, so information from the validation set leaked into training and the evaluation is optimistic. The fix is to split first and fit a Pipeline containing the scaler and classifier on the training rows only, then score the validation rows with it.