Data, features and production ML: preprocessing, encodings, point-in-time features, skew, drift and operations

  • Advanced
  • 1 h 40 min
  • Lesson 3 of 3 in Evaluation, statistics and data
  • Last verified

Open slides(27 slides)

Before you start

You will be able to

  • Treat missing values by mechanism (MCAR, MAR, MNAR) with imputation and a missing indicator, handle outliers, scaling and skew, and fit every learned statistic on the training rows only.
  • Choose an encoding for a categorical feature (one-hot, ordinal, target, hashing, embedding), explain why target encoding leaks unless it is out-of-fold and smoothed, and say when a feature cross helps.
  • Build lag, rolling and aggregate features that use only information available at prediction time (point-in-time joins), and keep training and serving identical with one pipeline definition, logging and golden tests.
  • Tell data drift, label shift and concept drift apart, compute PSI by hand and a KS statistic, say what each can and cannot see, and monitor a model whose labels arrive late.
  • Choose retraining triggers and a safe rollout, version data, code and models so a result can be reproduced, and debug a model that works in the notebook but fails in production in a sensible order.

Concept

The first lesson of this module made one score honest, and the second said how much to trust it. This lesson covers the layer underneath both: the data and features the model sees, and what happens to them after the model ships. A model is a function of its inputs. If the inputs are built differently in training and in production, or drift away from what the model learned, a good validation score stops meaning anything.

QuestionTool in this lesson
Why is this value missing, and what do I put there?Missing-data mechanisms, imputation, a missing indicator
One huge value is ruining my scalingRobust scaling, clipping, log transforms
How do I feed a category with 5,000 levels to a model?One-hot, ordinal, target (out-of-fold), hashing, embeddings
Can I use “orders in the last 30 days”?Point-in-time joins, past-only windows
The model was great offline and is poor liveTraining-serving skew, pipelines, logging, golden tests
Has the world changed under the model?Data, label and concept drift, PSI, KS
When do I retrain, and how do I roll it out?Triggers, shadow and canary, versioning, reproducibility

Why It Matters

Most production failures of ML systems are not model failures. They are data failures: a column that is null in production, a feature computed one way in SQL and another way in the serving code, a window that quietly includes tomorrow, a population that moved. The paper on hidden technical debt in ML systems lists data dependencies, hidden feedback loops and changes in the external world among the risks that are specific to ML (Sculley et al., 2015). Google’s engineering guide names a closely related problem “training-serving skew” (Rules of ML). Interviewers for senior roles ask how you would debug a model that works in the notebook and fails in production because the answer shows whether you have run one (common industry pattern).

Mental Model

Think of a model as a contract about its inputs. Training signs the contract: “inputs look like this, are built like this, and mean this”. Production must keep it. Four questions check the contract, and the lesson follows them in order:

  1. Is each input clean and honest? Missing values, outliers, labels you can trust. (Sections on data quality, missing data, scaling.)
  2. Is each input legal at prediction time? No target information, no future information. (Encoding, point-in-time features.)
  3. Is each input built the same way in training and serving? (Skew, pipelines, feature stores.)
  4. Is each input still distributed the way it was? (Drift, monitoring, retraining.)
Diagram: Production ML is a loop, not a line.

drift or decay

Problem and metric

Data and labels

Features

Train and validate

Register and deploy

Monitor

Diagram summary: Production ML is a loop, not a line. Monitoring feeds back into data collection and retraining, so every step before deployment must be repeatable and every step after it must be observable.

Data quality and labels

Before any technique, check the data itself. Cheap checks catch most pipeline failures: the schema (columns and types), null rates per column, value ranges and units, duplicate rows, and the category list. Run them at training time and again at serving time, and fail loudly instead of passing a default along (common practice).

Labels deserve the same suspicion as features. Three things go wrong:

  • The label is noisy. If a fraction of labels is wrong, even a perfect model is scored lower than it deserves. In the script (section 11), with 10% of labels flipped at random, a model that is always right is scored 0.902. Noise also sets a ceiling on what you can learn, so a gap to 100% is not always a model problem.
  • The label is defined differently in production. “Churned” meaning no purchase in 30 days in training and no login in 60 days in a dashboard is a mismatch, not noise.
  • The label arrives late or only for some rows. These two are covered under label delay and selective labels below.

Where humans label, measure how often two labellers agree and write the labelling rules down before collecting more (common practice).

Missing data

Three mechanisms

The right treatment depends on why a value is missing. The standard vocabulary has three cases. The idea of data “missing at random” and the conditions under which the missingness process can be ignored come from Rubin (1976); the three-way naming below is the usual textbook use.

MechanismMissingness depends onExampleConsequence
MCAR, missing completely at randomNothingA sensor drops 30% of readings at randomObserved rows are a fair sample. Little bias, just less data
MAR, missing at randomOther columns you observeOlder users skip a field more often, and age is recordedObserved rows are biased, but the bias can be corrected using the observed columns
MNAR, missing not at randomThe missing value itselfHigh earners skip the income questionObserved rows are biased in a way the data cannot correct

The script (section 1) builds all three for a variable with true mean 50.06 and standard deviation 9.94. Between 29% and 35% of the values go missing in each case:

MechanismObserved meanMean-imputed mean and sdImputed by group of an observed column: mean
MCAR (30% at random)50.0950.09, sd 8.3550.10
MAR (depends on an observed covariate)47.5847.58, sd 7.7650.00
MNAR (depends on the value itself)46.9746.97, sd 7.6748.36

Three lessons sit in this table. Under MCAR the observed mean is fine, but filling with the mean shrinks the spread (sd 8.35 against the true 9.94), which understates variance. Under MAR the mean is wrong (47.58), and using the observed covariate to impute fixes it (50.00). Under MNAR the observed mean is wrong and the covariate helps only partly (48.36): nothing in the observed data says by how much the missing values differ, so you need outside knowledge or a sensitivity analysis. You cannot tell MAR from MNAR by looking at the observed data alone, which is why you ask how the data was collected.

Imputation and missing indicators

Imputation fills a gap with a learned value. The simple ones are the column mean, median (robust to outliers) and most frequent value (for categories). Model-based ones predict the gap from other columns: scikit-learn offers IterativeImputer, which models each feature with missing values as a function of the others (marked experimental in its documentation), and KNNImputer, which averages the nearest rows that have a value (scikit-learn, Imputation). Start simple. A fancier imputer is one more thing to fit, version and serve.

A missing indicator is a 0/1 column that says “this value was missing”. It matters because missingness is often a signal. In the script (section 1), a lab test is missing for 70% of healthy patients and 20% of sick ones. The disease rate is 0.109 where the test is missing and 0.538 where it was taken. Fill in the mean and drop the indicator, and that signal is gone. SimpleImputer(add_indicator=True) adds the indicator columns for you (same documentation page).

Tree libraries often need no imputation at all: XGBoost and scikit-learn’s histogram boosting learn a branch direction for missing values; the trees lesson has the details. Linear models, neural networks and distance-based models cannot take NaN, so they need an imputer.

SituationReasonable default (common practice)
Numeric, few missing, skewedMedian plus an indicator
CategoricalMost frequent value, or a separate “missing” category, plus an indicator if the rate is material
Missingness is a known process (lab not ordered)Keep the indicator, think about the meaning of the fill value
Tree ensembleLeave NaN, let the library route it, still consider an indicator
Missing rate very highAsk whether the column is usable at all

Fit on training data only

Every imputer mean, scaler mean, category list and encoding is a statistic learned from data. Learn it from the training rows only, then apply it unchanged to validation, test and live rows. If the test rows help choose the statistic, information has crossed the split. The first lesson of this module calls this preprocessing leakage.

It has a second cost beyond optimism. A scaler fitted on everything hides a shift that should be visible. In the script (section 2) the training feature has mean -0.030 and the test feature mean 1.529, a clear shift. Scaled with training statistics, the test mean stays at 1.580, so the shift shows. Scaled with statistics fitted on train and test together, it looks like 0.617, a mild offset, and the test sd shrinks to 0.793. A median imputer shows the same effect: -0.028 from the training rows against 0.731 if the test rows are included.

Rule: fit on training, transform everywhere else. The section on pipelines shows how to make this automatic.

Outliers, scaling and transforms

Outliers are values far from the rest. First ask whether they are errors (a unit mix-up, a sentinel such as 9999 for “unknown”) or real rare events (a large transaction). Errors get fixed or treated as missing. Real rare values are information and should not be deleted (common practice).

Scaling puts features on a comparable range. It matters for models that use distances or gradients on raw features: linear and logistic regression with regularisation, k-nearest neighbours, SVMs and neural networks (common practice; see the linear models lesson for why gradient descent and penalties depend on scale). It does not matter for trees, because a split compares values only by order and any monotonic rescaling leaves the order unchanged (derived here).

