Sub topic 13
Common Pitfalls: Leakage, Grouped Samples, and Cost
This chapter assumes you can run learning_curve and validation_curve, and that you know what cross-validation, a pipeline, and a scoring metric are. Curves are only as trustworthy as the cross-validation behind them. Three problems account for most misleading curves: leakage, dependent samples, and compute cost.
Pitfall 1: Leakage from preprocessing
Data leakage means information from the validation fold influences training. The common case is fitting a scaler, imputer, or feature selector on the full dataset before calling the curve function. The statistics in that step (means, variances, selected features) then include validation rows.
The effect is a validation score that looks better than it should. The gap between the curves shrinks, and you may conclude that the model generalizes when it does not.
The fix is to put every data-dependent step inside a pipeline. learning_curve and validation_curve clone and refit the whole pipeline on each training split.
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
# Wrong: the scaler sees every row, including future validation rows.
# X_scaled = StandardScaler().fit_transform(X)
# Right: the scaler is refit on each training split.
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=2000))With a pipeline, tune a step's hyperparameter by its prefixed name, for example param_name="logisticregression__C".
Pitfall 2: Grouped samples
Ordinary k-fold assumes samples are independent. Often they are not. Several rows may come from one patient, one user, or one device. If rows from the same group land on both sides of a split, the model can recognize the group instead of learning the general pattern. Validation scores become too high.
Pass a groups array and use a group-aware splitter such as GroupKFold. This keeps each group entirely in training or entirely in validation.
import numpy as np
from sklearn.model_selection import GroupKFold, learning_curve
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
# X, y as before; groups holds one group label per sample (for example a patient or user ID).
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=2000))
train_sizes, train_scores, val_scores = learning_curve(
model,
X,
y,
groups=groups,
cv=GroupKFold(n_splits=5),
train_sizes=np.linspace(0.2, 1.0, 5),
scoring="accuracy",
)Time-ordered data has a related problem. Shuffled folds let the model train on the future and predict the past. Use TimeSeriesSplit for such data.
Pitfall 3: Cost
A curve is many model fits, not one.
| Function | Approximate number of fits |
|---|---|
| `learning_curve` | number of training sizes × number of folds |
| `validation_curve` | number of parameter values × number of folds |
Five sizes with five folds is 25 fits. A grid of 10 parameter values with 10 folds is 100. Slow models make this expensive quickly.
Ways to reduce cost:
- Use fewer folds (3 or 5) and fewer points on the axis while exploring.
- Set
n_jobs=-1to fit in parallel. - Run a first pass on a subsample, then repeat at full size only for promising settings.
- Use a log-spaced range for hyperparameters like
gammaorC, so a few points cover several orders of magnitude.
Fewer folds make the bands noisier, so do not read fine detail from a cheap curve.
Other things to check
- Metric mismatch. Accuracy on an imbalanced problem can look high at every size. Pick a metric that fits the task, such as F1 or ROC AUC, and use the same one for every curve you compare.
- Imbalanced classes. Use a stratified splitter so every fold contains each class.
- Reading too much into one run. Differences smaller than the fold-to-fold spread are not evidence.
Exercise
You compute a learning curve on data with five rows per patient, using a pipeline and the default cv=5. The validation score is very high and close to the training score. What is the most likely cause, and how do you fix it?
Show answer
Rows from the same patient appear in both training and validation folds, so the model can recognize patients. Pass a groups array of patient IDs and set cv=GroupKFold(n_splits=5) so each patient stays on one side of every split.
Exercise
A validation curve over 12 values of C with cv=10 takes too long. Name two changes that reduce the cost, and say what you give up with one of them.
Show answer
Use n_jobs=-1 to parallelize, or reduce to cv=5 or fewer parameter values. Fewer folds makes the mean and the error bands less stable, so small differences between settings become harder to trust.