Sub topic 5
Cause 2: Statistics and Vocabularies Fitted at Training Time
This chapter assumes you can read pandas and scikit-learn code. It also assumes you know the fit/transform split in scikit-learn and have seen a model trained offline and served behind an API or batch job. The previous chapter covered skew caused by writing the same feature logic twice. Here the code can be identical in both paths and the model still receives different inputs, because the transformation depends on numbers learned from data.
What "fitted state" means
Some preprocessing steps are fixed functions. Taking a logarithm or extracting the hour from a timestamp needs no data to decide how it behaves. Other steps must first learn parameters from the training set and then apply them. This chapter calls those learned parameters fitted state.
| Step | Fitted state | Learned from |
|---|---|---|
| Mean or median imputation | The fill value | Training column |
| Standardization | Mean and standard deviation | Training column |
| Min-max scaling | Minimum and maximum | Training column |
| One-hot or ordinal encoding | Category vocabulary and its order | Training column |
| Quantile binning | Bin edges | Training column |
| Target encoding | Per-category target average | Training features and labels |
| Text vectorizer | Token vocabulary, document frequencies | Training corpus |
| PCA or feature selection | Components, selected column list | Training matrix |
The rule for all of these is the same. The state is computed once, on training data only, and then frozen. At serving time the model must receive exactly that frozen state. Skew appears whenever the serving path recomputes the state, reconstructs it differently, or loses it.
How fitted state goes wrong
Recomputing statistics on the serving data
A common mistake is to call fit_transform on whatever data arrives at serving time. It is easy to write when a batch scoring job reuses the training notebook with a new input path. The statistics then describe the batch, not the training set.
import numpy as np
from sklearn.preprocessing import StandardScaler
train_ages = np.array([[30.0], [40.0], [50.0], [60.0]])
scaler = StandardScaler().fit(train_ages) # mean 45, std about 11.18
request = np.array([[60.0]])
print(scaler.transform(request)) # [[1.34164079]]
# Wrong: refitting on the request itself
print(StandardScaler().fit_transform(request)) # [[0.]]With a single row, the refitted scaler sees a constant column and returns 0 for any age. The model receives 0 for a 60-year-old and for a 20-year-old alike. Nothing fails, and predictions look plausible.
Batches are less obvious. If a nightly job scales each day's data with that day's own mean, the feature drifts with the batch composition. A day with unusually old customers is rescaled to look average, which hides the very signal the model uses.
Rebuilding the vocabulary from the serving data
Category encoders have the same problem. pd.get_dummies builds its columns from whatever values it sees, so it is a fit step disguised as a transform.
import pandas as pd
train = pd.DataFrame({"country": ["DE", "FR", "US", "FR"]})
print(pd.get_dummies(train["country"]).columns.tolist()) # ['DE', 'FR', 'US']
request = pd.DataFrame({"country": ["US"]})
print(pd.get_dummies(request["country"]).columns.tolist()) # ['US']Training produces three columns and serving produces one. If the request is then aligned to the model's input by position, the US flag lands in the slot the model learned for DE. If the framework raises a shape error, you notice. If a reindex or a padding step silently fixes the shape, you do not.
The same failure appears with pd.factorize or category codes computed per dataset. The integer assigned to FR depends on which values appeared first or which sort order applied. Two runs on different data can assign different integers to the same string.
Fitting on more than the training split
The reverse error happens inside the training path. If you fit the imputer or scaler on the full dataset before splitting, the validation rows influence the statistics. Validation scores then look slightly better than production will. This is not strictly skew between training and serving, but it produces the same symptom: offline metrics that production does not reproduce. Fit on the training split only, then transform validation and test data with that fitted object.
Target encoding is the stronger case. It uses the label to compute the feature, so fitting on rows that include a row's own label leaks that label into its feature. Production rows have no label, so the model has learned to trust a signal that does not exist at serving time. Use out-of-fold encoding during training, and apply the full-training-set mapping at serving.
Losing the state between the two environments
Even when the state was computed correctly, it can be lost or mismatched. Typical causes:
- The training notebook prints the mean and a developer copies the number into the serving code. The two values drift apart at the next retrain.
- The model artifact is updated but the file holding the vocabulary is not, so the model and its encoder come from different training runs.
- The serving container uses a different library version than training, so a pickled transformer loads with different defaults or fails to load.
The fix: fit once, save the fitted object, reuse it
Put every fitted step in the same pipeline object as the model, fit that object once on training data, and save the whole thing. The serving process loads the artifact and calls predict_proba. It never fits anything.
import joblib
import numpy as np
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, np.nan, 50, 60, 35],
"income": [40_000, 52_000, 61_000, np.nan, 90_000, 45_000],
"country": ["DE", "FR", "US", "FR", "US", "DE"],
})
y_train = [0, 0, 1, 0, 1, 0]
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")
# Serving process
served = joblib.load("model.joblib")
request = pd.DataFrame({"age": [np.nan], "income": [58_000], "country": ["BR"]})
print(served.predict_proba(request))
# The frozen state travels with the model
num = served.named_steps["preprocess"].named_transformers_["num"]
print(num.named_steps["impute"].statistics_) # training medians
print(served.named_steps["preprocess"].named_transformers_["cat"].categories_)This code handles the three failures above. The median for the missing age is the training median, not a value computed from the request. The scaler uses the training mean and standard deviation. The encoder keeps the training vocabulary and column order. The unseen country BR becomes an all-zero row of category columns instead of raising an error or shifting columns.
Replace nothing here; the diagram follows.
Edge cases and decisions
Unseen categories. handle_unknown="ignore" keeps serving alive, but it also hides a real change. A new country that makes up 20% of traffic is encoded as "none of the known countries". Log how often the encoder meets unknown values so that the fallback does not stay invisible. Later chapters cover logging and drift metrics.
Missing values at serving time that never occurred in training. SimpleImputer only learns a fill value for columns it was fitted on. If a column had no missing values in training, newer scikit-learn versions still transform serving NaNs using the stored statistic, but a downstream model may not expect them. Check how your own imputer and model behave on a NaN in a previously complete column, and decide whether to reject such requests.
Version pinning. Pickled objects are tied to library versions. Record the scikit-learn and pandas versions with the artifact, and build the serving image from the same pinned requirements. Loading across versions can emit a warning or silently change behavior.
Refreshing state. Frozen state is deliberate, but it ages. When the input distribution moves, the right response is to retrain, which refits all state and the model together. Updating only the scaler's mean while keeping the old model weights is a mismatch, because the weights were learned against the old scale.
Per-batch normalization on purpose. Sometimes per-batch statistics are part of the model design, such as per-user normalization. Then the training path must compute them the same way, over the same window and grouping, which makes this a shared-code problem rather than a fitted-state one.
Exercise
A serving job scores one day of data at a time. Its code calls StandardScaler().fit_transform(day_df[["income"]]) before model.predict, and the model was trained on a scaler fitted on all of last year's data. Name the problem, give one reason it fails silently, and state the fix.
Show answer
The scaler is refitted on each day's data, so it uses that day's mean and standard deviation instead of the training statistics. The model then receives values on a different scale from the one it learned, and shifts in the day's income level are scaled away. It fails silently because the output shape and dtype are valid, so no error is raised and predictions are still produced. The fix is to fit the scaler once on the training split, save it with the model in one pipeline, and call only transform (or predict_proba on the pipeline) at serving time.