Standardising (subtract the mean, divide by the standard deviation) is sensitive to outliers. The script (section 4) takes 99 ordinary values (mean 10, sd 2) and adds one value of 1,000. The scaled ordinary values had sd 1.000 before and 0.020 after: the single outlier inflates the standard deviation to 98.49 and squeezes everyone else into a sliver near zero. Scaling with the median and the interquartile range keeps the ordinary values spread out (sd 0.794) and lets the outlier stand out (390.6). scikit-learn’s RobustScaler does this, and its documentation recommends it when the data has many outliers (scikit-learn, Preprocessing). Clipping extreme values to a percentile is another common choice.

Skewed features can be pulled in with a transform. A lognormal sample in the script has mean 1.64 against median 0.99 and skewness 5.15. After taking logs the skewness is 0.02. Power transforms (Yeo-Johnson, Box-Cox) and the quantile transform do this in a learned way; the scikit-learn documentation warns that power transforms work well for some distributions and are ineffective for others, and that the quantile transform distorts correlations and distances, so look at the data before and after. These transforms are statistics too: learn them on the training rows.

Encoding categorical features

Models need numbers, and the encoding decides what the model can learn. Choose by cardinality (number of levels) and order:

EncodingHowUse whenCost
One-hotOne 0/1 column per levelFew levels, no orderWidth grows with levels. 500 levels is 500 columns
OrdinalInteger codes by a meaningful order (size S, M, L)The order is realOn nominal levels it invents an order a linear model will use
Target (mean) encodingReplace the level with the mean of the target for that levelMany levels, a supervised signalLeaks the label unless out-of-fold and smoothed
Frequency or countReplace the level with how often it occursFrequency itself is informativeDifferent levels with equal counts collide
HashingHash the level into a fixed number of bucketsHuge or open-ended vocabularies, memory limitsCollisions mix unrelated levels
EmbeddingA learned dense vector per level, trained with a neural networkVery many levels, enough data, a neural modelNeeds training data per level and cannot represent a never-seen level meaningfully (common practice)

Unseen levels at serving time need a plan. The script’s one-hot encoder gives an unseen level a row of zeros. In scikit-learn, OneHotEncoder(handle_unknown="ignore") does the same, and the documentation also describes grouping rare levels into an “infrequent” category with min_frequency or max_categories (Preprocessing).

Hashing keeps the width fixed without a vocabulary. The original feature-hashing paper presents it for very large multitask problems and derives exponential tail bounds showing that the interference between random subspaces is negligible with high probability (Weinberger et al., 2009). The cost is collisions, and the script (section 3) puts a number on it: 500 categories hashed into 256 buckets use 219 buckets, with 438 categories sharing a bucket with another and a largest bucket of 7; at 1,024 buckets 172 still share a bucket. Choose the bucket count from the collision rate you can accept.

Cyclical features such as hour of day need care. As a number, hour 23 and hour 0 are 23 apart although they are neighbours. Encoding the hour as a point on a circle, (sin⁡2πh/24,cos⁡2πh/24)(\sin 2\pi h/24, \cos 2\pi h/24), fixes it: the distance between 23 and 0 is 0.2611, the same as between 0 and 1, and the distance between 0 and 12 is 2.0000.

Target encoding and its leakage

Target encoding replaces a level with the mean of the target for that level. It is powerful for high-cardinality features, and it is the most common way to leak a label by accident. Written with smoothing:

x^c=sc+m yˉnc+m\hat{x}_c=\frac{s_c+m\,\bar{y}}{n_c+m}

SymbolMeaning
scs_cSum of the targets in level cc
ncn_cNumber of training rows in level cc
yˉ\bar{y}Mean of all training targets (the prior)
mmSmoothing strength, a number of pseudo-rows at the prior

This is the same blend as scikit-learn’s TargetEncoder, which weights the level mean by nc/(m+nc)n_c/(m+n_c) and the overall mean by the rest (Preprocessing). A level with few rows is pulled to the prior. In the script (section 3), with prior 0.3220 and m=10m=10: a level with one row (target 1) has raw mean 1.000 and smoothed value 0.384, a level with 10 rows at mean 0.800 becomes 0.561, and a level with 100 rows at 0.800 becomes 0.757. Smoothing trusts a level in proportion to its evidence.

Why it leaks. If each row’s own target is inside its own encoding, the feature contains the label. A level with one row is the extreme case: the encoding is that row’s target. The script (section 3) makes the labels independent of the category on purpose, so there is nothing to learn, and measures the AUC of the encoded feature used as a score:

SettingTrain, in-sampleTrain, out-of-foldHeld-out test
No smoothing0.7700.5010.489
Smoothing m=10m=100.7650.4970.489

In-sample the feature looks predictive (about 0.77) although it carries no information, because the model is rewarded for memorising levels. Out-of-fold and on new rows the AUC is about 0.5. A downstream model trained on the in-sample feature would lean on it and then fail on new data. When each category has its own true rate (0.10 to 0.50), the out-of-fold feature keeps a real signal: held-out AUC 0.562 without smoothing and 0.570 with it, against 0.655 for the true rates. Smoothing helped only a little here, so it is a safeguard for rare levels, not a fix for leakage.

The cure is out-of-fold encoding. Split the training rows into folds. Encode each fold with the statistics of the other folds, so a row’s own target never enters its own value. For the test and live rows, use the encoding from all training rows. scikit-learn’s TargetEncoder.fit_transform does the cross fitting internally, its documentation states that fit(X, y).transform(X) is not the same as fit_transform(X, y), and it encodes categories unseen in fitting with the overall target mean. Use fit_transform on training data and transform on everything else. The homework builds this by hand.

Leave-one-out is not a safe shortcut. It is tempting to encode each row with the mean of the other rows of its level, so the row’s own target is removed. That passes the simple check of the previous paragraph and still leaks, because within a level the value (sc−yi)/(nc−1)(s_c-y_i)/(n_c-1) goes down when yiy_i goes up, so it encodes the row’s own label through the shift. In the script (section 3), with one constant level and 2,000 rows, the leave-one-out feature has AUC 0.000 on the training rows (every positive gets a lower value than every negative), against 0.473 for 5-fold out-of-fold. With 400 independent levels the two effects roughly cancel (0.495 against 0.501), which is luck, not safety. The CatBoost paper is about this family of problems: its abstract describes a special kind of target leakage and a prediction shift in boosting, and an algorithm for categorical features designed to counter it (Prokhorenkova et al., 2018). Use out-of-fold folds.

Interactions and crosses

A feature cross is a new feature built from two or more features, such as the product x1x2x_1x_2 or the pair (country, device). Linear models are additive: they cannot represent an effect that exists only when two features combine. The script (section 5) labels a row positive when x1x2>0x_1x_2>0 (with 5% of labels flipped). The best single sign rule on x1x_1 reaches 0.500 accuracy and on x2x_2 0.504, while the rule on the cross x1x2x_1x_2 reaches 0.952. Neither input alone says anything, and their combination says nearly everything.

Trees and neural networks can learn interactions themselves, so crosses matter most for linear models and for very simple pipelines (common practice). A cross of two high-cardinality features has a huge number of levels, which brings back the hashing and target-encoding questions above.

Time, lag and aggregate features

Behaviour over time is often the strongest signal: counts, sums and averages over a window (orders in the last 30 days), lags (value one week ago), recency (days since the last event), and calendar parts (hour, day of week, with sin/cos for cycles). These features are also where leakage hides, because the same raw log can answer a question at any time.

Point-in-time correctness

The rule: a feature for a prediction made at time tt may use only information that existed at time tt. Two ways to break it:

  • A window that reaches past tt. A “last 30 days” feature computed for the whole month includes days after the prediction.
  • A join to the latest value. Joining a user’s current profile to a historical event gives that event a value from the future.

The script (section 6) simulates churn prediction. Customers who will churn stop their activity after time tt. Counting events in the 30 days before tt gives AUC 0.773. Counting seven more days past tt as well gives AUC 0.921, a better score from information that does not exist at prediction time. Nothing in the code looks wrong; the only symptom is a score too good to be true, and a collapse in production.

A point-in-time join gives every labelled event the latest feature value that was available at the event’s timestamp, and nothing later. The homework function point_in_time_join implements it, with an optional time-to-live (TTL) that ignores values too old to trust. Take feature rows ("u1", 1, 3), ("u1", 5, 4), ("u1", 9, 10) as (key, timestamp, value). An event for u1 at time 8 gets 4, the value from time 5, not the 10 from time 9. An event at time 0 gets nothing. An event at time 100 gets 10, or nothing if a TTL of 3 says that value is too old. Feast’s documentation describes the same idea: scanning backward from each entity’s timestamp, with a TTL that is relative to each timestamp and not to the time of the query (Feast, Point-in-time joins).

