Prevent data leakage in your first machine learning project
By Future Data Academy · 3 min read · Updated
A practical guide to train/test splits, preprocessing, time-aware evaluation and checking what information exists at prediction time.
A model can score impressively during development and fail on new cases because its evaluation contains information it would not have at prediction time. This is data leakage. Start with the prediction decision, not the algorithm.
Define the moment of prediction
Suppose you predict whether an order will be returned, immediately after checkout. A return-approved flag is not a usable input: it only exists after the outcome. Neither is a customer summary that accidentally includes returns occurring after this order. For every proposed feature, write when and how it becomes available.
This is different from a weak predictor. An unhelpful but available feature may simply fail to improve performance; a future-only feature makes the experiment unrealistic.
Split before learning transformations
For an independent-row dataset, reserve test examples before fitting imputers, scalers, feature selectors or the model. Learn transformation parameters from the training data, then apply those fitted transformations to validation or test data. Even an imputer fitted on all rows uses information about the held-out population.
A pipeline can keep these steps together during cross-validation. For example, with numeric inputs and a binary classification target:
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
model = make_pipeline(
SimpleImputer(strategy="median"),
StandardScaler(),
LogisticRegression(max_iter=1000),
)
model.fit(X_train, y_train)
predictions = model.predict(X_test)
Here X_train, X_test, y_train and y_test are already separated inputs. This is a workflow illustration, not a complete experiment or a claim about accuracy. A pipeline cannot repair features that already contain future information.
Choose a split that matches deployment
Random splitting is not always appropriate. If several rows belong to the same person, placing that person in both sets can exaggerate generalization to new people. Use a group-aware split when the evaluation question is performance on unseen groups. For forecasting, train on earlier observations and evaluate on later ones; do not randomly mix future observations into training.
Time splits may also need a gap when labels or features span overlapping windows. The right split depends on when labels become available and what a future production prediction would know.
Keep the final test set for the final question
Repeatedly choosing features and settings based on test scores turns the test set into part of model development. Use validation or cross-validation for those choices. Evaluate the final selected procedure on the reserved test set, and report the sample size, metric and relevant limitations.
A single accuracy figure can hide failure on a minority class. Compare a simple baseline and inspect the kinds of errors that matter for the decision. Do not claim that a better test score proves fairness or deployment readiness.
Audit your project
Create a table with four columns: feature, availability time, transformation fitted on, and leakage risk. Check duplicate entities across splits, target-derived fields, future aggregates and preprocessing fitted before splitting. Ask another reader to reconstruct the sequence from your saved code.
As an exercise, explain why “days until return” is invalid at checkout, but “number of completed prior orders before checkout” may be valid when calculated without future records. Then describe how your split changes if the goal is prediction for entirely new customers.
Explore the course catalog for machine learning and model evaluation lessons. Use a private note to document the assumptions in your own split.
Further reading: scikit-learn's official guide to common pitfalls and data leakage. The academy example is original and simplified; the reference offers additional implementation guidance.
