Train-Test Split, Cross-Validation & Avoiding Data Leakage
Train-Test Split, Cross-Validation & Avoiding Data Leakage
The true measure of a machine learning model is its ability to generalize to unseen future data. Evaluating a model on the same data it was trained on produces overly optimistic performance estimates due to overfitting. Mastering holdout splitting, Stratified K-Fold Cross-Validation, and rigorous leakage prevention is a core competency for data analysts.
1. Train-Test Split: Holdout Validation
The simplest validation strategy splits historical data into two disjoint subsets:
- Training Set (typically 70-80%): Used by the estimator to learn optimal weights and parameters.
- Testing Set (typically 20-30%): Kept in a vault until training is complete to assess real-world out-of-sample generalization.
stratify=y Matters:
In customer churn where only 5% of users churn, a random split might accidentally assign 8% churners to the test set and only 3% to the train set. Stratification preserves identical class ratios across both splits!2. K-Fold Cross-Validation
A single train-test split can yield misleading results if the random split happens to contain an unusually easy or hard test set. K-Fold Cross-Validation divides the data into $K$ equal folds:
- The model trains on $K-1$ folds and tests on the remaining fold.
- This process repeats $K$ times so every fold acts as the validation set once.
- The final metric is the average performance across all $K$ iterations.
3. Data Leakage: The #1 Killer of Production ML Models
Data leakage occurs when information from outside the training dataset (such as the target variable or future test set distributions) inadvertently influences model training:
Major Sources of Data Leakage:
- 1Global Imputation/Scaling: Computing the global mean of a column across the entire dataset before calling
train_test_split. - 2Lookahead Leakage: In time series, using future data to predict the past.
- 3Duplicate / Clustered Rows: Having multiple transactions from the exact same user present in both train and test splits.
4. Bulletproof Pipelines with Scikit-Learn Pipeline
To guarantee that transformers are fit exclusively on training folds during cross-validation, wrap steps in a Scikit-Learn Pipeline:
Multiple Choice Questions
stratify=y in train_test_split for classification?Pipeline?Linear Regression: Coefficients, R-Squared & MSE
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.