For rolling features the same rule means a past-only window: position ii uses the values before ii, never ii itself. The homework function past_rolling_mean returns [None, 3.0, 4.0, 4.0] for the series [3, 5, 4, 10] with a window of three. A window that included the current value would give 6.33 at the last step and carry the target in.

Two related traps: a feature that is computed later than the prediction, such as a nightly batch that is not ready when the live request arrives, and a value that is later corrected (backfilled) in the warehouse so the training table holds the corrected number while serving saw the first one. Keep the first-seen value or its timestamp.

Training-serving skew

Training-serving skew is a difference between performance during training and performance during serving. Google’s guide gives three causes: a discrepancy between how data is handled in the training and serving pipelines, a change in the data between training and serving, and a feedback loop between the model and the algorithm (Rules of ML). The first is a bug you can prevent. The other two are covered in the drift and retraining sections.

Diagram: When training and serving compute features in two places, the two versions drift apart.

Online serving

Offline training

different logic, freshness, null handling

Batch SQL or pandas features

Train

Service code re-implements features

Predict

One feature definition
shared by both paths

Diagram summary: When training and serving compute features in two places, the two versions drift apart. One shared definition, in a library or a feature store, removes the second implementation.

The script (section 7) shows the effect of one small difference. A rule flags a value below 85 as fraud. Offline, the 10% missing values were filled with the training median (100.0), so they were not flagged: 2,801 flagged rows, precision 0.831, recall 0.684. In serving, the missing values arrived as 0 and were flagged: 4,831 flagged rows, precision 0.556, recall 0.788. The model did not change. The null handling did. Other usual sources are different aggregation windows, time zones, library versions, stale lookups, and a feature that exists in the warehouse but not at request time.

Defences, in the order they pay off:

  1. Reuse code. Rule 32 of the Google guide: re-use code between the training pipeline and the serving pipeline whenever possible, and avoid different programming languages for the two, since that makes sharing code nearly impossible.
  2. Log what you served. Rule 29: the best way to make sure you train like you serve is to save the features used at serving time and use them for training; if that is too much, log a small fraction so you can check that serving and training agree.
  3. Golden tests. Keep a few fixed inputs with known feature vectors and run them through both paths on every change (common practice).
  4. Monitor input and feature distributions in production against training (drift sections).

Pipelines keep the steps together

A scikit-learn Pipeline chains transformers and a final estimator into one object. Its documentation lists three purposes, including safety: pipelines help avoid leaking statistics from test data into the trained model in cross-validation, by ensuring the same samples are used to train the transformers and predictors. A ColumnTransformer applies different steps to different columns inside the same pipeline; by default the remaining columns are dropped (remainder="drop") (scikit-learn, Pipelines and composite estimators).

Python

from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

numeric = Pipeline([
    ("impute", SimpleImputer(strategy="median", add_indicator=True)),
    ("scale", StandardScaler()),
])
prep = ColumnTransformer([
    ("num", numeric, ["age", "income"]),
    ("cat", OneHotEncoder(handle_unknown="ignore"), ["city", "device"]),
])
model = Pipeline([("prep", prep), ("clf", LogisticRegression(max_iter=1000))])

model.fit(X_train, y_train)           # every statistic is learned here, on training rows only
scores = model.predict_proba(X_new)   # serving applies the same fitted steps

This snippet is not run by the lesson script, which uses only the standard library. The point is the shape: preprocessing and model live in one fitted object, so cross-validation refits the imputer, scaler and encoder inside each fold, and the object you save is the object you serve. It fixes statistic leakage and the “two code paths” problem for features that this pipeline computes. It does not fix features computed outside it, such as joins and windows done in SQL, which is why point-in-time joins and logging are separate defences.

Feature stores at overview level

A feature store is a system that defines each feature once and serves it both for training (as a point-in-time-correct table) and for low-latency lookup at serving time. Its promises are one definition, point-in-time joins and reuse across teams. The costs are real: another system to run, a latency budget for online lookups, and feature definitions that become a shared contract. A small team with a few features is often better served by a shared library and logging (common practice). Feature stores do not remove the need to monitor.

Drift

A model is trained on a snapshot. The world keeps moving. Drift is the general word for the data a model sees moving away from the data it learned from.

Three kinds of drift

TypeWhat changesExampleDetect with
Data (covariate) driftP(X)P(X) changes while P(y∣X)P(y\mid X) stays fixedA new merchant mix, a new device typeCompare input distributions to training: PSI, KS
Label (prior) shiftP(y)P(y) changes while P(X∣y)P(X\mid y) stays fixedFraud rate jumps in a holiday seasonPredicted-positive rate against the expected base rate
Concept driftP(y∣X)P(y\mid X) changesFraudsters adapt, the economy changes default behaviourPerformance on labelled data, which needs labels

Concept drift is defined as a change over time in the relationship between the input data and the target variable (Gama et al., 2014). The distinction matters because the responses differ (common practice): data drift may need nothing (the model can still be right in the new region) or new data for the new region, a pipeline bug needs a fix and no retraining, and concept drift needs new labels and retraining. Real changes often mix the three. Note that under label shift the input distribution P(X)P(X) also moves, so input PSI can fire too; the kinds are definitions, not clean diagnoses.

Diagram: The three kinds of drift are visible in different places.

Model decays

Data drift: P of X changes

Label shift: P of y changes

Concept drift: P of y given X changes

See it in inputs: PSI, KS, null rates

See it in scores: predicted positive rate

See it only in labelled outcomes

Diagram summary: The three kinds of drift are visible in different places. Inputs reveal data drift, scores hint at label shift, and only labelled outcomes reveal concept drift.

PSI and the KS statistic

The Population Stability Index compares a reference distribution (usually training) with a current one over BB bins:

PSI=∑i=1B(ai−ei)ln⁡aiei\mathrm{PSI}=\sum_{i=1}^{B}\left(a_i-e_i\right)\ln\frac{a_i}{e_i}

SymbolMeaning
eie_iShare of the reference data in bin ii (expected)
aia_iShare of the current data in bin ii (actual)
BBNumber of bins, usually cut at the reference quantiles

By hand. Expected shares (0.5, 0.5) and actual shares (0.3, 0.7):

PSI=(0.3−0.5)ln⁡0.30.5+(0.7−0.5)ln⁡0.70.5=0.1022+0.0673≈0.1695\mathrm{PSI}=(0.3-0.5)\ln\frac{0.3}{0.5}+(0.7-0.5)\ln\frac{0.7}{0.5}=0.1022+0.0673\approx 0.1695

Each term is zero or positive because (a−e)(a-e) and ln⁡(a/e)\ln(a/e) always have the same sign, so the index is never negative. It is zero only when every share matches, and it is symmetric in the two distributions. A bin with a zero share makes ln⁡(a/e)\ln(a/e) blow up, so shares are floored at a small ε\varepsilon; the choice matters. In the script (section 8) a new category with 10% of current rows and none in the reference gives PSI 0.708 with ε=10−4\varepsilon=10^{-4} and 1.170 with ε=10−6\varepsilon=10^{-6}.

The usual reading is a rule of thumb: below 0.1 stable, 0.1 to 0.25 worth watching, above 0.25 a major shift (common practice; a convention, not a derived law). The script shows three reasons to treat the numbers with care.

  • Sample size sets a noise floor. With no drift at all, a second-order expansion gives an expected PSI of about (B−1)(1/na+1/ne)(B-1)(1/n_a+1/n_e) (derived here, with nan_a and nen_e the current and reference sample sizes). Against 50,000 reference rows and 10 bins, the simulation gives a mean PSI of 0.0950 for 100 current rows (95th percentile 0.2029), 0.0087 for 1,000 rows and 0.0011 for 10,000. A daily window of 100 rows can cross 0.1 by chance, while a window of 10,000 practically never does (95th percentile 0.0019).
  • Bin choice matters. The same drifted sample (mean +0.5, sd 1.2) gives PSI 0.2060 with 5 bins, 0.2417 with 10 and 0.2669 with 20. Fix the bins from the reference and keep them.
  • PSI is blind to what the bins do not see. It compares marginal distributions of one feature at a time.

The Kolmogorov-Smirnov (KS) statistic is the largest vertical gap between two empirical CDFs:

D=max⁡x∣Fa(x)−Fb(x)∣D=\max_x\left|F_a(x)-F_b(x)\right|

It needs no bins. SciPy’s ks_2samp tests the null hypothesis that the two samples come from the same distribution and assumes continuous data (SciPy, ks_2samp). In the script (section 8), against 50,000 reference rows: no drift gives PSI 0.0017 and KS 0.0078; a mean shift of +0.1 gives 0.0093 and 0.0407; a shift of +0.5 gives 0.2500 and 0.2045; a pure spread change (sd times 1.5, same mean) gives 0.1979 and 0.1029. Both see the spread change even though the mean did not move.

