Data · Guide

Data Preparation

Exploratory analysis, cleaning, feature engineering and splitting — the work that sets your ceiling before any model is chosen.

— min read Data

Where the Work Actually Is

Practitioners consistently report spending most of their time here rather than on modelling. That is not a failure of tooling — preparation is where the accuracy comes from.

Your features set the ceiling. A good model on weak features loses to an ordinary model on strong ones, every time. Swapping algorithms moves a metric by a fraction of what a well-constructed feature does.

This section is also where the most damaging mistakes happen, because they are silent. A leak or a bad join does not throw an error — it produces an excellent validation score and a model that fails in production.

The order matters: look at the data, clean it, split it, then engineer features using only the training part. Doing those last two in the wrong order is the single most common serious error in applied machine learning.

Exploratory Analysis

Before any transformation, find out what you actually have. The goal is not pretty charts — it is discovering the problems early, while they are still cheap.

CheckWhat you are looking for
Row and column countDoes it match what you were promised?
Missingness per columnWhich columns are unusable, and is the missingness patterned?
Distribution of each numericSkew, bimodality, impossible values
Cardinality of each categoryAn ID masquerading as a feature
Duplicate rowsUsually a join that fanned out
Target balance1% positives changes everything downstream
Correlation with the targetAnything suspiciously perfect is a leak
A feature that predicts the target almost perfectly is not a triumph, it is a bug. Something derived from the answer has ended up in your inputs. Find it before you celebrate.

Plot before you summarise. Identical means and variances hide completely different shapes, and the shape decides which transformations make sense.

Cleaning & Missing Values

Ask why a value is missing before deciding what to do about it. The mechanism decides whether dropping is harmless or destroys your sample.

MechanismMeaningDropping rows is…
MCARMissing completely at randomSafe, just wasteful
MARMissing depends on other observed columnsBiased unless you account for it
MNARMissing depends on the missing value itselfActively dangerous

Income left blank by high earners is MNAR: dropping those rows removes exactly the people you most need. Often the fact of missingness is itself predictive, so add a boolean was_missing column rather than pretending the gap never existed.

StrategyUse whenCost
Drop the rowFew rows affected, MCARLoses data, can bias
Drop the columnMostly empty and not importantLoses a signal you cannot recover
Mean or median fillNumeric, small gapsShrinks variance, invents certainty
Category "Unknown"CategoricalHonest, and often predictive
Model-based imputationGaps matter and data is richComplexity, and a new leak risk
Compute the fill value from the training split only. Taking the median of the whole dataset lets test-set information reach your model, and the score you then report is not real.

Outliers deserve the same question. A negative age is an error and should be fixed. A very large transaction may be the exact case you are trying to detect — deleting it because it is inconvenient is how fraud models get built that never fire.

Feature Engineering

Turning raw columns into things a model can use. Domain knowledge pays off here more than anywhere else in the pipeline.

TechniqueForNotes
One-hot encodingLow-cardinality categoriesExplodes with many categories
Ordinal encodingCategories with a real orderImplies spacing that may not exist
Target encodingHigh-cardinality categoriesLeaks badly unless fitted inside folds
ScalingDistance and gradient modelsTrees do not need it
Log transformRight-skewed numericsPrices, counts, durations
BinningNon-linear effectsDiscards information; use sparingly
Date partsTimestampsDay of week and hour usually beat the raw stamp

Scaling matters for anything measuring distance or following a gradient — k-nearest neighbours, SVMs, neural networks, and regularised regression. Tree-based models split on thresholds and are indifferent to it, which is one reason gradient boosting is so forgiving on tabular data.

Fit every transformer on the training split and apply it to the others. A scaler fitted on all your data has already seen the test set. Pipelines exist mainly to make this mistake hard to commit.

Train, Validation & Test Splits

Three sets, three jobs. Train fits the parameters. Validation chooses between models and settings. Test is looked at once, at the end, to estimate real performance.

Every time you tune against the test set you contaminate it a little, and its estimate drifts optimistic. That is what the validation set is protecting.

SituationSplit it byBecause
Ordinary tabular dataRandomRows are independent
Imbalanced targetStratifiedKeeps the rare class in every fold
Time seriesChronologicallyYou cannot train on the future
Several rows per userBy user (grouped)Otherwise the same person is in both sides
Data leakage is the defining failure of this stage: any information in training that would not exist at prediction time. It shows up as a validation score that looks too good and a production model that does not work. Split first, engineer second.

With limited data, k-fold cross-validation gives a more stable estimate than one split, because every row is used for validation exactly once. Keep a genuinely untouched test set anyway.

Common Mistakes

MistakeWhat it produces
Scaling or imputing before splittingLeakage; an inflated score that never reproduces
Random split on time seriesTraining on the future; useless in production
Random split with repeat usersThe same person on both sides of the split
Dropping every row with a gapSilently biased sample when missingness is patterned
Deleting outliers by defaultRemoving the very events you were asked to detect
Target encoding outside foldsThe strongest and most convincing leak there is
Tuning against the test setNo honest estimate of performance left

Interview Questions

What is data leakage and how do you prevent it?

Any information available in training that would not exist at prediction time. Prevent it by splitting first and fitting every transformer — scalers, imputers, encoders — on the training split alone, then applying to the rest. Pipelines make this the default.

Why split time series chronologically?

A random split lets the model learn from the future to predict the past, which it can never do in production. Train on earlier periods, validate on later ones.

MCAR, MAR, MNAR — why does it matter?

It decides whether dropping rows is safe. MCAR is merely wasteful. MAR biases you unless you account for the related columns. MNAR — where missingness depends on the hidden value, like high earners omitting income — removes exactly the cases you need.

Which models need feature scaling?

Anything using distance or gradients: k-NN, SVMs, neural networks, regularised regression. Tree-based models split on thresholds and are unaffected.

Your validation accuracy is 99%. What do you check first?

Leakage. Look for a feature derived from the target, a row that appears on both sides of the split, or a transformer fitted before splitting. A near-perfect score on real-world data is a bug until proven otherwise.

Why three sets rather than two?

Validation is used repeatedly to choose models and hyperparameters, so it gradually stops being an honest estimate. The test set is held back and looked at once, at the end.

Quick Quiz

1. You should fit a scaler on…
2. Time-series data should be split…
3. High earners leaving income blank is…
4. Which model type is indifferent to feature scaling?
5. A feature correlating almost perfectly with the target usually means…