Sub topic 5
Cause 2: Statistics and Vocabularies Fitted at Training Time
Assume you know basic Python and pandas, understand supervised learning, and have seen a model deployed behind an API or batch job.
Many preprocessing steps learn values from training data. These learned values are called fit-time state. Examples include the median used to fill missing values, the mean and standard deviation used for scaling, and the list of categories used for one-hot encoding.
The model must use the same state during serving. If production calculates new values, the model receives features with a different meaning or scale.
Fit and transform are different operations
A transformer has two important operations:
- Fit calculates and stores values from data.
- Transform applies stored values to new data.
For example, a median imputer fits a median from the training rows. It then uses that same median for validation rows and production requests. It must not calculate a new median for each request.
| Transformer | State fitted during training | Serving behavior |
|---|---|---|
| Median imputer | One median per numeric column | Fill missing values with those medians |
| Standard scaler | Mean and standard deviation | Apply the training scale |
| One-hot encoder | Known category vocabulary | Use the same columns for known categories |
How fit-time state causes skew
Suppose training ages are [30, 40, 50], and one age is missing. The training median might be 40. If the serving handler fills missing ages with 0, the model sees a value far outside the training pattern.
Category encoding has a similar problem. Training may create columns for US, CA, and GB. A separately written serving process might create columns in a different order or drop a column when a category is absent. The numbers still look valid, so this error can fail silently.
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": [30_000, 50_000, 45_000, None],
"country": ["US", "CA", "US", "GB"],
})
y_train = [0, 1, 0, 1]
preprocess = ColumnTransformer([
("numeric", Pipeline([
("impute", SimpleImputer(strategy="median")),
("scale", StandardScaler()),
]), ["age", "income"]),
("country", OneHotEncoder(handle_unknown="ignore"), ["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": 48_000,
"country": "FR", # unseen category; ignored safely
}])
print(loaded_model.predict_proba(request))The pipeline fits the imputer, scaler, and encoder once. The saved artifact contains all three fitted objects and the classifier. Serving only calls predict or predict_proba; it does not refit anything.
Keep fit-time state with the model
A model artifact should include every transformation needed to turn raw input into model features. This prevents a separately implemented serving path from making different decisions.
Fit-time state can become stale when the data-generating process changes. That is a retraining question, not a reason to silently refit during serving. Monitor feature distributions and decide whether to update the model through a controlled training and release process.
Exercise
Why should a serving process transform a missing age with the training median instead of calculating a new median?
Show answer
The model learned its coefficients from features transformed with the training median. Reusing that median preserves the feature meaning and scale.