KS has the usual large-sample problem. A mean shift of just 0.02 with 100,000 rows on each side gives PSI 0.00033 but KS 0.0076, above the approximate 5% critical value 1.3582/n=0.00611.358\sqrt{2/n}=0.0061 (the standard asymptotic approximation, common practice). A test can be “significant” for a shift nobody cares about. Pair a distance with a threshold chosen for cost, as in the statistics lesson, where significance is not importance.

For concept drift the inputs can stay put. In the script, the input PSI is 0.0003 while the rule “x above 0” falls from accuracy 1.000 to 0.659 because the true rule moved to “x above 1”. No input statistic can see that. Only labels can.

Monitoring and label delay

Monitor four layers, cheapest first: data quality (schema, null rates, ranges, category list), feature drift (PSI or KS per feature, against training), score drift (the distribution of predictions and the positive rate), and performance once labels arrive. Latency, error rates and the share of requests served by a fallback belong on the same dashboard.

Labels often arrive late: a chargeback weeks later, a readmission after 30 days. Until they arrive, the newest cohorts look better than they are. The script (section 9) draws label delays with a mean of 20 days for a 5% positive rate. A cohort aged 14 days has only 0.510 of its positives labelled, so the observed positive rate is 0.0253 against the true 0.0496. At 30 days it is 0.779 labelled (rate 0.0387), at 60 days 0.949 and at 90 days 0.990 (rate 0.0491). A dashboard that reports “accuracy over the last 7 days” without this correction measures label maturity, not model quality.

What to do: use the leading indicators now (input and score drift, review outcomes, any early labels), report true metrics by cohort (by the date the prediction was made) once labels have matured, and compare cohorts of the same age (common practice).

Retraining, versioning and reproducibility

When to retrain. Four triggers are common: a schedule, a drift threshold, a performance drop on matured labels, and enough new labelled data (common practice). Each trades cost against staleness. The script (section 10) is a toy: the true decision boundary moves by 0.1 per week for 40 weeks, a model learns the boundary at training time, labels arrive two weeks late and each retrain uses the boundary as it was two weeks earlier.

PolicyMean accuracyWorst weekRetrains
Never retrain0.6090.4870
Every 10 weeks0.9080.6733
When last known accuracy is below 0.950.9520.85415

The trigger policy is best on accuracy and costs 15 retrains, each with its own validation and rollout work. The schedule is cheaper and worse in the gaps. This toy only shows the shape of the trade-off; real costs, label delay and drift speed decide.

Safe rollout. Validate offline, then run the new model in shadow mode (it scores live traffic but nothing acts on it), then a canary (a small share of traffic with guardrail metrics), then ramp up, with a one-step rollback and a fallback such as the previous model or a simple rule (common practice). For comparing the two with confidence, see the A/B sections of the statistics lesson.

Feedback loops and selective labels. The model’s decisions shape the data it will be retrained on. If a lender approves only applicants the model scores highly, repayment outcomes exist only for approved applicants, and a model retrained on them never sees the people it rejected. Sculley et al. list hidden feedback loops among the ML-specific risks, and Google’s guide names the feedback loop between model and algorithm as a source of skew. Keep an exploration or hold-out slice where decisions are not driven by the model, so outcomes exist for every kind of case (common practice).

Version everything that can change a result. A model is the product of code, data, configuration and random seeds. Record: the code version, the exact training data snapshot (or a hash of it), the feature definitions, the library versions, the hyperparameters and the seeds, and store them with the model artifact in a registry (common practice). The script (section 11) shows the idea: a hash of a canonical dump of a dataset snapshot is stable (the same snapshot gives the same hash) and changes when one cell changes (62ebb76364d6... against 43802cef968d...). Fixed seeds give repeatable draws. Reproducibility lets you answer “what changed?” when behaviour changes, and “can we get the old model back?” when a rollout fails.

Debugging a model that fails in production

When a model that validated well misbehaves, work from the cheapest, most common cause to the most expensive. Check the model last.

Diagram: Seven checks, ordered by cost and frequency: input validity, then skew, then leakage in the old evaluation, then drift, then label...

Production metric drops

1. Inputs valid?
schema, nulls, units, ranges

2. Skew?
served features against training features for the same case

3. Leakage in the original evaluation?
future information, same-entity split

4. Drift?
PSI per feature, time window

5. Label or definition mismatch?
what counts as positive

6. Silent fallbacks, timeouts, wrong artifact version

7. Only then: a real concept change. Retrain or redesign

Diagram summary: Seven checks, ordered by cost and frequency: input validity, then skew, then leakage in the old evaluation, then drift, then label definitions, then serving mechanics, and only then the model.

Why this order. Invalid inputs and skew are usually the cheapest to check and, in practice, a frequent cause (common practice), and a leaky evaluation means the offline number was never real, so retraining would not help. Rank features by PSI between two time windows to find where the data moved, then decide for each whether to retrain, fix the pipeline or ignore it.

Code

This standard-library script produced every number in the lesson that is computed here. The first part is the helper code from homework/solution.py (without docstrings); the rest is the experiments. It has fixed seeds and runs in about 1 second (Python 3.14.6, run with python3 -I). Another Python version may draw different random numbers, which moves the simulated figures slightly but not their pattern. The closed-form numbers (the hand PSI, sin/cos distances, smoothing arithmetic, hash digests) do not depend on the version.

Python

import math
from bisect import bisect_right

EPS = 1e-12


def _is_missing(v):
    return v is None or (isinstance(v, float) and math.isnan(v))


def _mean(xs):
    return sum(xs) / len(xs)


class Imputer:
    def __init__(self, strategy="mean"):
        if strategy not in ("mean", "median", "most_frequent"):
            raise ValueError("strategy must be 'mean', 'median' or 'most_frequent'")
        self.strategy = strategy
        self.fill_ = None

    def fit(self, values):
        present = [v for v in values if not _is_missing(v)]
        if not present:
            raise ValueError("no observed values to learn from")
        if self.strategy == "mean":
            self.fill_ = _mean(present)
        elif self.strategy == "median":
            s = sorted(present)
            mid = len(s) // 2
            self.fill_ = s[mid] if len(s) % 2 == 1 else (s[mid - 1] + s[mid]) / 2
        else:
            counts = {}
            for v in present:
                counts[v] = counts.get(v, 0) + 1
            best = max(counts.values())
            self.fill_ = min(v for v, c in counts.items() if c == best)
        return self

    def transform(self, values):
        if self.fill_ is None:
            raise RuntimeError("call fit first")
        filled, flags = [], []
        for v in values:
            if _is_missing(v):
                filled.append(self.fill_)
                flags.append(1)
            else:
                filled.append(v)
                flags.append(0)
        return filled, flags


class StandardScaler:
    def __init__(self):
        self.mean_ = None
        self.scale_ = None

    def fit(self, values):
        if len(values) == 0:
            raise ValueError("cannot fit on an empty column")
        self.mean_ = _mean(values)
        std = math.sqrt(sum((v - self.mean_) ** 2 for v in values) / len(values))
        self.scale_ = std if std >= EPS else 1.0
        return self

    def transform(self, values):
        if self.mean_ is None:
            raise RuntimeError("call fit first")
        return [(v - self.mean_) / self.scale_ for v in values]


class OneHotEncoder:
    def __init__(self):
        self.categories_ = None

    def fit(self, values):
        self.categories_ = sorted(set(values))
        return self

    def transform(self, values):
        if self.categories_ is None:
            raise RuntimeError("call fit first")
        index = {c: i for i, c in enumerate(self.categories_)}
        rows = []
        for v in values:
            row = [0] * len(self.categories_)
            if v in index:
                row[index[v]] = 1
            rows.append(row)
        return rows


def target_encoding_fit(categories, y, smooth):
    if len(categories) != len(y) or len(y) == 0 or smooth < 0:
        raise ValueError("need equal, non-empty lists and smooth >= 0")
    prior = _mean(y)
    n, s = {}, {}
    for c, t in zip(categories, y):
        n[c] = n.get(c, 0) + 1
        s[c] = s.get(c, 0) + t
    encoding = {c: (s[c] + smooth * prior) / (n[c] + smooth) for c in n}
    return encoding, prior


def target_encoding_apply(categories, encoding, prior):
    return [encoding.get(c, prior) for c in categories]


def target_encoding_oof(categories, y, n_folds, smooth):
    n = len(y)
    if len(categories) != n or n_folds < 2 or n_folds > n or smooth < 0:
        raise ValueError("need equal lists, 2 <= n_folds <= len(y) and smooth >= 0")
    out = [0.0] * n
    for f in range(n_folds):
        train = [i for i in range(n) if i % n_folds != f]
        enc, prior = target_encoding_fit([categories[i] for i in train], [y[i] for i in train], smooth)
        for i in range(f, n, n_folds):
            out[i] = enc.get(categories[i], prior)
    return out


