All lessons in Machine Learning Engineering: Reliable Predictive Models

Fit Preprocessing Inside the Split

Handle missing values, categories, and scaling without leaking validation information.

30 minutes · Free lesson

What you will learn

  • Explain why every statistic used for imputation, encoding, or scaling must be estimated from training rows only.
  • Hand-compute training-only imputation and standardization values and show how pooling validation rows changes them.
  • Judge whether a candidate dispatch feature exists at prediction time and recognise that a Pipeline cannot repair a feature that will be unavailable.

The carrier's late-delivery model scores a parcel at the moment the van door closes. At that instant the row contains the depot's dispatch load, a weather risk score, a weekend flag, and whatever else the dispatch system has already recorded. Before any of that reaches a logistic regression or a forest it is cleaned: missing scores are filled, categories are turned into numbers, continuous columns are rescaled. Each of those cleaning steps learns something from data, and what it learns must come from the same rows the model is allowed to learn from. This lesson is about keeping that boundary intact.

Preprocessing is fitting

A mean imputer stores a mean. A standard scaler stores a mean and a standard deviation. A one-hot encoder stores the list of categories it has seen. A target encoder stores a per-category late rate. These are parameters, estimated from rows, exactly like the weights of a model. If you estimate them on the full table and then split the table into training and validation parts, every validation row has already influenced the numbers used to transform it.

The effect on a single value is often small, which is why people dismiss it. The effect on the trustworthiness of a selection decision is not small: you are comparing procedures that used information outside the intended training boundary. The observed score can move either way on a particular sample; its validity, not a guaranteed numerical improvement, is the issue.

Worked example: filling a missing weather score

Suppose a small development table has been split by row index before anything else happens. The weather risk column, on a scale from 0 to 10, looks like this.

Splitweather_risk values
training2, 4, 6, 8, missing
validation10, missing

Worked example

Mean imputation fitted correctly and incorrectly

  1. Fit the imputer on training rows only. The non-missing training values are 2, 4, 6, 8, so the stored mean is (2 + 4 + 6 + 8) / 4 = 20 / 4 = 5.
  2. Transform both splits with that stored value. The missing training entry becomes 5 and the missing validation entry also becomes 5. The validation row with value 10 is untouched.
  3. Now repeat the mistake of fitting on the pooled table. The non-missing values across both splits are 2, 4, 6, 8, 10, so the pooled mean is 30 / 5 = 6.
  4. Under the leaky fit, the missing validation entry becomes 6 instead of 5. That number was pulled upward by the validation row holding a 10, a row the dispatch system would not have had when the imputer was really built.
  5. Interpretation: the shift from 5 to 6 is one unit on a ten-point scale. With five training rows it is visible; with many more comparable rows this particular change would often be smaller, but the principle is the same and the leaked quantity can be larger for rare categories or skewed columns.

Scaling with training statistics

Standardization subtracts a mean and divides by a standard deviation so that penalised linear models treat columns on comparable scales. The scikit-learn StandardScaler stores the mean and the population standard deviation (dividing the squared deviations by the row count, not the row count minus one) of the training rows it was fitted on. Use the same convention when you check by hand.

Worked example

Standardizing dispatch load for new parcels

  1. Training dispatch_load values are 40, 60, 80, 100, 120. The mean is 400 / 5 = 80.
  2. Deviations from the mean are minus 40, minus 20, 0, 20, 40. Their squares are 1600, 400, 0, 400, 1600, summing to 4000. Dividing by the row count 5 gives a variance of 800, and the standard deviation is the square root of 800, approximately 28.284.
  3. A validation parcel with dispatch_load 150 is transformed to (150 minus 80) / 28.284, approximately 2.475. A validation parcel with load 20 becomes (20 minus 80) / 28.284, approximately minus 2.121.
  4. Both validation values lie outside the training range, and that is fine. The scaler does not clip; it applies the stored linear map. The model will see values beyond anything it trained on, which is a real property of deployment and should be visible in validation, not hidden by refitting the scaler on the pooled table.
  5. If the scaler had instead been fitted on all seven rows including 150 and 20, the mean would be 570 / 7, approximately 81.43, and the spread would widen, changing the transformed values. The validation score would describe a procedure that used evaluation information during fitting.

Categories the model has never met

One-hot encoding turns a depot code into a group of indicator columns. The encoder fitted on training rows that mention depots A, B, and C produces three columns. A validation parcel from depot D has no column of its own. The correct behaviour is to decide, before looking at validation data, how unknown categories are handled: in scikit-learn the handle_unknown setting can map them to all-zero indicators, which is an honest statement that the model knows nothing about this depot. Refitting the encoder on pooled data to create a D column quietly assumes D will always be known, and that assumption fails the first time a new depot opens. Note that the base workbook dataset has no depot column; depots here are a hand fixture for the design discussion.

Target encoding is riskier. Replacing depot A with the late rate of depot A is a model in itself, and if the rate includes the current row's own label, the feature leaks the answer into the input. Compute the rate from training rows only, and if you must use it on training rows too, compute it in an out-of-fold manner so no row sees its own label. Unseen categories get a fallback such as the overall training late rate.

