Sub topic 5
Cross-validation for comparing settings
What this chapter assumes
You should know how to train a scikit-learn model, call fit and predict, and explain overfitting. You should also know why a final test set stays untouched during tuning. This chapter covers how to compare hyperparameter settings fairly using cross-validation. Later chapters build searches on top of it.
Why a single validation split is not enough
A single train/validation split gives you one score per setting. That score depends on which rows landed in the validation set. With a small dataset, two settings can differ by one or two percentage points purely because of the split.
Cross-validation (CV) reduces this problem. It repeats the train/validate cycle several times on different partitions and averages the results. The average is a steadier estimate of how a setting performs. The spread across folds shows how uncertain that estimate is.
How k-fold cross-validation works
In k-fold CV, you split the training data into k equal parts called folds. For each fold:
- Hold that fold out as the validation fold.
- Fit a fresh model on the other k-1 folds.
- Score the model on the held-out fold.
You end up with k scores. Their mean is the CV score for that setting. Every row is used for validation exactly once and for training k-1 times.
Only the training portion of your data goes into CV. The test set stays out until you have chosen a final setting.
Comparing two settings with `cross_val_score`
cross_val_score runs the loop above and returns the k scores. Use the same folds for every setting you compare. Passing a splitter object with a fixed random_state guarantees this.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import StratifiedKFold, cross_val_score, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=0, stratify=y
)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
for C in [0.1, 1, 10]:
model = make_pipeline(StandardScaler(), SVC(C=C, gamma=0.01))
scores = cross_val_score(model, X_train, y_train, cv=cv, scoring="accuracy")
print(f"C={C:<5} mean={scores.mean():.3f} std={scores.std():.3f}")The output has one line per value of C, with the mean and standard deviation of five accuracy scores. Read both numbers. If two settings differ by less than the standard deviation, you have no good evidence that one is better.
Choosing a splitting strategy
The default in scikit-learn is sensible, but not always correct. Pick the splitter that matches your data.
| Situation | Splitter | Why |
|---|---|---|
| Classification, imbalanced classes | `StratifiedKFold` | Keeps class proportions similar in every fold |
| Regression or balanced classes | `KFold` | Simple, no class information needed |
| Several rows per person, machine, or site | `GroupKFold` | Keeps all rows of a group in one fold |
| Data ordered in time | `TimeSeriesSplit` | Validates only on data after the training window |
| Small dataset, noisy scores | `RepeatedStratifiedKFold` | Repeats k-fold with different shuffles to reduce variance |
When you pass an integer such as cv=5 to a classifier, scikit-learn uses stratified k-fold without shuffling. Regressors get plain KFold. If your rows are sorted, for example by class or by date, unshuffled folds can be badly unbalanced. Pass an explicit splitter with shuffle=True for non-time-series data.
Choosing k
The number of folds trades bias against variance and cost.
- Small k, such as 3, trains each model on less data. Scores tend to be slightly pessimistic, and the run is cheap.
- Large k, such as 10, trains on more data, so scores are closer to what a model fit on all the training data would achieve. The run costs more, and the fold scores are correlated because the training sets overlap heavily.
- Leave-one-out (k equal to the number of rows) is rarely worth the cost. Its scores are high-variance and it needs one fit per row.
Five or ten folds is the usual choice. For tuning, 5 is a good default because each setting must be evaluated many times, and cost is multiplied by k.
Using more than one metric
cross_validate returns fit time, score time, and several metrics at once. This helps when you want to optimize one metric and monitor another.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import StratifiedKFold, cross_validate
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
X, y = load_breast_cancer(return_X_y=True)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
model = make_pipeline(StandardScaler(), SVC(C=1, gamma=0.01))
results = cross_validate(
model, X, y, cv=cv,
scoring=["accuracy", "f1", "roc_auc"],
return_train_score=True,
)
for name in ["fit_time", "train_accuracy", "test_accuracy", "test_f1", "test_roc_auc"]:
print(name, results[name].mean().round(3))Setting return_train_score=True shows the training score next to the validation score. A large gap means overfitting. Two low scores that are close together suggest underfitting. This costs a little extra time, and it is worth it while you are still learning how a model reacts to its settings.
Common errors
- Fitting preprocessing before CV. If you scale or select features on all the data and then cross-validate, information from the validation fold leaks into training. Put preprocessing inside a
Pipelineso it is refit on each training fold. The examples above do this. - Comparing settings on different folds. If each setting gets a new random split, differences in score mix real effects with split luck. Use one splitter object with a fixed seed.
- Picking the best mean and ignoring the spread. A setting that wins by 0.2 percentage points with a standard deviation of 2 points has not clearly won. Prefer the simpler or cheaper setting when scores are within noise.
- Reporting the best CV score as the expected performance. The best of many CV scores is biased upward, because you selected it for being high. Only an untouched test set, or nested CV (a later chapter), gives an honest estimate.
- Using the test set inside CV. Cross-validate on the training portion only.
- Metric mismatch. The default score for classifiers is accuracy. On imbalanced data, set
scoringto something like"f1","roc_auc", or"average_precision".
Cost to keep in mind
Evaluating one setting with 5-fold CV means 5 model fits. A grid of 20 settings means 100 fits. Use n_jobs=-1 in cross_val_score or in the search classes to run folds in parallel. Cost scales with the number of settings and the number of folds, which is the main reason the later chapters on random search and pruning exist.
Exercise
You compare two settings of a model with 5-fold CV. Setting A has mean accuracy 0.962 and standard deviation 0.015. Setting B has mean accuracy 0.958 and standard deviation 0.012. Setting B trains twice as fast. Which setting would you choose, and what two checks would you run before trusting the comparison?
Show answer
Choose B. The 0.004 difference is far smaller than either standard deviation, so there is no evidence that A is better, and B is cheaper. First, check that both settings were scored on identical folds (one splitter object with a fixed random_state). Second, check that preprocessing is inside a Pipeline so no information leaks from validation folds. You could also repeat the CV with RepeatedStratifiedKFold to see whether the gap stays within noise.
Exercise
A dataset has 10 rows per patient, and you want to predict a diagnosis for new patients. Which splitter should you use, and why would plain KFold give an inflated score?
Show answer
Use GroupKFold with the patient ID as the group. Plain KFold can place some of a patient's rows in training and others in validation. The model can then match the validation rows to the same patient's training rows, which does not reflect performance on unseen patients, so the score is too high.