Sub topic 13
Common pitfalls: leakage, grouped samples, and cost
Learning curves and validation curves are only as trustworthy as the cross-validation score behind them. This chapter covers the mistakes that produce curves that look fine but mislead you. It assumes you can already compute both curves with learning_curve and validation_curve, and that you know what a scikit-learn pipeline is. It also assumes you know the basic idea of cross-validation.
Why pitfalls matter more for curves
A single bad score is easy to spot. A bad curve is harder to spot, because the curve has a plausible shape. Leakage lifts the validation line and shrinks the gap, so you read "low variance" when the model is actually memorizing. Dependent samples do the same. A wrong metric tells you the model fits well when it ignores the minority class. Compute cost shapes which curves you can afford to draw at all.
Pitfall 1: data leakage
Data leakage means information from the validation fold reaches the model during training. The validation score then measures something other than performance on new data.
The common sources are:
- Fitting a scaler, imputer, or encoder on the full dataset before cross-validation.
- Selecting features using all labels, then cross-validating only the model.
- Tuning on the same data you report as final performance.
- Duplicated rows that land on both sides of a split.
Feature selection is the most dramatic case. The code below uses pure noise, so no honest method can beat chance accuracy of about 0.5.
import numpy as np
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
rng = np.random.default_rng(0)
X = rng.normal(size=(100, 2000))
y = rng.integers(0, 2, size=100)
# Wrong: the selector sees every label before cross-validation starts.
X_selected = SelectKBest(f_classif, k=20).fit_transform(X, y)
leaky = cross_val_score(LogisticRegression(max_iter=1000), X_selected, y, cv=5)
# Right: the selector is refit inside each training split.
pipe = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression(max_iter=1000))
clean = cross_val_score(pipe, X, y, cv=5)
print(f"leaky accuracy: {leaky.mean():.2f}")
print(f"clean accuracy: {clean.mean():.2f}")The leaky score typically lands far above 0.5, and the clean score stays near 0.5. Both are computed from the same data. Only the clean one is honest.
The fix is structural. Put every step that learns from data (scaling, imputation, selection, encoding) inside a Pipeline. Pass the pipeline to learning_curve or validation_curve. Each fold then refits the whole chain on its own training portion.
Leakage in the curve workflow
There is a second, quieter form. Suppose you pick a hyperparameter from a validation curve, then quote that curve's best validation score as your expected performance. You chose the value because it scored best on those folds, so the number is optimistic. Keep a final test set that no curve or search has touched, and report performance only from it.
Pitfall 2: grouped and dependent samples
Standard KFold assumes rows are independent. Many datasets violate that:
- Several rows come from the same patient, user, device, or document.
- Images are crops or augmentations of the same source.
- Measurements are repeated over time on the same unit.
If rows from one group appear in both training and validation, the model can recognize the group instead of learning the pattern. The validation score rises, and the gap between the curves narrows falsely.
Use a grouping-aware splitter and pass groups to the curve function. The next example defines synthetic groups so it runs as written. In real work, groups comes from your data, such as a patient ID column.
import numpy as np
from sklearn.datasets import load_digits
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GroupKFold, learning_curve
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_digits(return_X_y=True)
# Synthetic groups for demonstration: every 10 consecutive rows share a group.
groups = np.arange(len(y)) // 10
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",
)
print(train_sizes)
print(train_scores.mean(axis=1))
print(val_scores.mean(axis=1))This code does two things. The pipeline refits the scaler on each training split, which prevents leakage. GroupKFold keeps every group entirely on one side of each split.
Choosing the right splitter
| Situation | Splitter |
|---|---|
| Independent rows, balanced classes | `KFold` or `ShuffleSplit` |
| Independent rows, imbalanced classes | `StratifiedKFold` |
| Repeated measures per entity | `GroupKFold` |
| Groups plus imbalanced classes | `StratifiedGroupKFold` |
| Data ordered in time | `TimeSeriesSplit` |
Time-ordered data needs special care. Random folds let the model train on the future and predict the past, which is leakage. TimeSeriesSplit always validates on data later than the training data.
Note also that without shuffle, plain KFold takes contiguous blocks. If your file is sorted by class or by date, those blocks are not representative. Sorted data is a reason to choose the splitter deliberately, not to accept the default.
Pitfall 3: an unsuitable scoring metric
Every score on your curves comes from the scoring argument. The default is the estimator's own score method, which is accuracy for classifiers. With 95% of samples in one class, a model that always predicts that class scores 0.95. Both curves sit high and close together, and you conclude the model fits well.
Match the metric to the goal:
- Imbalanced classification:
balanced_accuracy,f1,average_precision, orroc_auc. - Regression where large errors are costly:
neg_root_mean_squared_error. - Regression where outliers should matter less:
neg_mean_absolute_error.
Scikit-learn scorers follow a "greater is better" convention. Error metrics therefore carry a neg_ prefix, and their curves are negative numbers that rise toward zero as the model improves. Remember this when you label axes and read the direction of the gap.
Pitfall 4: cost
Curves are expensive because each point is a full set of model fits. The counts are simple:
| Function | Fits performed |
|---|---|
| `learning_curve` | number of training sizes × number of folds |
| `validation_curve` | number of parameter values × number of folds |
A learning curve with 5 sizes and 5 folds fits 25 models. A validation curve over 6 values with 5 folds fits 30. Nesting a curve inside a hyperparameter search multiplies these counts again.
To keep cost under control:
- Run fits in parallel with
n_jobs=-1. - Use fewer sizes first (four or five are enough to see a trend), then refine only where the curve bends.
- Use 3 folds while exploring, and 5 or 10 for the final figure.
- Compute curves on a representative subsample when the full dataset takes hours.
- For estimators that support
partial_fit, passexploit_incremental_learning=Trueso the model grows through the sizes instead of refitting from scratch. - Use a wide logarithmic parameter range first, since many hyperparameters span orders of magnitude, then zoom in.
Fewer folds make each estimate noisier, so the variability bands from the previous chapter widen. Saving compute this way is a trade, not a free gain.
A pre-flight checklist
Other failure modes
- Convergence warnings. An iterative solver that stops early produces a worse model at some points, which distorts the curve. Raise
max_iteror scale features, as the examples here do. - Failed fits. By default a fit that raises an error stops the computation. Setting
error_score=np.nanrecords the failure instead, but investigate the cause rather than averaging around it. - Random seeds. Stochastic estimators and shuffled splits give slightly different curves each run. Set
random_stateon the estimator and the splitter so results can be reproduced and compared. - Reading small differences. A gap of 0.005 between two parameter values is often inside the fold-to-fold spread. Do not treat it as a real ranking.
Exercise
A teammate computes a learning curve on a medical dataset with several rows per patient, using the default 5-fold cross-validation. The validation curve sits almost on top of the training curve at 0.97, which suggests an excellent, low-variance model. Name the most likely problem, explain why it fools the curve, and say what to change.
Show answer
The most likely problem is leakage through dependent samples. Rows from the same patient land in both training and validation folds, so the model can recognize patients instead of learning general patterns, and the validation score is inflated. The small gap is therefore misleading. Pass a patient ID array as groups and use GroupKFold (or StratifiedGroupKFold if classes are imbalanced) so each patient appears on only one side of every split. Also confirm that scaling and other preprocessing sit inside a Pipeline.
Exercise
A learning curve with 6 training sizes and 10 folds is run on a model that takes 30 seconds to fit. How many fits does it perform, and what are two ways to reduce the wait?
Show answer
It performs 6 × 10 = 60 fits, about 30 minutes of sequential compute. Two ways to cut it: run the folds in parallel with njobs=-1, and use fewer folds (for example 3 or 5) or fewer sizes during exploration. A subsample of the data, or exploitincrementallearning=True for an estimator with partialfit, also helps.