Slides · Evaluation, statistics and data
Data, features and production ML: preprocessing, encodings, point-in-time features, skew, drift and operations
1 / 27
Data, features and production ML
Preprocessing, encodings, point-in-time features, skew, drift and operations.
Concept
Why this is worth 100 minutes
- Most production failures of ML systems are data failures: a null column, a feature built two ways, a window that includes tomorrow, a population that moved.
- Interviewers ask “works in the notebook, fails in production” because it shows whether you have run a model (common industry pattern).
- Mental model: a model is a contract about its inputs. Training signs it, production must keep it.
Five things you will be able to do:
- Treat missing values, outliers and scale without leaking.
- Choose an encoding, and explain why target encoding leaks.
- Build point-in-time features and prevent skew.
- Tell the kinds of drift apart and compute PSI.
- Choose retraining and rollout, and debug in order.
Compare
Why is it missing?
| Mechanism | Depends on | Observed mean (true 50.06) | Group-wise fill |
|---|---|---|---|
| MCAR | Nothing | 50.09 | 50.10 |
| MAR | Another observed column | 47.58 | 50.00 |
| MNAR | The missing value itself | 46.97 | 48.36 |
- Mean fill keeps the observed mean and shrinks the spread: sd 8.35 against 9.94 under MCAR.
- A missing indicator keeps the signal: disease rate 0.109 where the lab test was missing, 0.538 where taken.
Sources[1] Inference and Missing Data[2] Imputation of missing values (SimpleImputer, MissingIndicator, IterativeImputer, KNNImputer)
Check yourself
Check: a nightly job
A nightly job computes the median of each column over all of last month’s data, including the days you will test on, then splits train and test. What is wrong?
Answer
The fill values were learned from rows that include the test period, so test information shaped the training features. Split first, learn the median on the training rows only, and reuse that value for test and live rows. A pipeline does this automatically inside each fold.
Worked example
Fit on training only
- Train feature mean -0.030, test mean 1.529.
- Scaler fitted on train: scaled test mean 1.580, the shift shows.
- Scaler fitted on train and test together: 0.617, the shift is hidden.
- Median fill: -0.028 from train rows, 0.731 if the test rows are included.
Rule: fit on training rows, transform everywhere else.
Sources[3] Common pitfalls and recommended practices (data leakage)[4] Pipelines and composite estimators (Pipeline and ColumnTransformer)
Worked example
One outlier, two scalers
| 99 values (mean 10, sd 2) plus one 1,000 | Scaled spread of the 99 |
|---|---|
| Standard scaler (sd 98.49) | 0.020 |
| Median and IQR | 0.794 |
- Check whether the value is an error or a rare real event.
- Skew: a lognormal sample went from skewness 5.15 to 0.02 after a log.
- Trees do not need scaling: splits depend on order only.
Compare
Choosing an encoding
| Encoding | Use when | Cost |
|---|---|---|
| One-hot | Few unordered levels | Width: 500 levels, 500 columns |
| Ordinal | The order is real | Invents order for nominal levels |
| Target | Many levels, supervised signal | Leaks unless out-of-fold |
| Hashing | Huge vocabularies | 500 into 256 buckets: 438 collide |
| Embedding | Many levels, neural model | Needs data per level |
- Hour of day: sin and cos put 23 and 0 at distance 0.2611, the same as 0 and 1.
Sources[5] Preprocessing data: encoding categorical features and the target encoder (scikit-learn user guide)[6] Feature Hashing for Large Scale Multitask Learning
Math
Target encoding and its leak
x^c=nc+msc+myˉ- Overall mean 0.3220, m = 10: one row at target 1 becomes 0.384, ten rows at 0.800 become 0.561, 100 rows at 0.800 become 0.757.
- Labels independent of the category, AUC of the encoded feature: 0.770 in-sample, 0.501 out-of-fold, 0.489 held out.
- Cure: encode each fold from the other folds, use the full-train encoding for test and live rows.
- Leave-one-out still leaks: on one constant level its training AUC was 0.000, against 0.473 for 5-fold out-of-fold.
Sources[5] Preprocessing data: encoding categorical features and the target encoder (scikit-learn user guide)[7] CatBoost: unbiased boosting with categorical features
Check yourself
Check: the validation score is great
A teammate target-encodes a 3,000-level column on the full training set, then cross-validates the model and reports an AUC far above the baseline. What do you ask for?
Answer
Ask how the encoding was fitted. If every row’s label was used in its own encoding, the score is memorisation. Re-run with the encoder inside the pipeline so each fold encodes from the other folds, and compare the held-out score.
Concept
Feature crosses
- A cross combines features: a product, or a pair such as (country, device).
- Additive models cannot represent an effect that exists only in a combination.
- Label is 1 when x1 times x2 is above 0 (5% flipped): best sign rule on x1 0.500, on x2 0.504, on the cross 0.952.
- Trees and networks learn interactions. Crosses of high-cardinality features explode in width.
Worked example
Point-in-time correctness
- Rule: a feature for a prediction at time t may use only what existed at t.
- Churn model, events in the 30 days before t: AUC 0.773. Adding 7 days past t: AUC 0.921.
- Feature rows (time, value): (1, 3), (5, 4), (9, 10).
| Event time | Result |
|---|---|
| 8 | 4 |
| 0 | nothing |
| 100 | 10, or nothing with TTL 3 |
- Rolling mean of 3, 5, 4, 10 with a window of 3, past only: nothing, 3.0, 4.0, 4.0.
Check yourself
Check: orders in the last 30 days
The feature “orders in the last 30 days” is computed from a table refreshed every night. Predictions are made all day. What can go wrong?
Answer
Training rows may use a window ending at the event time while serving uses yesterday’s night run, so the same feature has different freshness in the two paths. Define the feature as of a timestamp, compute it with a point-in-time join, and log what serving actually used.
Diagram
Training-serving skew
Source[9] Rules of Machine Learning: Best Practices for ML Engineering
Worked example
One null, two paths
- Rule flags values below 85. Offline the missing values were filled with the median 100.0: 2,801 flagged, precision 0.831, recall 0.684.
- Serving sent missing as 0: 4,831 flagged, precision 0.556, recall 0.788.
- Defences: reuse code (rule 32), log served features (rule 29), golden tests, one Pipeline object, monitoring.
- A Pipeline covers its own steps. SQL joins and windows need their own checks.
- A feature store defines features once for training and serving, at the cost of another system.
Sources[9] Rules of Machine Learning: Best Practices for ML Engineering[4] Pipelines and composite estimators (Pipeline and ColumnTransformer)
Compare
Three kinds of drift
| Kind | Changes | Visible in |
|---|---|---|
| Data (covariate) drift | P(X), with P(y given X) fixed | Input distributions: PSI, KS |
| Label shift | P(y), with P(X given y) fixed | Predicted positive rate |
| Concept drift | P(y given X) | Labelled outcomes only |
- Inputs PSI 0.0003, accuracy 1.000 to 0.659: the rule moved, not the data.
- Real changes can mix. Under label shift P(X) also moves, so input PSI can fire too.
- Response differs: pipeline fix, new data, or new labels and retraining.
Sources[10] A survey on concept drift adaptation[11] Hidden Technical Debt in Machine Learning Systems
Math
PSI and KS
PSI=i=1∑B(ai−ei)lneiai,D=xmax∣Fa(x)−Fb(x)∣- Shares (0.5, 0.5) against (0.3, 0.7): 0.1022 + 0.0673 = 0.1695.
- Rule of thumb (common practice): below 0.1 stable, 0.1 to 0.25 watch, above 0.25 act.
- Mean +0.5 against 50,000 reference rows: PSI 0.2500, KS 0.2045. Spread x1.5: PSI 0.1979, KS 0.1029.
Worked example
PSI pitfalls
| No drift, 10 bins, 50,000 reference rows | Mean PSI |
|---|---|
| 100 current rows | 0.0950 |
| 1,000 | 0.0087 |
| 10,000 | 0.0011 |
- Expected PSI under no drift is about (bins - 1)(1/n + 1/n_ref) (derived here).
- Bins matter: 5, 10 and 20 bins gave 0.2060, 0.2417, 0.2669.
- An empty reference bin needs a floor: PSI 0.708 or 1.170 for 1e-4 or 1e-6.
- KS with 100,000 rows each: a 0.02 shift gave 0.0076, above the 0.0061 critical value.
Check yourself
Check: PSI by hand
Expected shares (0.2, 0.8) and actual shares (0.3, 0.7). Which bin contributes more, and is the total above or below 0.1?
Answer
Bin 1: (0.3 - 0.2) ln(1.5) = 0.0405. Bin 2: (0.7 - 0.8) ln(0.875) = 0.0134. Total 0.0539, below 0.1. The bin whose share changed most relative to its size contributes more.
Worked example
Late labels
Mean label delay 20 days, true positive rate 0.0496:
| Cohort age (days) | Share of positives labelled | Observed rate |
|---|---|---|
| 14 | 0.510 | 0.0253 |
| 30 | 0.779 | 0.0387 |
| 60 | 0.949 | 0.0471 |
| 90 | 0.990 | 0.0491 |
- Watch inputs and scores now, report true metrics by cohort, compare cohorts of the same age.
Compare
When to retrain (toy run)
| Policy | Mean accuracy | Worst week | Retrains |
|---|---|---|---|
| Never | 0.609 | 0.487 | 0 |
| Every 10 weeks | 0.908 | 0.673 | 3 |
| Accuracy below 0.95 | 0.952 | 0.854 | 15 |
- Triggers: schedule, drift, performance drop, new data volume (common practice).
- Rollout: shadow, canary, ramp, with rollback and a fallback.
- Reproducibility: record code version, data snapshot or hash, feature definitions, library versions, hyperparameters and seeds with the model, so you can say what changed and restore the old one.
Check yourself
Check: what do you log?
A model scores 2 million requests a day. You may keep a small log to debug later. What do you put in it?
Answer
The exact feature values served for each logged request, the model and feature-definition versions, a timestamp, and the score. A sampled fraction is enough. Comparing logged features with training features for the same cases is how skew and silent fallbacks are found. The raw request alone cannot show how the features were built.
Diagram
Notebook fine, production broken
Code
Homework: the feature pipeline toolkit
Python
class Imputer:
"""Fit a fill value on train; transform returns (filled, flags)."""
def target_encoding_oof(categories, y, n_folds, smooth):
"""Encode each row from the other folds only."""
def psi(expected_counts, actual_counts, eps=1e-4):
"""Sum of (a - e) ln(a / e) over bins."""
def point_in_time_join(events, features, ttl=None):
"""Latest feature row not after each event."""- Also: scaler, one-hot, quantile bins, KS statistic, past-only rolling mean.
Summary
Recap
- Ask why data is missing, add an indicator, fit every statistic on training rows only, use robust scaling for outliers.
- Encode by cardinality; target encoding leaks unless out-of-fold and smoothed.
- Features use only what existed at prediction time; one shared definition prevents skew.
- Data, label and concept drift show in different places; PSI has a noise floor; labels arrive late.
- Retrain by cost, roll out in steps, version everything, debug inputs first and the model last.
References
References & Sources (1 of 3)
Inference and Missing Data (opens in a new tab)
Donald B. Rubin1976Biometrika 63(3), 581-592Paper
https://dash.harvard.edu/entities/publication/73120378-8764-6bd4-e053-0100007fdf3b
Used for Missing at random and the conditions under which the missing-data process can be ignored (abstract page).
scikit-learn2026Documentation
https://scikit-learn.org/stable/modules/impute.html
Used for SimpleImputer strategies, add_indicator and MissingIndicator, IterativeImputer (marked experimental) and KNNImputer. MCAR, MAR and MNAR are not covered by that page.
Common pitfalls and recommended practices (data leakage) (opens in a new tab)
scikit-learn2026Documentation
https://scikit-learn.org/stable/common_pitfalls.html
Used for Data leakage and the rule to fit transformations on training data only.
Pipelines and composite estimators (Pipeline and ColumnTransformer) (opens in a new tab)
scikit-learn2026Documentation
https://scikit-learn.org/stable/modules/compose.html
Used for Pipeline purposes (convenience, joint parameter selection, safety against leaking statistics in cross-validation) and ColumnTransformer with remainder dropped by default.
scikit-learn2026Documentation
https://scikit-learn.org/stable/modules/preprocessing.html
Used for TargetEncoder smoothing and cross fitting in fit_transform (fit then transform is not the same), the encoding of unseen categories, OneHotEncoder handle_unknown and infrequent categories, RobustScaler for outliers, and the cautions on power and quantile transforms.
References
References & Sources (2 of 3)
Feature Hashing for Large Scale Multitask Learning (opens in a new tab)
Kilian Weinberger, Anirban Dasgupta, Josh Attenberg, John Langford, et al.2009arXiv:0902.2206Preprint
https://arxiv.org/abs/0902.2206
Used for Feature hashing for large-scale multitask problems and the exponential tail bounds on interference between random subspaces (abstract).
CatBoost: unbiased boosting with categorical features (opens in a new tab)
Liudmila Prokhorenkova, Gleb Gusev, Aleksandr Vorobev, Anna Veronika Dorogush, et al.2018arXiv:1706.09516 (NeurIPS 2018)Preprint
https://arxiv.org/abs/1706.09516
Used for A special kind of target leakage and prediction shift in boosting, and an algorithm for categorical features designed to counter it (abstract).
Point-in-time joins (Feast documentation) (opens in a new tab)
Feast2026Documentation
https://docs.feast.dev/getting-started/concepts/point-in-time-joins
Used for Point-in-time correct joins that scan backward from each entity timestamp, and a TTL that is relative to each timestamp.
Rules of Machine Learning: Best Practices for ML Engineering (opens in a new tab)
Google for Developers2026Article
https://developers.google.com/machine-learning/guides/rules-of-ml
Used for The definition of training-serving skew with its three causes, rule 29 on logging serving-time features, and rule 32 on re-using code between training and serving.
A survey on concept drift adaptation (opens in a new tab)
Joao Gama, Indre Zliobaite, Albert Bifet, Mykola Pechenizkiy, et al.2014ACM Computing Surveys 46(4), article 44Paper
https://doi.org/10.1145/2523813
Used for Concept drift as a change in the relationship between inputs and the target over time (abstract page).
References
References & Sources (3 of 3)
Hidden Technical Debt in Machine Learning Systems (opens in a new tab)
D. Sculley, Gary Holt, Daniel Golovin, Eugene Davydov, et al.2015NeurIPS 2015 (Advances in Neural Information Processing Systems 28)Paper
https://papers.nips.cc/paper_files/paper/2015/hash/86df7dcfd896fcaf2674f757a2463eba-Abstract.html
Used for ML-specific risk factors including data dependencies, hidden feedback loops and changes in the external world (abstract page).
scipy.stats.ks_2samp (opens in a new tab)
SciPy2026Documentation
https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.ks_2samp.html
Used for The two-sample KS test, its statistic as the maximum absolute difference between empirical distribution functions, and the continuity assumption.
Keys: ← → move, Home End first and last, F full screen.