def quantile_edges(values, bins):
    if len(values) == 0 or bins < 2:
        raise ValueError("need values and bins >= 2")
    s = sorted(values)
    n = len(s)
    edges = []
    for k in range(1, bins):
        lo, rem = divmod(k * (n - 1), bins)
        hi = min(lo + 1, n - 1)
        edges.append(s[lo] + rem / bins * (s[hi] - s[lo]))
    return edges


def bin_counts(values, edges):
    if any(edges[i] > edges[i + 1] for i in range(len(edges) - 1)):
        raise ValueError("edges must be sorted")
    counts = [0] * (len(edges) + 1)
    for v in values:
        counts[bisect_right(edges, v)] += 1
    return counts


def psi(expected_counts, actual_counts, eps=1e-4):
    if len(expected_counts) != len(actual_counts) or len(expected_counts) == 0:
        raise ValueError("need two lists of the same non-zero length")
    if min(expected_counts) < 0 or min(actual_counts) < 0:
        raise ValueError("counts cannot be negative")
    te, ta = sum(expected_counts), sum(actual_counts)
    if te == 0 or ta == 0:
        raise ValueError("a total of zero has no shares")
    total = 0.0
    for ce, ca in zip(expected_counts, actual_counts):
        e = max(ce / te, eps)
        a = max(ca / ta, eps)
        total += (a - e) * math.log(a / e)
    return total


def ks_statistic(a, b):
    if len(a) == 0 or len(b) == 0:
        raise ValueError("both samples need values")
    xs, ys = sorted(a), sorted(b)
    n, m = len(xs), len(ys)
    i = j = 0
    best = 0.0
    while i < n or j < m:
        if j >= m or (i < n and xs[i] <= ys[j]):
            v = xs[i]
        else:
            v = ys[j]
        while i < n and xs[i] <= v:
            i += 1
        while j < m and ys[j] <= v:
            j += 1
        best = max(best, abs(i / n - j / m))
    return best


def point_in_time_join(events, features, ttl=None):
    if ttl is not None and ttl < 0:
        raise ValueError("ttl cannot be negative")
    by_key = {}
    for key, ts, value in features:
        by_key.setdefault(key, []).append((ts, value))
    stamps = {}
    for key, rows in by_key.items():
        rows.sort(key=lambda r: r[0])
        stamps[key] = [r[0] for r in rows]
    out = []
    for key, ts in events:
        if key not in by_key:
            out.append(None)
            continue
        idx = bisect_right(stamps[key], ts) - 1
        if idx < 0:
            out.append(None)
            continue
        f_ts, value = by_key[key][idx]
        if ttl is not None and f_ts < ts - ttl:
            out.append(None)
        else:
            out.append(value)
    return out


def past_rolling_mean(values, window):
    if window < 1:
        raise ValueError("window must be at least 1")
    out = []
    for i in range(len(values)):
        past = values[max(0, i - window):i]
        out.append(_mean(past) if past else None)
    return out


# ---------------------------------------------------------------------------
# Experiments (not part of the homework)
# ---------------------------------------------------------------------------
import hashlib
import json
import random
import time

T0 = time.time()


def mean(xs):
    xs = list(xs)
    return sum(xs) / len(xs)


def sd(xs):
    xs = list(xs)
    m = mean(xs)
    return math.sqrt(sum((v - m) ** 2 for v in xs) / len(xs))


def auc(scores, labels):
    order = sorted(range(len(scores)), key=lambda i: scores[i])
    ranks = [0.0] * len(scores)
    i = 0
    while i < len(order):
        j = i
        while j + 1 < len(order) and scores[order[j + 1]] == scores[order[i]]:
            j += 1
        for k in range(i, j + 1):
            ranks[order[k]] = (i + j) / 2 + 1
        i = j + 1
    pos = [r for r, y in zip(ranks, labels) if y == 1]
    n1, n0 = len(pos), len(labels) - len(pos)
    return (sum(pos) - n1 * (n1 + 1) / 2) / (n1 * n0)


def skew(xs):
    m, s = mean(xs), sd(xs)
    return mean(((v - m) / s) ** 3 for v in xs)


print("== 1. Missing data: three mechanisms")
rng = random.Random(1)
N = 20000
z = [rng.gauss(0, 1) for _ in range(N)]
x = [50 + 10 * (0.8 * zi + 0.6 * rng.gauss(0, 1)) for zi in z]
print("   true mean %.2f, true sd %.2f" % (mean(x), sd(x)))
masks = {
    "MCAR (30% at random)": [rng.random() < 0.3 for _ in range(N)],
    "MAR  (60% if z > 0, else 10%)": [rng.random() < (0.6 if zi > 0 else 0.1) for zi in z],
    "MNAR (60% if x > 50, else 10%)": [rng.random() < (0.6 if xi > 50 else 0.1) for xi in x],
}
for name, miss in masks.items():
    obs = [xi for xi, m in zip(x, miss) if not m]
    imp = Imputer("mean").fit([None if m else xi for xi, m in zip(x, miss)])
    filled, _ = imp.transform([None if m else xi for xi, m in zip(x, miss)])
    hi = [xi for xi, zi, m in zip(x, z, miss) if not m and zi > 0]
    lo = [xi for xi, zi, m in zip(x, z, miss) if not m and zi <= 0]
    grp = [(mean(hi) if zi > 0 else mean(lo)) if m else xi for xi, zi, m in zip(x, z, miss)]
    print("   %-32s missing %.3f | observed mean %.2f | mean-imputed mean %.2f, sd %.2f | z-group imputed mean %.2f"
          % (name, mean(1.0 if m else 0.0 for m in miss), mean(obs), mean(filled), sd(filled), mean(grp)))
rng = random.Random(2)
ys, ms = [], []
for _ in range(N):
    yv = 1 if rng.random() < 0.3 else 0
    ys.append(yv)
    ms.append(rng.random() < (0.2 if yv else 0.7))
print("   lab test missing: P(missing) %.3f, P(y=1 | missing) %.3f, P(y=1 | observed) %.3f"
      % (mean(1.0 if m else 0.0 for m in ms), mean(y for y, m in zip(ys, ms) if m), mean(y for y, m in zip(ys, ms) if not m)))

print("\n== 2. Fit on training data only")
rng = random.Random(3)
tr = [rng.gauss(0, 1) for _ in range(1000)]
te = [rng.gauss(1.5, 1) for _ in range(1000)]
sc_train = StandardScaler().fit(tr)
sc_all = StandardScaler().fit(tr + te)
print("   train mean %.3f sd %.3f; test mean %.3f sd %.3f" % (mean(tr), sd(tr), mean(te), sd(te)))
print("   scaler fitted on train: scaled test mean %.3f, sd %.3f" % (mean(sc_train.transform(te)), sd(sc_train.transform(te))))
print("   scaler fitted on train+test: scaled test mean %.3f, sd %.3f" % (mean(sc_all.transform(te)), sd(sc_all.transform(te))))
imp_t = Imputer("median").fit([None if i % 10 == 0 else v for i, v in enumerate(tr)])
print("   median fill from train %.3f; from train+test it would be %.3f" % (imp_t.fill_, Imputer("median").fit(tr + te).fill_))

print("\n== 3. Encoding categoricals")
cats500 = ["c%03d" % i for i in range(500)]
oh = OneHotEncoder().fit(cats500)
print("   one-hot of 500 categories: %d columns; an unseen category gives a row with sum %d" % (len(oh.categories_), sum(oh.transform(["new"])[0])))


def bucket(name, buckets):
    return int.from_bytes(hashlib.md5(name.encode()).digest()[:4], "big") % buckets


for b in (64, 256, 1024):
    loads = {}
    for cname in cats500:
        loads[bucket(cname, b)] = loads.get(bucket(cname, b), 0) + 1
    shared = sum(v for v in loads.values() if v > 1)
    print("   hash 500 categories into %4d buckets: %3d buckets used, largest bucket holds %d, %3d categories share a bucket"
          % (b, len(loads), max(loads.values()), shared))
d_raw = abs(23 - 0)
d_cyc = lambda h1, h2: math.hypot(math.sin(2 * math.pi * h1 / 24) - math.sin(2 * math.pi * h2 / 24),
                                  math.cos(2 * math.pi * h1 / 24) - math.cos(2 * math.pi * h2 / 24))
print("   hour 23 vs hour 0: raw distance %d, sin/cos distance %.4f; hour 0 vs 1: %.4f; hour 0 vs 12: %.4f"
      % (d_raw, d_cyc(23, 0), d_cyc(0, 1), d_cyc(0, 12)))

