Sub topic 6
Cause 3: Different Data Sources, Schemas, and Missing-Value Handling
This chapter covers the third cause of training-serving skew: the model's inputs come from different places or arrive in different shapes in training and in production. It assumes you know basic Python and pandas, the train, validate, predict workflow, and the idea of a model behind an API or batch job. It also assumes you have read the earlier chapters on duplicated feature code and fit-time state.
How data source skew differs from code skew
In the code skew chapter, two pieces of code computed the same feature differently. Here the code can be identical and the skew still appears, because the raw values it receives differ.
Typical situations:
- Training reads from a data warehouse. Serving reads from an operational database or from the request body.
- Training uses a nightly snapshot. Serving uses the live record, which may be fresher, staler, or not yet populated.
- Training data was cleaned by analysts (duplicates removed, outliers dropped). Serving data is raw.
- A upstream team renames a column, changes a unit, or changes an encoding, and only one path is updated.
The model cannot tell you any of this happened. It receives numbers and returns a prediction.
Source differences
Warehouse tables and online stores often disagree in small, systematic ways.
| Difference | Training side | Serving side | Effect |
|---|---|---|---|
| Units | `income` in dollars per year | `income` in dollars per month | Serving values are about 12 times smaller |
| Encoding | `country` as ISO codes ("DE") | `country` as full names ("Germany") | Category is unseen, so the encoder ignores it |
| Types | `age` as integer | `age` as string from JSON | Casting errors, or silent coercion to NaN |
| Freshness | Feature computed at end of day | Feature read from a cache updated hourly | Serving values lag or lead training values |
| Filtering | Test accounts and bots removed | Test accounts and bots included | Serving population differs from training population |
The categorical case is the most dangerous. With scikit-learn, OneHotEncoder(handle_unknown="ignore") turns an unseen category into an all-zero row. That prevents a crash, which is useful, but it also hides the problem. Every "Germany" request is silently scored as if the country were unknown.
Schema differences
A schema is the agreed list of columns, their types, and their allowed values. Schema skew happens when training and serving disagree on any of these.
Common forms:
- Missing columns. The serving request omits a field that training always had.
- Extra columns. A new field appears. Most pipelines ignore it, but some positional code shifts every later column.
- Reordered columns. A model that takes a NumPy array, not a named DataFrame, reads values in the wrong slots. No error is raised if the types match.
- Type changes. An integer becomes a float, or a number becomes a string.
Reordering is worth a closer look. If the model was trained on [age, income] and a serving handler builds [income, age], a call such as model.predict(np.array([[income, age]])) still runs. The prediction is wrong and nothing warns you. Passing named columns through a fitted scikit-learn Pipeline with a ColumnTransformer avoids this, because it selects columns by name.
Missing-value handling
Missing values are where data source and schema differences turn into numbers the model has never seen. A value can be missing in several distinct ways:
- The key is absent from the request.
- The key is present with
Noneornull. - The value is an empty string,
"N/A",-1, or9999, used by the source system as a placeholder. - The upstream lookup timed out and the feature was never computed.
Training and serving frequently treat these differently. In training, a data scientist reads the table, sees NaN, and fills it with the mean. In serving, a handler reads the request, sees an absent key, and uses a default of 0. This is the example from the start of the tutorial, where the model sees 40 in training and 0 in production.
There is a second, subtler effect. The rate of missingness can differ. If 2% of training rows have no age but 30% of production requests do, because a mobile client no longer sends it, then even a perfectly consistent fill rule produces a very different feature distribution. The model leans on the filled value far more often than it was trained to.
The next example shows a serving handler that normalizes all the missing forms into one, matching the rule fitted in training.
import math
# Sentinel values that the source system uses to mean "no value".
MISSING_SENTINELS = {None, "", "N/A", -1, 9999}
def is_missing(value) -> bool:
if isinstance(value, float) and math.isnan(value):
return True
return value in MISSING_SENTINELS
def clean_age(value, fill_value: float) -> float:
"""Return a numeric age; fill_value is the median saved at training time."""
if is_missing(value):
return fill_value
return float(value)
TRAINING_MEDIAN_AGE = 38.0 # loaded from the saved artifact, not hard-coded in practice
for raw in [41, None, "", "N/A", float("nan"), "52"]:
print(repr(raw), "->", clean_age(raw, TRAINING_MEDIAN_AGE))This keeps the handler consistent for the cases you listed, but it still duplicates logic. The better fix, covered in the prevention chapters, is to apply the same fitted SimpleImputer in both paths. The sentinel list above must also match what the training pipeline treated as missing.
Seeing the problem in a diagram
The diagram shows where the two paths can diverge before any model code runs.
Catching these problems early
You cannot always make the two sources identical, so combine prevention with checks.
Validate the schema at the boundary
Check each serving input against the schema saved with the model. Reject or flag requests with missing columns, wrong types, or values outside the plausible range. The following example uses plain pandas so it runs without extra libraries.
import pandas as pd
EXPECTED = {
"age": ("float64", 0, 120),
"income": ("float64", 0, 10_000_000),
"country": ("object", None, None),
}
KNOWN_COUNTRIES = {"DE", "FR", "US"}
def validate(df: pd.DataFrame) -> list[str]:
problems = []
for col, (dtype, low, high) in EXPECTED.items():
if col not in df.columns:
problems.append(f"missing column: {col}")
continue
if str(df[col].dtype) != dtype:
problems.append(f"{col}: dtype {df[col].dtype}, expected {dtype}")
if low is not None and ((df[col] < low) | (df[col] > high)).any():
problems.append(f"{col}: value outside [{low}, {high}]")
if "country" in df.columns:
unseen = set(df["country"].dropna()) - KNOWN_COUNTRIES
if unseen:
problems.append(f"country: unseen values {sorted(unseen)}")
return problems
request = pd.DataFrame({"age": [41.0], "income": [52000.0], "country": ["Germany"]})
print(validate(request)) # ['country: unseen values [\'Germany\']']Here the check catches the "Germany" versus "DE" mismatch that the encoder would have hidden.
Track the missing rate
Log, per feature, the fraction of requests where the value was missing before filling. Compare it with the training rate. A jump from 2% to 30% is a clear signal even when no other check fails. The detection chapters cover how to log serving features and compare distributions with PSI and the KS test.
Compare sources directly
When you can, join a sample of warehouse records with the same entities from the online store and compare each feature. Differences in units and encoding show up immediately.
Decision criteria
- Reject or fill? For a safety-critical or high-value decision, reject a request with a missing required field and return an error. For a low-stakes ranking, fill with the training value and log it.
- Strict or lenient encoders? Use
handle_unknown="ignore"to keep the service up, but pair it with a validation check that counts unseen categories. - One source or two? Reading training data from the same store that serves production removes a whole class of skew. If you cannot, document the contract between the two sources and test it.
Exercise
A model was trained on a warehouse table where signup_channel holds values such as "web" and "app". After a service update, the online request sends "WEB" and "APP". The pipeline uses OneHotEncoder(handle_unknown="ignore") and no errors appear, but accuracy drops. Explain what is happening, and name two checks that would have caught it.
Show answer
The encoder never saw "WEB" or "APP", so with handle_unknown="ignore" it outputs all zeros for the channel columns. The model scores every request as if the channel were unknown, which is a source and encoding mismatch rather than a code bug. A serving-time schema check that compares categorical values with the training vocabulary would flag the unseen values. Logging the share of unseen categories, or comparing the logged feature distribution with training using PSI, would also show the change.
Exercise
In training, 2% of rows have a missing age and are filled with the median of 38. In production, a client change makes 30% of requests omit age, and the handler also fills with 38. The fill rule matches. Why can the model still perform worse, and what should you monitor?
Show answer
The fill rule is consistent, but the rate of missingness changed. The model now sees the value 38 far more often than during training and relies on a feature that carries less real information. Monitor the missing rate per feature in serving and compare it with the training rate. Adding an age_missing indicator also makes the shift visible.