Sub topic 5
Cross-validation for comparing settings
This chapter assumes you can train and score a scikit-learn model, you know what a train/test split is, and you have met overfitting. Here you will use cross-validation to compare hyperparameter settings fairly.
Why one validation split is not enough
A single validation split gives one score per setting. That score depends on which rows landed in the validation set. With a small dataset, a lucky split can make a poor setting look best.
Cross-validation (CV) reduces this noise. It splits the training data into k parts called folds. It trains k times, and each time one fold is held out for scoring and the other k-1 folds are used for training. You then average the k scores.
Comparing settings with cross_val_score
The code below scores four values of C on the same folds. Using one StratifiedKFold object means every setting sees identical splits, so differences come from the setting and not from the split.
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.01, 0.1, 1, 10]:
model = make_pipeline(StandardScaler(), SVC(C=C))
scores = cross_val_score(model, X_train, y_train, cv=cv)
print(f"C={C:<5} mean={scores.mean():.3f} std={scores.std():.3f}")Three choices in this code matter:
- Stratified folds keep the class proportions in every fold. This is the default for classifiers when you pass an integer to
cv. shuffle=Truewith a fixedrandom_stateguards against data stored in sorted order and keeps the splits repeatable.- The scaler is inside the pipeline. It is refit on the training folds of each round, so no information from the validation fold leaks into preprocessing.
Only X_train is used. The test set stays untouched.
Reading the numbers
Look at the standard deviation as well as the mean. If two settings differ by 0.003 and the standard deviation is 0.015, the data does not show that one is better. In that case prefer the simpler or cheaper setting.
GridSearchCV and RandomizedSearchCV run this same loop for every candidate. They report the mean in cv_results_["mean_test_score"] and the spread in cv_results_["std_test_score"].
Common errors
| Error | Effect | Fix |
|---|---|---|
| Scaling or selecting features before CV on all data | Optimistic scores from leakage | Put each step in a pipeline |
| Different folds for each setting | Differences mix setting and split noise | Reuse one `cv` object |
| Plain k-fold on imbalanced classes | Folds with few or no positives | Use `StratifiedKFold` |
| Shuffling time-ordered data | Training on the future | Use `TimeSeriesSplit` |
| Rows from the same group in different folds | Validation scores too high | Use `GroupKFold` |
| Reporting the best CV score as final performance | Optimistic estimate | Score the test set once |
Exercise
You compare two settings with 5-fold CV. Setting A scores 0.962 with std 0.012. Setting B scores 0.958 with std 0.010. A teammate says A is better. How do you respond, and what could you do to check?
Show answer
The 0.004 gap is much smaller than either standard deviation, so the data does not separate them. Treat them as tied and pick the cheaper or simpler one. To check further, use repeated stratified k-fold (RepeatedStratifiedKFold) with the same folds for both settings and compare the per-fold score differences.