print("   -- smoothing with 10 pseudo-rows")
cats_s = ["few"] * 1 + ["some"] * 10 + ["many"] * 100 + ["rest"] * 889
y_s = [1] + [1] * 8 + [0] * 2 + [1] * 80 + [0] * 20 + [1] * 233 + [0] * 656
enc_s, prior_s = target_encoding_fit(cats_s, y_s, 10)
enc_0, _ = target_encoding_fit(cats_s, y_s, 0)
print("   prior %.4f" % prior_s)
for c_, n_ in (("few", 1), ("some", 10), ("many", 100)):
    print("   category %-4s n=%3d: raw mean %.3f, smoothed %.3f" % (c_, n_, enc_0[c_], enc_s[c_]))

print("   -- target-encoding leakage, labels independent of the category")
rng = random.Random(4)
n_rows, n_cat = 4000, 400
cat_all = ["k%d" % rng.randrange(n_cat) for _ in range(n_rows)]
y_all = [1 if rng.random() < 0.3 else 0 for _ in range(n_rows)]
c_tr, c_te, y_tr, y_te = cat_all[:2000], cat_all[2000:], y_all[:2000], y_all[2000:]
for smooth in (0, 10):
    enc, pr = target_encoding_fit(c_tr, y_tr, smooth)
    in_sample = target_encoding_apply(c_tr, enc, pr)
    oof = target_encoding_oof(c_tr, y_tr, 5, smooth)
    on_test = target_encoding_apply(c_te, enc, pr)
    print("   smooth %2d: AUC of the encoded feature  train in-sample %.3f | train out-of-fold %.3f | held-out test %.3f"
          % (smooth, auc(in_sample, y_tr), auc(oof, y_tr), auc(on_test, y_te)))
print("   -- leave-one-out encoding (the row's own target removed) still leaks")


def loo_encode(cats, ys):
    n_c, s_c = {}, {}
    for c_, t_ in zip(cats, ys):
        n_c[c_] = n_c.get(c_, 0) + 1
        s_c[c_] = s_c.get(c_, 0) + t_
    return [(s_c[c_] - t_) / (n_c[c_] - 1) if n_c[c_] > 1 else mean(ys) for c_, t_ in zip(cats, ys)]


one_level = ["same"] * len(y_tr)
print("   one constant level, 2000 rows: AUC of the feature, leave-one-out %.3f | 5-fold out-of-fold %.3f"
      % (auc(loo_encode(one_level, y_tr), y_tr), auc(target_encoding_oof(one_level, y_tr, 5, 0), y_tr)))
print("   400 levels, labels independent: AUC leave-one-out %.3f | 5-fold out-of-fold %.3f"
      % (auc(loo_encode(c_tr, y_tr), y_tr), auc(target_encoding_oof(c_tr, y_tr, 5, 0), y_tr)))
print("   -- same, but each category has its own true rate (0.10 to 0.50)")
rng = random.Random(5)
rate = {"k%d" % i: 0.10 + 0.40 * rng.random() for i in range(n_cat)}
y_all2 = [1 if rng.random() < rate[c_] else 0 for c_ in cat_all]
y_tr2, y_te2 = y_all2[:2000], y_all2[2000:]
for smooth in (0, 10):
    enc, pr = target_encoding_fit(c_tr, y_tr2, smooth)
    oof = target_encoding_oof(c_tr, y_tr2, 5, smooth)
    print("   smooth %2d: AUC  train in-sample %.3f | train out-of-fold %.3f | held-out test %.3f | best possible (true rates) %.3f"
          % (smooth, auc(target_encoding_apply(c_tr, enc, pr), y_tr2), auc(oof, y_tr2),
             auc(target_encoding_apply(c_te, enc, pr), y_te2), auc([rate[c_] for c_ in c_te], y_te2)))

print("\n== 4. Scaling, outliers and skew")
rng = random.Random(6)
ln = [math.exp(rng.gauss(0, 1)) for _ in range(5000)]
print("   lognormal(0,1) sample: mean %.2f, median %.2f, skewness %.2f; after log: skewness %.2f"
      % (mean(ln), sorted(ln)[2500], skew(ln), skew([math.log(v) for v in ln])))
clean = [rng.gauss(10, 2) for _ in range(99)]
dirty = clean + [1000.0]
zc = StandardScaler().fit(clean).transform(clean)
zd = StandardScaler().fit(dirty).transform(dirty)
q1, med, q3 = quantile_edges(dirty, 4)
zr = [(v - med) / (q3 - q1) for v in dirty]
print("   99 ordinary values (mean 10, sd 2): sd of the scaled values %.3f clean, %.3f after adding one value of 1000"
      % (sd(zc), sd(zd[:99])))
print("   with the outlier: standard scaler sd %.2f, outlier z %.2f; median/IQR scaling: sd of ordinary values %.3f, outlier %.1f"
      % (StandardScaler().fit(dirty).scale_, zd[-1], sd(zr[:99]), zr[-1]))

print("\n== 5. Feature crosses")
rng = random.Random(7)
x1 = [rng.gauss(0, 1) for _ in range(4000)]
x2 = [rng.gauss(0, 1) for _ in range(4000)]
yx = [(1 if a * b > 0 else 0) if rng.random() > 0.05 else (0 if a * b > 0 else 1) for a, b in zip(x1, x2)]


def sign_rule_accuracy(feature):
    pos = mean(1.0 if (f > 0) == (t == 1) else 0.0 for f, t in zip(feature, yx))
    return max(pos, 1 - pos)


print("   y = 1 when x1 * x2 > 0, 5%% of labels flipped. Best sign rule on x1: %.3f, on x2: %.3f, on the cross x1*x2: %.3f"
      % (sign_rule_accuracy(x1), sign_rule_accuracy(x2), sign_rule_accuracy([a * b for a, b in zip(x1, x2)])))

print("\n== 6. Point-in-time correctness")
feats = [("u1", 1, 3), ("u1", 5, 4), ("u1", 9, 10), ("u2", 2, 7)]
evs = [("u1", 5), ("u1", 8), ("u1", 0), ("u2", 1), ("u1", 100)]
print("   events %s -> %s" % (evs, point_in_time_join(evs, feats)))
print("   with ttl 3 -> %s" % point_in_time_join(evs, feats, ttl=3))
series = [3, 5, 4, 10]
print("   series %s: past-only rolling mean (window 3) %s; mean including the current value at the last step %.2f"
      % (series, past_rolling_mean(series, 3), mean(series[-3:] if len(series) >= 3 else series)))
rng = random.Random(8)
n_cust = 3000
churn, leaky, correct = [], [], []
for _ in range(n_cust):
    ch = 1 if rng.random() < 0.3 else 0
    p_before = 0.3 if ch else 0.4
    p_after = 0.0 if ch else 0.4
    before = sum(1 for _d in range(30) if rng.random() < p_before)
    after = sum(1 for _d in range(7) if rng.random() < p_after)
    churn.append(ch)
    correct.append(-before)
    leaky.append(-(before + after))
print("   churn prediction at time t, events counted in the 30 days before t: AUC %.3f; counting 7 days past t as well: AUC %.3f"
      % (auc(correct, churn), auc(leaky, churn)))

print("\n== 7. Training-serving skew")
rng = random.Random(9)
n_s = 20000
xv = [rng.gauss(100, 15) for _ in range(n_s)]
yv = [1 if v + rng.gauss(0, 5) < 85 else 0 for v in xv]
miss = [None if rng.random() < 0.1 else v for v in xv]
imp = Imputer("median").fit(miss)
offline, _ = imp.transform(miss)
served = [0.0 if v is None else v for v in miss]


def prec_rec(values):
    flag = [1 if v < 85 else 0 for v in values]
    tp = sum(1 for f, t in zip(flag, yv) if f and t)
    return tp / sum(flag), tp / sum(yv), sum(flag)


for name, vals in (("offline (median fill %.1f)" % imp.fill_, offline), ("served (fill 0)", served)):
    p_, r_, nf = prec_rec(vals)
    print("   %-26s flagged %5d, precision %.3f, recall %.3f" % (name, nf, p_, r_))

print("\n== 8. Drift")
e2, a2 = [0.5, 0.5], [0.3, 0.7]
print("   hand example: expected %s actual %s: PSI = %.4f" % (e2, a2, psi([50, 50], [30, 70])))
rng = random.Random(10)
ref = [rng.gauss(0, 1) for _ in range(50000)]
edges = quantile_edges(ref, 10)
ref_counts = bin_counts(ref, edges)
cases = [("no drift", 0.0, 1.0), ("mean +0.1", 0.1, 1.0), ("mean +0.5", 0.5, 1.0), ("sd x1.5, mean same", 0.0, 1.5), ("mean +0.5, sd x1.2", 0.5, 1.2)]
drifted = None
for name, mu, sg in cases:
    cur = [rng.gauss(mu, sg) for _ in range(10000)]
    drifted = cur
    print("   %-20s PSI %.4f   KS %.4f" % (name, psi(ref_counts, bin_counts(cur, edges)), ks_statistic(ref, cur)))
