Sub topic 5
Features and training-serving consistency
This chapter assumes you can train a supervised model with scikit-learn, read pandas code, and know that a deployed model usually runs behind a service. It covers how raw data becomes model inputs, and how to make sure the model sees the same inputs in production as it did in training.
What a feature is
A feature is a numeric or categorical input the model receives, computed from raw data. Examples include a customer's age, the number of orders in the last 30 days, or a one-hot encoded plan type. Feature engineering is the code that turns raw records into those inputs. It covers scaling, encoding, aggregation, and handling of missing values.
In the lifecycle, this step sits between data management and experiment tracking. The data chapter produces a validated, versioned dataset. This chapter produces the transformation logic that the model depends on. The trained model is only valid together with that logic.
Training-serving skew
Training-serving skew means the feature values a model sees in production differ from the values it saw in training, for the same underlying input. The model code is unchanged and no error is raised. Predictions just get worse.
Skew is hard to notice because nothing crashes. A mismatched scaler still produces numbers, and a swapped category order still produces a valid vector.
| Cause | Example | Typical symptom |
|---|---|---|
| Duplicated logic | Training uses pandas, serving uses a hand-written Java port that rounds differently | Small, systematic prediction offsets |
| Different fitted statistics | Scaler mean is recomputed on a live batch instead of reused from training | Predictions shift with batch composition |
| Category handling | Unseen category raises an error online, or maps to a different column index | Errors or silent misclassification |
| Missing-value rules | Training fills nulls with the median, serving fills with 0 | Bias on records with gaps |
| Time-window differences | Offline "last 30 days" uses calendar days, online uses a rolling counter that lags | Feature lower online than offline |
| Data leakage in training | A feature includes information only known after the prediction time | Excellent offline metrics, poor production results |
The last row is not strictly skew but has the same effect, and it is covered below.
The core principle: one definition, used twice
The most reliable defense is a single implementation of each transformation, used by both the training job and the serving path. The diagram shows the shape of this design.
The loop from the artifact back to the transformation matters. Many transformations have fitted state, such as a mean, a standard deviation, or a category list. That state is learned once on training data and must be reused unchanged at serving time.
Pattern 1: bundle preprocessing with the model
If you use scikit-learn, put preprocessing and model in a single Pipeline and save them as one artifact. The fitted scaler and encoder travel with the classifier, so serving cannot use different statistics.
import joblib
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
train = pd.DataFrame(
{
"age": [25, 32, 47, 51, 38, 29, 60, 44],
"plan": ["basic", "pro", "basic", "pro", "basic", "pro", "basic", "pro"],
"churned": [0, 0, 1, 0, 1, 0, 1, 0],
}
)
X = train[["age", "plan"]]
y = train["churned"]
preprocess = ColumnTransformer(
[
("num", StandardScaler(), ["age"]),
("cat", OneHotEncoder(handle_unknown="ignore"), ["plan"]),
]
)
model = Pipeline([("prep", preprocess), ("clf", LogisticRegression())])
model.fit(X, y)
joblib.dump(model, "churn_model.joblib")
# Serving side: load one artifact, send raw fields, never re-fit anything.
served = joblib.load("churn_model.joblib")
request = pd.DataFrame([{"age": 41, "plan": "enterprise"}]) # category unseen in training
print(round(float(served.predict_proba(request)[0, 1]), 3))Two details prevent common failures. handle_unknown="ignore" makes an unseen category encode as all zeros instead of raising an error. The request uses the same column names as training, because ColumnTransformer selects by name.
The limitation is that this works when training and serving both run Python with compatible library versions. Pin the scikit-learn version in both environments, because a pickled pipeline can fail or behave differently across versions.
Pattern 2: shared feature code and parity tests
When training runs as a batch job and serving needs low latency, you often cannot share a single pipeline object. Instead, put the feature functions in a shared package that both import. Add a parity test that runs the same raw records through the batch path and the online path and asserts equal output.
A common arrangement is that the batch path takes a DataFrame and the online path takes one dictionary. Test both on the same rows, including edge cases: nulls, zeros, unseen categories, and extreme values. Run this test in CI so a change to either path fails the build.
Pattern 3: a feature store
A feature store is a system that stores feature definitions, computes them, and serves them in two forms. The offline store holds historical values for building training sets. The online store holds the latest values for low-latency lookup. Both are populated from the same definitions, which addresses skew by construction.
A feature store adds infrastructure, so it pays off mainly when several models reuse the same features or when online features need precomputed aggregates. For a single model with simple transformations, Pattern 1 is usually enough.
Point-in-time correctness
Training sets are built from history, so each row must contain only what was known at the moment the prediction would have been made. If you join a customer's current order count to a churn label from three months ago, the feature contains the future. The model learns from information it will never have in production.
Use an as-of join: for each labeled event, take the latest feature value at or before the event time.
import pandas as pd
events = pd.DataFrame(
{
"user_id": [1, 1, 2],
"event_time": pd.to_datetime(["2026-03-01", "2026-06-01", "2026-04-15"]),
"label": [0, 1, 0],
}
).sort_values("event_time")
features = pd.DataFrame(
{
"user_id": [1, 1, 2],
"feature_time": pd.to_datetime(["2026-02-20", "2026-05-20", "2026-04-01"]),
"orders_30d": [3, 9, 5],
}
).sort_values("feature_time")
training_set = pd.merge_asof(
events,
features,
left_on="event_time",
right_on="feature_time",
by="user_id",
direction="backward",
)
print(training_set[["user_id", "event_time", "orders_30d", "label"]])User 1's March event gets orders_30d of 3 from February. Their June event gets 9 from May. A plain join on user_id would have attached one value to both rows.
Detecting skew after release
Prevention is not enough, so measure it. Log the exact feature vector the service used for each prediction, along with a request ID. Later, recompute the same features offline from raw data for a sample of those requests and compare. Differences point to a specific feature and often to a specific code path. The monitoring and drift chapters build on these logs, and they also give you a ready-made reference for later comparison with training data.
Common errors
- Fitting the scaler or encoder on the full dataset before the train-test split, which leaks test statistics into training.
- Re-fitting a transformer inside the serving process instead of loading the fitted one.
- Relying on column position instead of column name, so a reordered input silently misaligns features.
- Changing a feature definition without retraining, or retraining without recording which feature code version was used. Store the feature code version with the run in your experiment tracker.
- Testing only with clean records. Production data contains nulls, new categories, and out-of-range values.
Exercise
A churn model scores 0.95 AUC offline but performs near chance in production. The features include orders_30d, joined to labeled events by user_id using the current value from the feature table. Name the most likely problem, and give one fix and one check that would catch it earlier.
Show answer
The likely problem is leakage from a join that is not point-in-time correct. The current orders_30d reflects activity after the labeled event, so training rows contain future information that production requests lack. The fix is an as-of join (for example pd.merge_asof with direction="backward") that takes the latest feature value at or before each event time. A check that would catch it earlier is a review or test that asserts every feature timestamp is not later than its event timestamp, or comparing logged serving features against offline recomputation.