Sub topic 5
Features and Training-Serving Consistency
This chapter assumes you know basic Python and have trained and evaluated a supervised model. The focus is the boundary between feature engineering and serving. A feature is an input value that a model uses to make a prediction. Feature engineering is the process of creating useful features from raw data.
The Working Model
A model does not usually consume raw business data directly. It consumes a feature vector with a fixed meaning, order, type, and scale.
For example, a fraud model might use:
amount_log: the logarithm of the transaction amounthour: the hour when the transaction occurredmerchant_country_known: whether the country is knowncustomer_age: the customer's age in years
The same transformations must run during training and prediction. If training converts dollars to logarithms but serving sends raw dollars, the model receives values with a different meaning.
This problem is called training-serving skew. It can reduce accuracy without producing an obvious software error.
| Concern | Training | Serving |
|---|---|---|
| Input | Historical raw records | A new raw request |
| Transformation | Feature pipeline | The same feature pipeline |
| Output | Features used to fit the model | Features passed to prediction |
| Main risk | Accidental leakage | Different logic or missing values |
Keep Transformations Together
Put feature transformations and the estimator in one pipeline. A pipeline is an ordered sequence of transformations followed by a model. Saving the pipeline preserves the transformation logic with the model.
The example below creates a numeric feature from a transaction amount and trains a classifier. The prediction function accepts raw records, so callers do not need to reimplement the transformations.
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import FunctionTransformer, StandardScaler
def make_features(records):
amounts = np.array([record["amount"] for record in records], dtype=float)
return np.log1p(amounts).reshape(-1, 1)
training_data = [
{"amount": 5.0},
{"amount": 12.0},
{"amount": 80.0},
{"amount": 120.0},
]
labels = [0, 0, 1, 1]
model = Pipeline([
("features", FunctionTransformer(make_features, validate=False)),
("scale", StandardScaler()),
("classifier", LogisticRegression(random_state=42)),
])
model.fit(training_data, labels)
new_transaction = [{"amount": 25.0}]
print(model.predict(new_transaction)[0])The pipeline applies log1p and scaling both when fitting and when predicting. In a deployed system, save this complete pipeline rather than saving only the classifier.
Common Errors
- Computing a feature with information that was unavailable at prediction time. This is data leakage, and it makes evaluation look better than real performance.
- Fitting a scaler or encoder separately on serving data. Fitted transformations must use training-time parameters.
- Changing feature order or names between training and serving.
- Handling missing values differently in the two environments.
- Reimplementing feature logic in two programming languages and allowing the implementations to diverge.
- Omitting the feature code, schema, or dependencies from the model artifact.
Exercise
Why should a scaler be fitted during training and reused during serving?
Show answer
Its means and standard deviations define the transformation expected by the model. Fitting it again on live data changes that transformation and can create training-serving skew.