Leak-Proof Preprocessing and Training Pipeline Design
Machine LearningModel answerLast updated
Design an end-to-end workflow that validates, cleans, splits, fits, and serves a model so that no statistic from held-out or future data influences training.
You are handed a tabular dataset and asked to build a workflow that turns raw records into a trained predictive model. The same workflow must later be applied, unchanged, to held-out evaluation data and to new records that arrive after deployment.
Describe the design of this workflow:
- What each stage is responsible for, and in what order the stages run.
- Where and how information leakage could creep in, and what you do to stop it.
- What gets saved so that serving-time behaviour matches training-time behaviour.
- How the workflow reacts to missing, malformed, or previously unseen values.
The schema, target, missingness patterns, and model family are intentionally not given. Pick a concrete illustrative scenario and state your assumptions. Let the actual data contract drive your cleaning choices. Do not simply discard every row with a missing value, and do not compute any preprocessing statistic on the full dataset before splitting.
Questions worth settling in your answer:
- What is one observation, and are rows independent, grouped (for example, several rows per customer), or ordered in time?
- Which columns are features, identifiers, labels, or information that would not exist at prediction time?
- How are missing, invalid, duplicate, and unseen categorical values treated?
- Which preprocessing quantities must be learned from training data only?
Hints
Hint 1
Start from the unit of prediction and the moment of prediction: what is known at that moment, and how are rows related (independent, grouped, or temporal)? That determines how you split.
Hint 2
Separate stateless steps (type coercion, schema checks, deterministic fixes) from stateful steps (imputation values, scaling parameters, category vocabularies, target encodings). Only the stateful ones need fitting, and they must be fitted on the training portion only.
Hint 3
Bundle preprocessing and model into one serializable object, and think about what happens when a request arrives with a missing column, a wrong type, or a category never seen in training.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Illustrative scenario
Assume we predict whether a subscription customer will cancel within 30 days. Each row is a customer snapshot taken at a scoring date, with numeric usage fields, a few categorical fields (plan, region), a timestamp, a customer ID, and a binary label. Some customers appear in several snapshots, and missing values exist in income-like and usage fields. These assumptions drive the choices below; with different data, the same principles apply but the specifics change.
Stage 0: Define the data contract
Before touching values, write down the contract: column names, types, allowed ranges, nullability, which columns are features, which are identifiers (kept for joins and grouping, never fed to the model), and which are unavailable at prediction time (for example, a "cancellation reason" field filled in after the event). Removing such columns is the first and most important leakage defence.
Stage 1: Stateless validation and cleaning
These steps use no learned statistics, so they are safe to apply before splitting and identically at serving time:
- Enforce types, parse dates, normalise strings (case, whitespace), map known sentinel values (-1, "N/A", 9999) to proper nulls.
- Flag impossible values (negative age, future dates) as invalid; set to null or reject depending on severity.
- Deduplicate exact duplicate records. Be careful with near-duplicates of the same entity: they matter for splitting (below).
- Log every decision (rule, count of affected rows) so cleaning is auditable and reproducible.
Missingness is information. Do not drop all incomplete rows: it shrinks the data, can bias it if missingness correlates with the label, and does nothing for serving, where incomplete records will still arrive. Drop a row only when the label is missing or the key identity is unusable. Drop a column only if it is almost entirely null or violates the contract.
Stage 2: Leakage-aware split
Split before fitting anything.
- Independent rows: random stratified split (train / validation / test, for example 70/15/15), stratifying on the label if it is imbalanced.
- Grouped rows (several per customer): use a group split so no customer appears on both sides. Otherwise the model memorises the entity and the metric is inflated.
- Time-ordered data: split chronologically (train on the past, validate and test on the future), and use rolling or expanding-window cross-validation for tuning.
- The test set is touched once, at the end. Hyperparameter search and model selection use validation or cross-validation only.
Stage 3: Stateful transformations, fitted on training data only
Everything that learns from data goes inside the pipeline and is fitted on the training fold only:
- Imputation: median or mean for numerics, most frequent or an explicit "missing" level for categoricals. Add missing-indicator columns when missingness may be informative.
- Scaling: means and standard deviations (or robust quantiles) from training data.
- Categorical encoding: vocabulary learned from training; rare levels grouped into "other". Target encoding, if used, must be computed out-of-fold inside the training set, otherwise the label leaks into the features.
- Outlier capping: percentile thresholds from training data.
- Feature selection and dimensionality reduction: also fitted on training only.
Validation and test data only go through transform, never fit. During cross-validation, the whole pipeline is refit per fold, since fitting the scaler on all data and then cross-validating the model is a classic subtle leak.
Time-based features (rolling averages, "days since last login") must be computed using only information available up to each row's scoring date.
Stage 4: Model training and evaluation
Fit the model on the transformed training data, tune on validation or CV, and pick the metric to match the problem (PR-AUC or recall at a precision target for imbalanced churn, not accuracy). Report the final score on the untouched test set once. Compare against a trivial baseline to catch suspiciously high results, which usually indicate leakage.
Stage 5: Persist one artifact
Serialize a single pipeline object containing the schema, the cleaning rules, the fitted transformers (with their learned parameters), the model, and version metadata (data snapshot, code version, training date, metrics). Serving loads this one object, so training and inference cannot drift apart through reimplemented preprocessing.
Stage 6: Inference-time behaviour
- Schema check first: missing required columns or wrong types produce a clear error or a safe fallback, not a silent wrong prediction.
- Missing values: handled by the training-fitted imputers.
- Unseen categories: mapped to "other" or the unknown bucket, with a counter incremented (never crash, never invent a new column).
- Out-of-range values: clipped or flagged using training-derived bounds.
- Output checks: probabilities in [0, 1], no NaNs.
Stage 7: Monitoring
Track input drift (feature distributions versus training, rate of nulls and unseen categories), prediction drift, and, when labels arrive, real performance. Set alerts and a retraining trigger. Retraining reruns the entire pipeline from the split onward.
Trade-offs
- A group or time split gives lower but honest metrics compared with a random split; accept that.
- Richer imputation (model-based) may help accuracy but adds state and latency to serving.
- Strict rejection of bad records protects quality but can cause outages; a quarantine-and-default policy is often a better balance.
Common mistakes
- Fitting imputers or scalers on the full dataset before splitting.
- Random splitting of grouped or temporal data.
- Keeping post-outcome columns or identifiers as features.
- Target encoding without out-of-fold computation.
- Tuning repeatedly against the test set.
- Reimplementing preprocessing separately for serving.
- Dropping all rows with nulls, then having no plan for nulls in production.
- Dropping duplicates only after the split, so copies end up on both sides.
Minimal code sketch (scikit-learn style)
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.model_selection import GroupShuffleSplit
from sklearn.ensemble import GradientBoostingClassifier
import joblib
num = Pipeline([("imp", SimpleImputer(strategy="median", add_indicator=True)),
("sc", StandardScaler())])
cat = Pipeline([("imp", SimpleImputer(strategy="most_frequent")),
("oh", OneHotEncoder(handle_unknown="ignore", min_frequency=20))])
pre = ColumnTransformer([("num", num, num_cols), ("cat", cat, cat_cols)])
pipe = Pipeline([("pre", pre), ("model", GradientBoostingClassifier())])
gss = GroupShuffleSplit(n_splits=1, test_size=0.2, random_state=0)
tr, te = next(gss.split(X, y, groups=df["customer_id"]))
pipe.fit(X.iloc[tr], y.iloc[tr]) # all statistics learned here only
score = pipe.score(X.iloc[te], y.iloc[te])
joblib.dump(pipe, "churn_pipeline_v1.joblib")
Because the preprocessing lives inside the pipeline, cross-validation and serving both reuse exactly the fitted state.