Sub topic 2
Stratified k-fold for classification
Assume you know supervised learning, overfitting, accuracy, NumPy, and scikit-learn’s fit and predict API. This chapter focuses on choosing folds that match the data.
Stratified k-fold for classification
In k-fold cross-validation, the data is divided into k parts called folds. The model trains on k-1 folds and tests on the remaining fold. This repeats until every fold has been used for testing.
Stratified k-fold keeps approximately the same class proportions in every fold. For example, if 20% of the samples are positive, each fold will contain about 20% positive samples. This makes scores more comparable, especially when classes are imbalanced.
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
model = make_pipeline(
StandardScaler(),
LogisticRegression(max_iter=1000)
)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
scores = cross_val_score(model, X, y, cv=cv, scoring="accuracy")
print(scores)
print(f"mean={scores.mean():.3f} std={scores.std():.3f}")The mean summarizes typical performance. The standard deviation shows how much the score changes across folds.
Avoiding data leakage with pipelines
Data leakage occurs when information from a test fold influences training. For example, scaling all samples before cross-validation lets the test fold influence the mean and standard deviation used for scaling.
A pipeline keeps preprocessing inside each fold. In the example, StandardScaler is fitted only on each training portion, then applied to that fold’s test portion.
Choosing k: bias, variance, and cost
A larger k trains on more data in each fold, which usually reduces pessimistic bias. However, the training sets overlap more, so fold scores can be more correlated. Larger k also costs more because the model is trained more times.
| Choice | Typical trade-off |
|---|---|
| 5 or 10 folds | Good general-purpose balance |
| Larger k | More computation and often noisier estimates |
| Smaller k | Faster, but each model trains on less data |
Use shuffled stratified 5-fold or 10-fold cross-validation as a starting point for ordinary classification. The best choice also depends on dataset size and model cost.
Grouped data: keeping related samples together
When samples come from people, devices, or experiments, related samples must stay in the same fold. Otherwise, nearly identical samples can appear in both training and test data, producing an overly optimistic score.
Use GroupKFold and provide one group identifier per sample.
Exercise
Why should samples from one patient remain in a single fold?
Show answer
To prevent patient-specific information from appearing in both training and test data.