Slides · Evaluation, statistics and data

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

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:

  1. Treat missing values, outliers and scale without leaking.
  2. Choose an encoding, and explain why target encoding leaks.
  3. Build point-in-time features and prevent skew.
  4. Tell the kinds of drift apart and compute PSI.
  5. Choose retraining and rollout, and debug in order.

Compare

Why is it missing?

MechanismDepends onObserved mean (true 50.06)Group-wise fill
MCARNothing50.0950.10
MARAnother observed column47.5850.00
MNARThe missing value itself46.9748.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.

Sources1 Inference and Missing Data2 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.

Sources3 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,000Scaled spread of the 99
Standard scaler (sd 98.49)0.020
Median and IQR0.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.

Source5 Preprocessing data: encoding categorical features and the target encoder (scikit-learn user guide)

Compare

Choosing an encoding

EncodingUse whenCost
One-hotFew unordered levelsWidth: 500 levels, 500 columns
OrdinalThe order is realInvents order for nominal levels
TargetMany levels, supervised signalLeaks unless out-of-fold
HashingHuge vocabularies500 into 256 buckets: 438 collide
EmbeddingMany levels, neural modelNeeds data per level
  • Hour of day: sin and cos put 23 and 0 at distance 0.2611, the same as 0 and 1.

Sources5 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=sc+m yˉnc+m\hat{x}_c=\frac{s_c+m\,\bar{y}}{n_c+m}
  • 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.

Sources5 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 timeResult
84
0nothing
10010, 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.

Source8 Point-in-time joins (Feast documentation)

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

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 removes the second implementation.

Source9 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.

Sources9 Rules of Machine Learning: Best Practices for ML Engineering4 Pipelines and composite estimators (Pipeline and ColumnTransformer)

Compare

Three kinds of drift

KindChangesVisible in
Data (covariate) driftP(X), with P(y given X) fixedInput distributions: PSI, KS
Label shiftP(y), with P(X given y) fixedPredicted positive rate
Concept driftP(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.

Sources10 A survey on concept drift adaptation11 Hidden Technical Debt in Machine Learning Systems

Math

PSI and KS

PSI=∑i=1B(ai−ei)ln⁡aiei,D=max⁡x∣Fa(x)−Fb(x)∣\mathrm{PSI}=\sum_{i=1}^{B}(a_i-e_i)\ln\frac{a_i}{e_i}, \qquad D=\max_x\left|F_a(x)-F_b(x)\right|
  • 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.

Source12 scipy.stats.ks_2samp

Worked example

PSI pitfalls

No drift, 10 bins, 50,000 reference rowsMean PSI
100 current rows0.0950
1,0000.0087
10,0000.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.

Source12 scipy.stats.ks_2samp

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 labelledObserved rate
140.5100.0253
300.7790.0387
600.9490.0471
900.9900.0491
  • Watch inputs and scores now, report true metrics by cohort, compare cohorts of the same age.

Compare

When to retrain (toy run)

PolicyMean accuracyWorst weekRetrains
Never0.6090.4870
Every 10 weeks0.9080.6733
Accuracy below 0.950.9520.85415
  • 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

Diagram: Seven checks ordered by cost and frequency.

Production metric drops

1. Inputs valid?

2. Skew: served against training features

3. Leakage in the old evaluation

4. Drift: PSI per feature

5. Label or definition mismatch

6. Fallbacks, timeouts, wrong artifact

7. Only then: concept change, retrain or redesign

Diagram summary: Seven checks ordered by cost and frequency. The model is the last thing to suspect.

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)

  1. Inference and Missing Data (opens in a new tab)

    Donald B. Rubin1976Biometrika 63(3), 581-592Paper

    Used for Missing at random and the conditions under which the missing-data process can be ignored (abstract page).

  2. Imputation of missing values (SimpleImputer, MissingIndicator, IterativeImputer, KNNImputer) (opens in a new tab)

    scikit-learn2026Documentation

    Used for SimpleImputer strategies, add_indicator and MissingIndicator, IterativeImputer (marked experimental) and KNNImputer. MCAR, MAR and MNAR are not covered by that page.

  3. Common pitfalls and recommended practices (data leakage) (opens in a new tab)

    scikit-learn2026Documentation

    Used for Data leakage and the rule to fit transformations on training data only.

  4. Pipelines and composite estimators (Pipeline and ColumnTransformer) (opens in a new tab)

    scikit-learn2026Documentation

    Used for Pipeline purposes (convenience, joint parameter selection, safety against leaking statistics in cross-validation) and ColumnTransformer with remainder dropped by default.

  5. Preprocessing data: encoding categorical features and the target encoder (scikit-learn user guide) (opens in a new tab)

    scikit-learn2026Documentation

    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)

  1. 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

    Used for Feature hashing for large-scale multitask problems and the exponential tail bounds on interference between random subspaces (abstract).

  2. 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

    Used for A special kind of target leakage and prediction shift in boosting, and an algorithm for categorical features designed to counter it (abstract).

  3. Point-in-time joins (Feast documentation) (opens in a new tab)

    Feast2026Documentation

    Used for Point-in-time correct joins that scan backward from each entity timestamp, and a TTL that is relative to each timestamp.

  4. Rules of Machine Learning: Best Practices for ML Engineering (opens in a new tab)

    Google for Developers2026Article

    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.

  5. 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

    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)

  1. 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

    Used for ML-specific risk factors including data dependencies, hidden feedback loops and changes in the external world (abstract page).

  2. scipy.stats.ks_2samp (opens in a new tab)

    SciPy2026Documentation

    Used for The two-sample KS test, its statistic as the maximum absolute difference between empirical distribution functions, and the continuity assumption.