The split comes first, then the Pipeline

The order of operations that keeps the boundary intact is simple to state. First choose the split that matches future use, which for the carrier would be a time-ordered split with dispatch dates before evaluation dates, or a group split by depot if generalisation to new depots is the question; the base workbook uses explicitly independent synthetic rows, so a random split is defensible there and the time or group versions are design extensions. Second, fit every transformer on the training part only. Third, transform validation rows with the stored parameters. Inside cross-validation this repeats for every fold, so the imputer, scaler, and encoder are refitted each time on that fold's training rows.

A scikit-learn Pipeline enforces this mechanically: calling fit on the pipeline fits each step in sequence on the training rows handed to it, and calling predict applies stored parameters only. Combined with cross_val_score or a search object, the pipeline is refitted inside each fold automatically, which removes the most common accidental leak. Feature selection belongs inside the pipeline for the same reason: choosing the top columns by correlation with the label on the full table is a fit operation.

What a Pipeline cannot do is tell you whether a column will exist at dispatch. Consider these candidates.

Candidate columnKnown when the van leaves?Verdict
dispatch_loadyes, counted at the depotusable
weather_riskyes, from the morning forecastusable
minutes_driver_stoppedno, recorded during the routeunavailable, leaks the outcome
customer_complaint_filedno, happens after deliveryunavailable, leaks the outcome

The last two would pass through a perfectly constructed pipeline and produce a spectacular validation score that evaporates in production. The defence is a written prediction contract listing the exact timestamp at which each column is frozen, checked against the data source, not against the file's column names.

Two mistakes that look like diligence

The first is standardizing or imputing the whole table at load time because it feels like tidy data hygiene, then splitting. The code reads cleanly and the leak is invisible in the metrics. The fix is to make the split the first line of the modelling script and to keep raw columns until a pipeline consumes them.

The second is fitting the encoder on pooled data because an unseen category raised an error during validation. The error was the correct signal; the pooled refit silences it and misreports how the model handles novelty.

Investigate in the workbook

Download the Machine learning investigation workbook, unzip it, create a Python 3.12 environment, install requirements.txt, then run python ml_workbook.py --development-only --output results followed by python -m unittest discover -s tests -v. Open report.json and read the manifest section to see how rows were assigned to training, validation, and the sealed final split. Then read the source and locate where preprocessing and model fitting are called: confirm that nothing with a fit method touches validation or final rows before evaluation. As an experiment, introduce the leak deliberately in a copy of the script by scaling the full synthetic-parcels.csv before the split and compare the development metrics of the logistic model between the two versions. The difference you observe is specific to your run; do not generalise either its size or sign. Explain the boundary violation even if the metric barely changes or becomes worse.

Exercise

A training column of parcel weight in kilograms has the values 3, 7, 1, 9, missing, 5. A median imputer is fitted on these rows. What value fills the missing entry, and what value fills a missing entry in a later validation row whose other neighbours happen to have weights 20 and 30?

Check your answer

The imputer stores one number from training rows only. The non-missing training values sorted are 1, 3, 5, 7, 9, whose median is the middle value 5. The missing training entry becomes 5. The validation entry also becomes 5, because the stored parameter does not change when validation rows arrive; the values 20 and 30 are irrelevant to the fitted imputer.

Exercise

A scaler fitted on training dispatch_load rows stored a mean of 80 and a population standard deviation of approximately 28.284. Standardize two validation loads of 94 and 66, and state what the two transformed values add to.

Check your answer

For 94: (94 minus 80) / 28.284 = 14 / 28.284, approximately 0.495. For 66: (66 minus 80) / 28.284 = minus 14 / 28.284, approximately minus 0.495. They sum to 0 because the two raw values are symmetric around the stored training mean of 80, not because validation data was used to centre anything.

Exercise

Training rows for a hand-fixture depot column have labels (1 means late) as follows: depot A has labels 1, 0, 1, 1 and depot B has labels 0, 0, 1. A target encoder replaces a depot code with the training late rate and uses the overall training late rate for unseen depots. What values are assigned to a validation parcel from depot A and to a validation parcel from a new depot D?

Check your answer

Depot A has 3 late parcels out of 4, so its encoded value is 0.75. Depot D was never seen in training, so it receives the overall training rate: total late parcels are 3 + 1 = 4 out of 4 + 3 = 7 rows, giving 4 / 7, approximately 0.571. Neither value uses any validation label, which is the point.

Further reading

Summary

Imputers, scalers, and encoders are fitted objects whose parameters must be estimated from training rows only, refitted inside every cross-validation fold, and applied unchanged to validation and final rows. A Pipeline enforces that mechanically. It cannot detect columns that will not exist at dispatch, so the prediction contract must list when each feature is frozen, and any feature recorded after the van leaves is excluded by design rather than by code.

Next action

Run the workbook once, open report.json, and write down the three split sizes from the manifest and the line in the source where the first fit call happens, confirming it receives training rows only.

Choose another lesson