Sub topic 2
Cause 3: different data sources, schemas, and missing-value handling
This chapter assumes you know pandas, can train a scikit-learn pipeline, and understand how a join matches rows by key.
Different sources and schemas
Training usually reads from a warehouse table. Serving often reads from a live database or a request payload. The two can disagree on column names, units, types, or encodings. A country field might hold ISO codes in the warehouse and full names in the API. Nothing crashes when the model receives the wrong form. It just sees different inputs.
Missing values
Training code often fills missing values with a statistic from the training set. Serving code, written later by someone else, may fill them with a default such as 0. The model then sees 40 for a missing age in training and 0 in production.
import pandas as pd
train = pd.DataFrame({"age": [30, 40, None, 50]})
train_median = train["age"].median() # fitted once: 40.0
train["age"] = train["age"].fillna(train_median)
def serve_age(request: dict) -> float:
age = request.get("age")
return 0.0 if age is None else float(age) # different rule
print(train["age"].tolist()) # [30.0, 40.0, 40.0, 50.0]
print(serve_age({"age": None})) # 0.0Cause 4: time leakage and point-in-time correctness
Time leakage occurs when a training row uses a feature computed after its label time. The model learns from information it will not have at prediction time, so offline scores look better than live scores. A point-in-time join prevents this. For each label, it takes the latest feature value at or before the label time.
import pandas as pd
labels = pd.DataFrame({
"user_id": [1, 1],
"label_time": pd.to_datetime(["2026-01-10", "2026-01-20"]),
"churned": [0, 1],
}).sort_values("label_time")
features = pd.DataFrame({
"user_id": [1, 1, 1],
"feature_time": pd.to_datetime(["2026-01-05", "2026-01-15", "2026-01-25"]),
"logins_30d": [12, 7, 2],
}).sort_values("feature_time")
train = pd.merge_asof(labels, features, left_on="label_time",
right_on="feature_time", by="user_id",
direction="backward")
print(train[["label_time", "logins_30d"]])The 2026-01-25 value is excluded from both rows, because it was computed after the label times.
Prevention: one transformation in both paths
Write preprocessing once, fit it on training data only, and call the same object from training and serving. Hand-written copies of the logic drift apart over time.
Prevention: ship preprocessing inside the model artifact
Bundle the imputer, scaler, and encoder with the classifier. The saved artifact then carries its own fitted medians, means, and category lists.
import joblib
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
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) # X_train and y_train come from your training set
joblib.dump(model, "model.joblib")> Note: the callout below is a fenced block, not a blockquote.
Prevention: feature stores and a single feature definition
A feature store keeps one definition of each feature. It serves that definition offline for building training sets and online for live requests. Teams with several models sharing features get the most benefit. A single model with one feature function often needs only the shared transform and the bundled pipeline.
Exercise
Serving fills missing income with 0, but training filled it with the median. Which change removes this mismatch?
Show answer
Put the fill inside the bundled pipeline's SimpleImputer, fitted on training data. Serving then applies the stored median, so both paths use the same value.