Sub topic 8
Prevention: one transformation, used in both paths
This chapter covers the main fix for duplicated feature logic: write each transformation once and call it from both the training path and the serving path. It assumes you can read pandas and scikit-learn code, know the train, validate, predict workflow, and have seen the earlier chapter on duplicated feature code (code skew). Bundling fitted state into the model artifact comes in the next chapter. This chapter focuses on the code that computes features.
The principle: one definition, two callers
Code skew happens because two people (or two moments) write the same feature twice. The two copies start identical and then drift apart. One gets a bug fix and the other does not. One handles None and the other does not.
The fix is structural. A feature is defined in exactly one function. The training job calls that function on a table of historical events. The serving handler calls the same function on one request. If the two paths cannot disagree about the logic, the logic cannot cause skew.
What goes wrong without sharing
Recall the failing pair from earlier: training fills a missing age with the training mean, and a separately written serving handler fills it with 0.
import pandas as pd
# Training path: missing ages are filled with the training mean (40.0)
train = pd.DataFrame({"age": [30, 40, None, 50]})
train["age"] = train["age"].fillna(train["age"].mean())
# Serving path: a separately written handler fills missing ages with 0
def serve_features(request: dict) -> dict:
return {"age": request.get("age") or 0}
print(train["age"].tolist()) # [30.0, 40.0, 40.0, 50.0]
print(serve_features({"age": None})) # {'age': 0}The model learned that a missing age looks like 40. In production it receives 0. Nothing raises an error, and predictions for those rows are quietly wrong. There is also a second bug in request.get("age") or 0: a real age of 0 is treated as missing. A rewritten handler hides this kind of surprise.
Design rules for a shared transformation
A shared transformation is only useful if both paths can really call it. These rules make that practical.
- Pure functions. The function takes values in and returns values out. It does not read a database, call the clock, or touch global state. Anything it needs, such as the current time or a fitted statistic, is passed as an argument.
- Same input shape. Define the input as a schema both paths can produce, for example a DataFrame with named columns. A single request becomes a one-row DataFrame.
- Same output shape. The function returns the columns in a fixed order with fixed types.
- One home. Put the function in a small package that both the training job and the serving image install, pinned to the same version.
- Parameters, not constants. Values such as "fill with the training mean" are parameters that are fitted once and stored (see the next chapter). They are not literals typed into each caller.
Example: refactoring the age feature
Here is the age example rewritten so both paths call one function. The function has the fill value as an explicit argument, so no caller can invent its own.
import pandas as pd
AGE_FILL = 40.0 # fitted once on training data and stored with the model
def build_features(raw: pd.DataFrame, age_fill: float = AGE_FILL) -> pd.DataFrame:
"""Single definition of the features, used for training and serving."""
out = pd.DataFrame(index=raw.index)
out["age"] = pd.to_numeric(raw["age"], errors="coerce").fillna(age_fill)
out["is_senior"] = (out["age"] >= 65).astype(int)
return out
# Training path: a table of historical rows
history = pd.DataFrame({"age": [30, 40, None, 50]})
train_features = build_features(history)
# Serving path: one request, wrapped as a one-row table
def serve_features(request: dict) -> dict:
row = pd.DataFrame([request])
return build_features(row).iloc[0].to_dict()
print(train_features["age"].tolist()) # [30.0, 40.0, 40.0, 50.0]
print(serve_features({"age": None})) # {'age': 40.0, 'is_senior': 0.0}Three details matter here:
- The serving path builds a one-row DataFrame and reuses the same code. It does not translate the logic into dictionaries.
pd.to_numeric(..., errors="coerce")turns malformed strings into missing values, and then the same fill rule applies. Both paths get the same handling for bad data.AGE_FILLis a stand-in for a fitted value. Hard-coding it in a module is acceptable only as a teaching device.
Choosing where the shared code lives
Teams usually pick one of four approaches. Each trades simplicity against flexibility.
| Approach | How it works | Strength | Main risk |
|---|---|---|---|
| Shared library | A versioned Python package imported by both jobs | Simple, easy to test | Versions can differ between training and serving images |
| Scikit-learn pipeline | Transformers are steps in a `Pipeline` object | Code and fitted state travel together | Tied to Python and scikit-learn |
| Feature store | Features are defined once and served from storage | Handles history and online lookup | More infrastructure to run |
| Shared SQL or dbt model | Batch and online both read a computed table | One definition for aggregates | Online freshness and latency limits |
The next two chapters cover the pipeline and feature store options in detail. Start with the shared library when features are simple row-level transformations.
Common errors
Vectorized code that behaves differently on one row. A function that works on a whole column can change behaviour on a single row. For example, df["x"].fillna(df["x"].mean()) computes the mean from the batch. On a one-row request, the mean is the value itself, or NaN when the value is missing. Any statistic must be a fitted parameter, never computed inside the shared function from whatever data it receives.
Hidden dependence on the batch. Ranking, normalising within a group, or pd.qcut inside the function all depend on the other rows present. At serving time those rows do not exist. Replace them with stored thresholds.
Data type drift. A training table may hold age as float64, while a JSON request holds it as an int or a string. The shared function should coerce types explicitly, as to_numeric does above, rather than rely on whatever each caller sends.
Unpinned dependencies. The same code can give different results under a different pandas or scikit-learn version, for example in rounding or in default arguments. Pin versions in both images and record them with the model.
Silent column reordering. If the function returns columns in an order that depends on input dict order, the model may receive features in the wrong positions. Select columns explicitly by name in a fixed list.
Making the shared function testable
A shared function also gives you one place to test. Test the edge cases that tend to split the two paths: missing values, zero, strings that look like numbers, and extra or missing columns.
import pandas as pd
def test_missing_and_zero_are_distinct():
raw = pd.DataFrame({"age": [None, 0, "35"]})
out = build_features(raw, age_fill=40.0)
assert out["age"].tolist() == [40.0, 0.0, 35.0]
def test_single_row_matches_batch():
raw = pd.DataFrame({"age": [None, 22, 70]})
batch = build_features(raw, age_fill=40.0)
for i in range(len(raw)):
one = build_features(raw.iloc[[i]], age_fill=40.0)
assert one.iloc[0].to_dict() == batch.iloc[i].to_dict()The second test checks the property that matters most: processing a row alone gives the same result as processing it inside a batch. Later chapters extend this idea into full offline and online parity tests.
Limits of this approach
Sharing a function is necessary and not sufficient.
- Different languages. If training is in Python and serving is in Java or a SQL engine, you cannot import the same function. Options are to serve from Python, export the logic to a portable format, or use a feature store that computes features for both sides.
- Different data. The function receives whatever the caller passes. If training reads a warehouse table and serving reads a live API with different units or encodings, the same code still produces different features.
- Latency. A heavy DataFrame operation may be too slow for a request that has a few milliseconds of budget. Measure it before adopting it. If it is too slow, optimise the one shared implementation instead of writing a second one.
- Aggregates over history. Features such as "logins in the last 30 days" need a window of past events. The shared function can define the calculation, but something still has to supply the right window in each path. That is where point-in-time correctness and feature stores come in.
Summary of the working model
Define every feature once. Make the function pure, give it a fixed input and output shape, and pass fitted values in as parameters. Call it from the training job on batches and from the server on single rows. Test that one row alone matches the same row in a batch.
Exercise
A teammate writes a shared function containing df["income"] = df["income"].fillna(df["income"].median()) and calls it from both the training job and the serving handler. Training results look fine, but serving predictions for requests with a missing income look off. Explain why, and describe the fix.
Show answer
The median is computed from whatever data the function receives. In training that is the full table, so the median is stable. In serving the input is one row, so the median of a missing value is NaN, and the fill does nothing (or uses an unrelated value if rows are batched together). The statistic is a hidden duplicate of the logic with different inputs. The fix is to compute the median once on the training data, store it as a fitted parameter, and pass it into the function as an argument (for example income_fill), so both paths use the same number.
Exercise
Name two rules for designing a shared transformation that make it callable from both a batch job and a request handler, and say what each one prevents.
Show answer
Any two of the following. Pure functions with no hidden reads of databases, clocks, or globals prevent the two paths from getting different results because of their environment. A fixed input and output schema, with explicit type coercion and column selection by name, prevents differences from JSON types, dict ordering, or missing columns. Passing fitted values as parameters prevents statistics from being recomputed from the wrong data. Pinning dependency versions in both images prevents the same code from behaving differently under different library versions.