print("   -- PSI under no drift depends on the sample size (10 bins, 50,000 reference rows, 100 repeats)")
for n_a in (100, 1000, 10000):
    vals = []
    for _ in range(100):
        cur = [rng.gauss(0, 1) for _ in range(n_a)]
        vals.append(psi(ref_counts, bin_counts(cur, edges)))
    vals.sort()
    print("   n = %5d: mean PSI %.4f (derived guess 9 x (1/n + 1/50000) = %.4f), 95th percentile %.4f"
          % (n_a, mean(vals), 9 * (1 / n_a + 1 / 50000), vals[94]))
cur = drifted
print("   -- the last drifted sample above (mean +0.5, sd 1.2) with different bin counts")
for b in (5, 10, 20):
    ed = quantile_edges(ref, b)
    print("   %2d bins: PSI %.4f" % (b, psi(bin_counts(ref, ed), bin_counts(cur, ed))))
print("   -- a new category")
exp_c = [600, 300, 100, 0]
act_c = [500, 300, 100, 100]
for eps in (1e-4, 1e-6):
    print("   expected shares 0.6/0.3/0.1/0, actual 0.5/0.3/0.1/0.1, eps %g: PSI %.3f" % (eps, psi(exp_c, act_c, eps)))
big_n = 100000
r1 = [rng.gauss(0, 1) for _ in range(big_n)]
r2 = [rng.gauss(0.02, 1) for _ in range(big_n)]
ed = quantile_edges(r1, 10)
print("   -- a tiny shift (mean +0.02) with %d rows on each side: PSI %.5f, KS %.4f, 5%% KS critical value 1.358 x sqrt(2/n) = %.4f"
      % (big_n, psi(bin_counts(r1, ed), bin_counts(r2, ed)), ks_statistic(r1, r2), 1.358 * math.sqrt(2 / big_n)))
print("   -- concept drift: the inputs do not move, the rule does")
rng = random.Random(11)
xa = [rng.gauss(0, 1) for _ in range(20000)]
xb = [rng.gauss(0, 1) for _ in range(20000)]
ya = [1 if v > 0 else 0 for v in xa]
yb = [1 if v > 1 else 0 for v in xb]
edg = quantile_edges(xa, 10)
print("   PSI of the input %.4f; accuracy of the rule 'x > 0' before %.3f, after the label rule moved to 'x > 1': %.3f"
      % (psi(bin_counts(xa, edg), bin_counts(xb, edg)), mean(1.0 if (v > 0) == (t == 1) else 0.0 for v, t in zip(xa, ya)),
         mean(1.0 if (v > 0) == (t == 1) else 0.0 for v, t in zip(xb, yb))))

print("\n== 9. Label delay")
rng = random.Random(12)
n_l = 40000
delay = [rng.expovariate(1 / 20) for _ in range(n_l)]
is_pos = [rng.random() < 0.05 for _ in range(n_l)]
for age in (7, 14, 30, 60, 90):
    seen = sum(1 for d, p in zip(delay, is_pos) if p and d <= age)
    print("   cohort aged %2d days: positives labelled so far %.4f (true rate %.4f; share of positives labelled %.3f; theory 1 - exp(-age/20) = %.3f)"
          % (age, seen / n_l, mean(1.0 if p else 0.0 for p in is_pos), seen / sum(is_pos), 1 - math.exp(-age / 20)))

print("\n== 10. Retraining policies on a drifting concept")


def run_policy(policy, weeks=40, seed=13):
    rng = random.Random(seed)
    model_c = 0.0
    last_train = 0
    retrains = 0
    accs = []
    labelled_acc = []
    for t in range(weeks):
        c_t = 0.1 * t
        xs = [rng.gauss(0, 1) for _ in range(2000)]
        acc = mean(1.0 if (v > model_c) == (v > c_t) else 0.0 for v in xs)
        accs.append(acc)
        labelled_acc.append(acc)
        retrain = False
        if policy == "schedule 10 weeks" and t - last_train >= 10:
            retrain = True
        if policy == "trigger: accuracy < 0.95" and t >= 2 and labelled_acc[t - 2] < 0.95:
            retrain = True
        if retrain:
            model_c = 0.1 * max(t - 2, 0)
            last_train = t
            retrains += 1
    return mean(accs), min(accs), retrains


for pol in ("never", "schedule 10 weeks", "trigger: accuracy < 0.95"):
    m_, lo_, r_ = run_policy(pol)
    print("   %-26s mean accuracy %.3f, worst week %.3f, retrains %d" % (pol, m_, lo_, r_))

print("\n== 11. Versioning and reproducibility")
snap = {"rows": [[1, 0.5, "a"], [2, 0.7, "b"]], "schema": ["id", "x", "cat"]}
snap2 = {"rows": [[1, 0.5, "a"], [2, 0.7, "c"]], "schema": ["id", "x", "cat"]}
h = lambda o: hashlib.sha256(json.dumps(o, sort_keys=True).encode()).hexdigest()
print("   snapshot hash %s ... ; one changed cell: %s ... ; same snapshot again: %s ..." % (h(snap)[:12], h(snap2)[:12], h(dict(snap))[:12]))
rng_a, rng_b, rng_c = random.Random(0), random.Random(0), random.Random(1)
print("   same seed gives the same first draw: %s; a different seed does not: %s" % (rng_a.random() == rng_b.random(), rng_a.random() == rng_c.random()))
rng = random.Random(14)
flips = [1 if rng.random() < 0.10 else 0 for _ in range(20000)]
print("   label noise: with 10%% of labels flipped, a model that is always right is scored %.3f" % (1 - mean(flips)))

print("\ntotal %.1f s" % (time.time() - T0))

What to look for: section 1 (three mechanisms and the missing indicator), section 2 (fitting on train versus on everything), section 3 (hashing collisions, cyclical distance, smoothing, target-encoding leakage), section 4 (outlier and skew), section 5 (a cross), section 6 (point-in-time and the leaky window), section 7 (skew from null handling), section 8 (PSI, KS, noise floor, bins, concept drift), section 9 (label delay), section 10 (retraining policies), section 11 (hash of a snapshot, label noise). In scikit-learn the equivalents are SimpleImputer, StandardScaler, RobustScaler, OneHotEncoder, TargetEncoder, ColumnTransformer and Pipeline; SciPy has scipy.stats.ks_2samp.

Real-World Application

A sound recipe for a tabular model that will run in production: write the prediction time and the label definition first, then list every feature with the time it becomes available. Split by time or entity as the first lesson of this module says. Build preprocessing inside one pipeline fitted on training rows only, with imputers that add indicators and encoders that handle unseen levels. Encode high-cardinality categories out-of-fold. Compute windowed features point-in-time. Log the exact features you serve. Before launch, compare served and training feature distributions on a shadow run. After launch, watch data quality, feature and score drift, and cohort performance as labels mature, and keep a rollback ready. When the metric drops, follow the debugging order above before you touch the model.

Interview Perspective

Expect “your model was 0.91 AUC offline and is poor in production, what do you do”, “what is training-serving skew and how do you prevent it”, “how do you monitor a model whose labels arrive 60 days late”, “data drift against concept drift”, “how do you handle missing values”, “what is wrong with target encoding”, and “compute the PSI of these two bins”. A strong answer states the order of checks, names the cheapest first, gives a number or a test for each, and says what it would log. A weak answer says “retrain it”.

Provenance: Common industry pattern. These are standard production-ML topics for applied ML roles, not a verified list for any named company.

Practice Questions

  • Basic (Common industry pattern): What are MCAR, MAR and MNAR, and why does the difference matter for imputation?
  • Basic (Common industry pattern): Why should a scaler or imputer be fitted on the training split only?
  • Intermediate (Common industry pattern): Why does target encoding leak, and how do you encode a high-cardinality feature safely?
  • Intermediate (Common industry pattern): What is training-serving skew? Give three causes and a defence for each.
  • Intermediate (Generated practice): Compute the PSI for expected shares (0.6, 0.4) and actual shares (0.45, 0.55), and say what you would do at that value.
  • Advanced (Common industry pattern): A model’s AUC was 0.91 offline and is much worse in production. Walk through your debugging order.
  • Advanced (Common industry pattern): How do you monitor a fraud model whose labels arrive 60 days late?
  • Product-Company (Generated practice): Design the retraining and rollout plan for a model whose input distribution shifts seasonally and whose decisions affect which outcomes you observe.

