Sub topic 14
Detecting Training-Serving Skew with PSI and the KS Test
This chapter assumes basic Python, pandas, histograms, and the usual train-validate-predict workflow. It also assumes that your service can log the feature values it sends to the model.
Compare the values the model actually sees
Training-serving skew appears when production features differ from the features used to train a model. Distribution checks help detect this problem by comparing two samples:
- Reference sample: feature values from the training set, usually after the same filtering and feature construction steps used for training.
- Serving sample: feature values logged immediately before production inference.
Log the model input rather than only the raw API request. A feature may change during parsing, imputation, encoding, scaling, or default handling.
Population Stability Index
The Population Stability Index (PSI) measures how much a serving distribution differs from a reference distribution. First, divide the reference values into bins. Then compare the fraction of observations in each bin.
For bin \(i\), PSI is:
(actual_i - expected_i) \times \ln(actual_i / expected_i)The total PSI is the sum across bins. Common rules of thumb are:
| PSI value | Typical interpretation |
|---|---|
| Below 0.10 | Little evidence of change |
| 0.10 to 0.25 | Investigate the feature |
| Above 0.25 | Large change that needs action |
These are operating guidelines, not universal laws. A small but important feature can deserve investigation even when its PSI is low. Always inspect the bin counts and the underlying records.
import numpy as np
from scipy.stats import ks_2samp
def psi(reference, actual, bins=10):
"""Measure the change from reference values to actual values."""
reference = np.asarray(reference, dtype=float)
actual = np.asarray(actual, dtype=float)
edges = np.unique(
np.quantile(reference, np.linspace(0, 1, bins + 1))
)
if len(edges) < 2:
return 0.0
edges[0], edges[-1] = -np.inf, np.inf
expected = np.histogram(reference, edges)[0] / len(reference)
observed = np.histogram(actual, edges)[0] / len(actual)
expected = np.clip(expected, 1e-6, None)
observed = np.clip(observed, 1e-6, None)
return float(np.sum((observed - expected)
* np.log(observed / expected)))
rng = np.random.default_rng(7)
training_age = rng.normal(40, 10, 5000)
serving_age = rng.normal(0, 1, 5000) # possible default-value bug
print(f"PSI: {psi(training_age, serving_age):.3f}")
result = ks_2samp(training_age, serving_age)
print(f"KS statistic: {result.statistic:.3f}")
print(f"KS p-value: {result.pvalue:.3g}")The Kolmogorov-Smirnov test
The Kolmogorov-Smirnov (KS) test compares two numeric distributions without requiring fixed bins. Its statistic is the largest vertical distance between their cumulative distribution functions. A large statistic means the samples differ.
The p-value estimates how surprising that difference would be if both samples came from the same distribution. With very large samples, tiny practical differences can produce a small p-value. Use the statistic and a practical threshold, not the p-value alone.
Run checks per feature and per meaningful time window. Exclude identifiers, group correlated features when investigating, and compare equivalent populations. For example, compare weekday traffic with weekday traffic if the training data contains only weekdays.
From alert to action
An alert is a starting point, not proof of a model defect. Check whether:
- The serving sample uses the same feature version and units as training.
- Missing values, unknown categories, and defaults changed.
- The comparison windows contain equivalent users and time periods.
- A deployment or upstream data change explains the difference.
- Model quality or business outcomes also changed.
If the feature pipeline is wrong, stop or roll back the affected release and fix the transformation. If the production population genuinely changed, evaluate the model on recent labeled data before deciding whether retraining is appropriate.
Exercise
A numeric feature has PSI 0.31, but the KS test has a moderate statistic and model accuracy has not changed. What should you do first?
Show answer
Inspect the shared bins, serving logs, missing-value rates, units, and population definitions. Confirm that the comparison is valid before rolling back or retraining.