Sub topic 9
Prevention: Ship Preprocessing Inside the Model Artifact
Assume you know basic Python, pandas, and supervised learning. You should also understand that a model is trained on features and later receives features from a production service.
A model artifact is a saved file containing everything needed to make predictions. If preprocessing is saved with the model, the artifact contains both the transformation rules and the trained estimator. Serving loads one object instead of reimplementing preprocessing in a separate handler.
Why bundling prevents skew
Preprocessing often has fit-time state. For example:
- An imputer stores the median used for missing values.
- A scaler stores the training mean and standard deviation.
- A one-hot encoder stores the category vocabulary and column order.
If training calculates these values in one script and serving calculates them again elsewhere, the two paths can disagree. A separately written service might also forget a step or handle an unknown category differently.
A pipeline applies preprocessing and prediction as one operation. Calling fit learns preprocessing state from training data. Calling predict or predict_proba later reuses that saved state.
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": [25, 40, None, 60],
"income": [35_000, 55_000, 48_000, None],
"country": ["US", "CA", "US", "GB"],
})
y_train = [0, 1, 0, 1]
numeric = Pipeline([
("impute", SimpleImputer(strategy="median")),
("scale", StandardScaler()),
])
categorical = OneHotEncoder(handle_unknown="ignore")
preprocess = ColumnTransformer([
("numbers", numeric, ["age", "income"]),
("country", categorical, ["country"]),
])
model = Pipeline([
("preprocess", preprocess),
("classifier", LogisticRegression()),
])
model.fit(X_train, y_train)
joblib.dump(model, "model.joblib")
loaded_model = joblib.load("model.joblib")
request = pd.DataFrame([{
"age": None,
"income": 52_000,
"country": "AU",
}])
print(loaded_model.predict_proba(request))The imputation medians, scaling values, category vocabulary, and classifier parameters are all learned before the artifact is saved. The serving process does not fit anything. It only loads the artifact and transforms new rows with the stored state.
Artifact boundaries and failure modes
The artifact must include every transformation that affects model input. If a feature is created before the pipeline, that feature's definition still needs versioned, shared code or an equivalent controlled component.
Bundling does not solve every problem. The request must still have the expected columns and compatible data types. A pipeline can ignore unknown categories, but it cannot safely infer whether a missing column means “no value” or “a broken request.” Validate the input schema before prediction.
| Risk | Bundled pipeline response |
|---|---|
| Training median differs from serving median | Reuse the fitted imputer |
| New category appears | Configure `handle_unknown="ignore"` |
| Columns arrive in the wrong form | Validate schema and types |
| Artifact and code are incompatible | Version and test the artifact |
Use an artifact format that your serving environment can load safely and consistently. Record the model version, preprocessing version, library versions, and training data time range. Treat the artifact as immutable after publication. To change preprocessing, train and test a new artifact rather than editing the deployed file.
Bundling is strongest when paired with an offline/online parity test. Send the same raw event through the batch feature path and the serving path, then compare the resulting values. The test should fail when column order, missing-value rules, units, or category handling differ.
Exercise
Why should the serving process load a fitted pipeline instead of fitting preprocessing on each request?
Show answer
A fitted pipeline reuses the training-time statistics and category vocabulary, so production applies the same transformation used during training. Fitting per request would change those rules and make predictions inconsistent.