Activity

Run the script, then change three things. In section 3, change the smoothing from 10 to 100 and note what happens to the held-out AUC in the signal case and to the value of the one-row level. In section 6, change the 7 days past tt to 14 and watch the leaky AUC. In section 8, change the current window for the no-drift PSI from 100 rows to 400 and compare the mean with (B−1)(1/na+1/ne)(B-1)(1/n_a+1/n_e). Then write the message you would send your team about a feature whose PSI is 0.18 on a day when 300 rows were scored.

Homework

Build the preprocessing and monitoring toolkit with the standard library only: an imputer with a missing indicator and a standard scaler that learn on training rows only, a one-hot encoder with unseen levels, smoothed and out-of-fold target encoding, quantile bins, PSI and the KS statistic, a point-in-time join with a TTL, and a past-only rolling mean. The code is in homework/; run the tests until they pass.

Quick Revision

  • Missing data: ask why. MCAR is harmless but loses data, MAR can be corrected with observed columns, MNAR cannot be fixed from the data. Add a missing indicator because missingness is a signal. Fit imputers, scalers and encoders on the training rows only.
  • One outlier of 1,000 cut the scaled spread of 99 ordinary values from 1.000 to 0.020. Use robust scaling, clipping or logs. Trees do not need scaling.
  • Choose an encoding by cardinality and order. Target encoding leaks (in-sample AUC 0.770 on pure noise) unless it is out-of-fold and smoothed. Crosses help linear models.
  • A feature at time tt may use only what existed at tt: past-only windows and point-in-time joins. The leaky window scored AUC 0.921 against 0.773.
  • Skew comes from two code paths. Share the code, log served features, use golden tests. A null filled with 0 instead of the median dropped precision from 0.831 to 0.556.
  • Data drift moves P(X)P(X), label shift P(y)P(y), concept drift P(y∣X)P(y\mid X). PSI sums (a−e)ln⁡(a/e)(a-e)\ln(a/e) over bins and has a sample-size noise floor. Only labels reveal concept drift.
  • Labels arrive late: judge cohorts of the same age. Retrain on a schedule or a trigger, roll out by shadow, canary and ramp, version data, code and seeds, and debug in the order inputs, skew, leakage, drift, labels, serving, model.

Check yourself

  • Walk-through: Without notes, explain how you would take a tabular model from notebook to production so that training and serving compute the same features, naming the check you run before launch and the metric you watch after.
  • Variation: A feature’s PSI is 0.31 this week, computed on 80 rows, and accuracy on matured labels is unchanged. Say what you believe and what you do next.
  • Common misconception: “Mean imputation is harmless”, “target encoding is safe if I smooth it”, and “PSI below 0.1 means the model is fine”.

Resources & Further Reading

Checked sources to go deeper. The essential ones come first in each group.

Official documentation

Further reading

Research papers

More for this module: Evaluation, statistics and data resources

Practice

Test what you just read. Quizzes and cards are grouped by module: Evaluation, statistics and data.

Check yourself24 questions on what this lesson set out to teach

Checking answers needs JavaScript. You can still read every question and option below.

0 of 24 answered

Keyboard: arrow keys move between options. Space or Enter selects the focused option.

ObjectiveTreat missing values by mechanism (MCAR, MAR, MNAR) with imputation and a missing indicator, handle outliers, scaling and skew, and fit every learned statistic on the training rows only.

  1. Question 1 of 24A variable has true mean 50.06 and about 35% of its values are missing. The mean of the observed values is 47.58. Filling each gap with the mean of its group, where the groups come from a fully observed column z, gives an overall mean of 50.00. Which explanation fits these numbers?

    Choose one answer.

  2. Question 2 of 24A lab value is missing for 70% of healthy patients and 20% of sick ones. The disease rate is 0.109 where the value is missing and 0.538 where it was measured. You will train a logistic regression. Which treatment keeps the most information?

    Choose one answer.

  3. Question 3 of 24Which statements about fitting preprocessing steps are correct? Select all that apply.

    Choose all that apply.

  4. Question 4 of 24A column has 99 ordinary values (mean 10, sd 2) and one value of 1,000. After standardising, the ordinary values have sd 0.020 instead of 1.000. What is the best response?

    Choose one answer.

ObjectiveChoose an encoding for a categorical feature (one-hot, ordinal, target, hashing, embedding), explain why target encoding leaks unless it is out-of-fold and smoothed, and say when a feature cross helps.

  1. Question 5 of 24A logistic regression needs a feature 'zip code' with 8,000 levels, many of them rare, and new zip codes appear every month. Which statement is correct?

    Choose one answer.

  2. Question 6 of 24Labels are independent of the category on purpose. A target-encoded feature scores AUC 0.770 on the training rows it was fitted on, 0.501 out-of-fold, and 0.489 on held-out rows. What does this show?

    Choose one answer.

  3. Question 7 of 24Target encoding with smoothing: the overall target mean is 0.40, and a level has 5 training rows of which 4 are positive. With smoothing strength m = 5, what is the encoded value?

    Choose one answer.

  4. Question 8 of 24Which statements about encoding are true? Select all that apply.

    Choose all that apply.

  5. Question 9 of 24In the script, the best single sign rule on x1 scores 0.500 accuracy, on x2 0.504, and on the product x1 times x2 scores 0.952. What is the right conclusion?

    Choose one answer.

ObjectiveBuild lag, rolling and aggregate features that use only information available at prediction time (point-in-time joins), and keep training and serving identical with one pipeline definition, logging and golden tests.

  1. Question 10 of 24A churn model uses the count of events in a window. Counting events in the 30 days before prediction time t gives AUC 0.773. Counting the 7 days after t as well gives AUC 0.921. What should you do?

    Choose one answer.

  2. Question 11 of 24Feature rows for one user are (time 2, low), (time 6, mid) and (time 7, high). A labelled event for that user happens at time 6.5. The join allows rows at most 1 time unit old (TTL 1). What value does the point-in-time join return?

    Choose one answer.

  3. Question 12 of 24A fraud rule flags values below 85. Offline, with missing values filled by the training median (100.0), precision is 0.831. Online, the same rule and model give precision 0.556 and many more flagged rows, because the serving code sends missing values as 0. What is the problem, and what is the fix?

    Choose one answer.

  4. Question 13 of 24Which statements about scikit-learn pipelines and encoders are true? Select all that apply.

    Choose all that apply.

  5. Question 14 of 24What does a feature store promise, and what does it cost?

    Choose one answer.

ObjectiveTell data drift, label shift and concept drift apart, compute PSI by hand and a KS statistic, say what each can and cannot see, and monitor a model whose labels arrive late.

  1. Question 15 of 24Expected bin shares are (0.4, 0.6) and actual shares are (0.3, 0.7). What is the PSI?

    Choose one answer.

  2. Question 16 of 24Two weeks of a model's input have PSI 0.0003 against training, yet accuracy on labelled cases fell from 1.000 to 0.659 because the true rule moved from 'x above 0' to 'x above 1'. What is this?

    Choose one answer.

  3. Question 17 of 24A daily PSI is computed on 100 rows against a 50,000-row reference with 10 bins and reads 0.12. With no drift, the simulation gave a mean PSI of 0.0950 and a 95th percentile of 0.2029 at this size. What do you do?

    Choose one answer.

  4. Question 18 of 24Which statements about detecting drift are true? Select all that apply.

    Choose all that apply.

  5. Question 19 of 24Labels arrive after a random delay with a mean of 20 days. A cohort aged 14 days shows an observed positive rate of 0.0253, while the true rate is 0.0496. A dashboard says the fraud rate halved in the last two weeks. What is the best reading?

    Choose one answer.

ObjectiveChoose retraining triggers and a safe rollout, version data, code and models so a result can be reproduced, and debug a model that works in the notebook but fails in production in a sensible order.

  1. Question 20 of 24In the toy drift simulation, never retraining scored mean accuracy 0.609 (0 retrains), retraining every 10 weeks 0.908 (3 retrains, worst week 0.673), and retraining when the last known accuracy fell below 0.95 gave 0.952 (15 retrains, worst week 0.854). Which statement is supported?

    Choose one answer.

  2. Question 21 of 24A model had AUC 0.91 offline and performs much worse in production. You can run one check first. Which one?

    Choose one answer.

  3. Question 22 of 24Which of these do you need to record to reproduce a trained model later? Select all that apply.

    Choose all that apply.

  4. Question 23 of 24A lender approves only applicants scoring above a cutoff and retrains every month on repayment outcomes of the approved loans. What is the main risk?

    Choose one answer.

  5. Question 24 of 24A new model scores live traffic and its predictions are logged, but nothing acts on them. What stage is this, and what does it catch that offline validation cannot?

    Choose one answer.