Lawfare Group → Knowledge Institute → Lawfare Academy
← CS 230 — Mathematics, Statistics and Data for AI
Weeks 12–14
Missing data, preprocessing and leakage
Learning objectives
- Explain and trace the mechanisms in missing data, preprocessing and leakage.
- Apply the method to the worked example and changed-condition exercise.
- Identify assumptions, failure cases and the evidence needed to justify a result.
- Test the added failure-mode fixture and explain which guarantee the evidence does and does not establish.
Current study directions: use the original Academy preparation chapters, preserved teaching and complete optional worked reasoning on LawfareGroup.com. Retained attributed readings, source exercises and historical assignment directions are optional further study. This notice supersedes earlier textbook-supported directions preserved below and in historical companions. Independent subject review and observed learner testing remain pending.
Missingness has meaning. A blank value can indicate not measured, not applicable, collection failure or a decision not to report. Replacing all blanks with zero imposes a substantive claim that may be false. Record missingness patterns and evaluate whether a missingness indicator is informative or merely encodes an unstable collection process.
Preprocessing is part of the model pipeline. Learn scaling parameters, imputation values and feature-selection rules from the training partition only, then apply them to validation and test data. Computing a mean from the entire dataset leaks information from the evaluation set into training. Even operations that do not use labels can transmit information about the future distribution.
Temporal leakage is particularly subtle. A field called final_invoice_status may be accurate but unavailable when the prediction must be made. A random split does not solve that problem. Define the prediction timestamp, feature availability and label observation window. Group leakage occurs when related records, such as repeated visits from one customer, appear on both sides of a split intended to represent new customers. Evaluation design must imitate the proposed use.
Worked reasoning The fill value is 4, learned only from known training values. The extreme test value does not shift it. This is a demonstration of partition discipline, not a universal endorsement of mean imputation. Categorical and time-series data need different considerations, and an all-missing training feature needs an explicit policy.
Extended teaching and laboratory
Preprocessing learns information from data. Imputation, scaling, feature selection and vocabulary construction therefore belong inside the training process. In cross-validation, each fold’s transformer must be fitted on that fold’s training portion. Fitting once on all data before folding lets validation observations influence the representation used to predict them.
A final untouched test set estimates performance after model selection. Repeatedly checking it and changing the pipeline makes it part of development. Keep records of partition logic, especially for grouped or time-dependent observations.
Worked problem Training values are [2,None,6]; held-out values are [100,None]. Compare training-only mean imputation with a mean fitted on all observed values.
Step-by-step reasoning 1. The training-only mean is 4. Replace missing values with 4 in both training and held-out data.
- Using all observed values gives (2+6+100)/3=36. This allows the held-out feature distribution to alter the learned transformer.
- Even without using labels, the evaluation no longer represents the declared training-only fitting process.
- For cross-validation, repeat fitting within each fold. Preserve groups and chronological boundaries where the prediction setting requires them.
Failure-oriented laboratory: Group leakage, missingness and deployment-time availability
A dataset split is part of the measurement design. If multiple rows belong to one customer, patient, device or document family, a random row split can place closely related observations in both training and evaluation. The resulting score may measure recognition of groups already seen rather than generalization to new groups. Choose the split unit to match the deployment question.
Preprocessing must also respect the boundary. Fit imputation, scaling and feature selection on training data, then apply the learned transformation to held-out data. Computing a fill value from the complete dataset leaks evaluation information even when labels are not directly used. Missingness can carry information, but its meaning may change when collection processes change.
Finally ask whether each feature exists at prediction time. A field created after an outcome is not a legitimate predictor for an earlier decision. Document availability timestamps, group identifiers and the target horizon. A reproducible report includes rejected features and reasons, not just the winning model and score.
Worked fixture
A fixture contains 100 customers with 10 rows each. A random row split puts nearly every customer on both sides. A feature named final_resolution is created after the outcome being predicted.
Explain the fixture
Use a customer-disjoint split when the task is prediction for previously unseen customers. Remove final_resolution because it is unavailable at decision time. A row split may still answer a different repeated-customer question, but that deployment target must be explicit. Never select whichever split yields the most attractive score.
Integrated application: implementation, debugging and local deployment
The complete service-company project is now part of this unit’s applied work. It supplies an inspectable browser interface, HTTP server, persistent SQLite ledger, transaction tests, export recovery, permission-scoped retrieval and a separate synthetic logistic evaluation pipeline. Begin with its actual test suite, then trace one user request from UI to storage and back. The README distinguishes the local teaching environment from a production deployment.
Course-specific investigation
Audit the model pipeline’s preprocessing and split boundaries. Replace the fixture with grouped synthetic data, add disjoint-group assertions and a feature-availability timestamp. Demonstrate the failure caused by preprocessing on the full dataset.
What the evidence must establish
Identify the prediction target before choosing a group or time split. Learn statistics on training data only. A repeated deterministic result is reproducibility, not evidence that leaked evaluation is valid.
Keep a reproducibility log with Python version, launch command, fixture, expected result, observed result and explanation of any discrepancy. Introduce one deliberate defect and show the corresponding failing test before restoring the implementation. Passing an existing test without explaining its boundary is insufficient. The integration project remains optional practice rather than a mandatory capstone submission.
A transformation is fitted state inside an evaluation design
The original training-only imputation investigation remains the starting point. Extend it by writing a feature contract: row identity and customer group, prediction time, outcome horizon, each input's type and units, valid range, availability time and missing-value meaning. A blank can mean collection failure, not applicable or withheld information. Those mechanisms can associate with outcomes and change across sites. An observed association does not establish that replacing the blank recovers the missing value or preserves a causal estimand.
For a numerical column, mean or median imputation learns a replacement from observed training entries. A constant fill is an explicit policy rather than an estimated value. A missingness indicator can preserve the fact that a value was absent, but can also encode an unstable collection practice. An entirely missing training column has no empirical mean; choose and document an explicit fallback or exclusion instead of dividing by zero. More elaborate iterative or nearest-neighbor imputers add model assumptions and hyperparameters. They must be fitted and evaluated within training folds just like a predictor.
Standard scaling learns training mean μ and standard deviation s, then transforms x to (x−μ)/s. For training [2,6], using the population standard deviation convention gives μ=4,s=2 and transformed values [−1,1]. A held-out100 becomes48; refitting the scaler on held-out observations would implement a different procedure. Libraries can use different variance conventions; name the convention before comparing numbers. A zero-variance feature cannot use literal division by zero; handle it under a declared policy. Extreme held-out standardized values can reveal extrapolation or shift, not automatically a coding error.
Min–max scaling learns endpoints and maps x to (x−min)/(max−min). For the same training data,100 maps to24.5, outside[0,1]. This is expected when a new value exceeds the training maximum. Clipping would change the rule and discard that magnitude information. Robust scaling instead uses training quantiles; it may reduce sensitivity to extreme values but does not establish representativeness or eliminate the need to evaluate shift.
Categorical encoders learn a vocabulary and column order. With training categories blue and red, a one-hot representation might assign[1,0] and[0,1]. A new green category requires a documented unknown-category behavior, such as rejection or a separate unknown column. Silently reordering columns or treating green as red violates the model contract. Ordinal integer codes create a numeric order that nominal categories do not possess. When an encoder uses target statistics, additional leakage controls are needed; never encode evaluation labels into their own inputs.
A pipeline packages fitted preprocessing followed by an estimator. A column-wise transformer can apply different numerical and categorical rules and concatenate outputs in a stable order. During fitting, transformations learn from the training subset; prediction applies those saved transformations without relearning from the target batch. In cross-validation, fit the entire pipeline independently on each fold's training data. Feature selection, vocabulary construction and dimensionality reduction also learn from data even when labels are not used. Fitting them globally before folding contaminates the evaluation boundary.
For independent observations a random split can approximate new draws from the same population. Grouped splits address new entities; chronological splits address future periods. The choice follows deployment, not the highest score. A customer-disjoint split alone does not enforce time availability, while a time split alone can include recurring customers. Declare both when the intended use requires both. Reserve an untouched final set after development choices; repeated adaptation to its results turns it into development evidence. Cross-validation variability is not automatically a confidence interval for every future setting.
Distribution shift can concern input frequencies, outcome prevalence or the input–outcome relationship. Changed devices, policies, customers and label collection can all matter. A preprocessing pipeline preserves a specified fitting procedure; it does not certify stability of those relationships. Monitor data contracts and performance with denominators, record delayed labels, and distinguish unlabeled input checks from observed predictive performance. Reproducibility of a seed or fixture cannot establish validity of leaked evaluation.
Optional changed record: trace fitted values through a fold
Training values are[1,missing,5] and held-out values are[9,missing]. Fit a mean imputer, then standard scaling on the imputed training column using population variance. Calculate both transformed partitions. A colleague instead fits the imputer on all observed values and calls the result acceptable because labels were unused.
The training fill is3, so training becomes[1,3,5] and held-out becomes[9,3]. The training mean is3 and population variance is(4+0+4)/3=8/3, giving standard deviation √(8/3). Training outputs are[−√(3/2),0,√(3/2)], while held-out outputs are[3√(3/2),0]. The alternative fill(1+5+9)/3=5 transmits the held-out feature distribution into fitted state. Omitting labels does not restore the declared training-only boundary. In another cross-validation fold, relearn both imputer and scaler using only that fold's training rows.
Optional criteria: distinguish missingness meaning from numerical replacement; reproduce the fitted statistics with their convention; trace the same saved transformations into held-out data; justify entity/time/availability boundaries and remaining shift limits. Award one point per fully explained criterion. The preserved native leakage case and complete application provide further optional implementation practice.
Apply the idea
Training values are [2,None,6]; held-out values are [100,None]. Compare training-only mean imputation with a mean fitted on all observed values.
Each customer has several rows. Random row splitting places the same customer in train and test. When is that a misleading evaluation?
Additional laboratory — Write assertions that train/test group intersections are empty, all fitted preprocessing uses training rows and feature timestamps precede the prediction cutoff. Compare a group split and a time split for their different questions.
Complete-application investigation: Audit the model pipeline’s preprocessing and split boundaries. Replace the fixture with grouped synthetic data, add disjoint-group assertions and a feature-availability timestamp. Demonstrate the failure caused by preprocessing on the full dataset.
Read the worked reasoning
It is misleading when deployment must generalize to unseen customers, because the test can benefit from customer-specific patterns already represented in training. Split by customer for that estimand. If deployment predicts future visits of known customers, a time-respecting design may be more appropriate. The correct split follows the intended deployment question.
Additional laboratory model — Assertions must fail when a duplicate group or future-created feature is deliberately inserted. A group split tests new entities; a time split tests later periods and may include recurring entities. Neither automatically substitutes for the other. State both the inference target and remaining distribution-shift risks.
Application reasoning model: Identify the prediction target before choosing a group or time split. Learn statistics on training data only. A repeated deterministic result is reproducibility, not evidence that leaked evaluation is valid.
Check understanding
Where should an imputation mean be learned?
- Independently from every test batch
Feedback
Refitting at inference changes the model and may create unstable behavior.
- From the training partition only
Feedback
Held-out data must not influence learned preprocessing.
- From the full dataset including held-out outcomes
Feedback
Whole-dataset fitting contaminates the evaluation.
Further reading
Current study directions: use the original Academy preparation chapters, preserved teaching and complete optional worked reasoning on LawfareGroup.com. Retained attributed readings, source exercises and historical assignment directions are optional further study. This notice supersedes earlier textbook-supported directions preserved below and in historical companions. Independent subject review and observed learner testing remain pending.
Read the original on-site preparation chapter and preserved investigation. Work the changed record before opening its full model. Earlier source assignment directions remain in immutable edition4.
- Original on-site preparation — A transformation is fitted state inside an evaluation design
- 2.2. Data Preprocessing Open the notebook in SageMaker Studio Lab
- 4.7. Environment and Distribution Shift Open the notebook in SageMaker Studio Lab
- 8.4. Imputation of missing values
- 8.3. Preprocessing data
- 8.1. Pipelines and composite estimators
- 12. Common pitfalls and recommended practices
- Primary documentation for Group leakage, missingness and deployment-time availability
- Academy — runnable synthetic lab kit and instructions
- Academy — complete application, source, integration tests and local deployment guide