Skip to content
mentoor

Topic 3 of 5 · 5 min read

Cross-validation on small datasets

Goal: Choose k-fold or stratified cross-validation for a small dataset and report the mean and spread of its fold scores.

Cross-validation scores a model several times on different held-out slices of the training data and reports the average and the spread. It gives a steadier estimate than one validation split, which matters most when you have few rows.

Check yourself · 1 of 3

In 5-fold cross-validation, how many times is the model fitted?

Choose one answer

Why it matters

With 300 rows, a 20 percent validation set is 60 rows. A single unlucky split can change the score by several points, and you cannot tell luck from a better model. Averaging over several splits reduces that noise and shows how much the score moves.

How k-fold works

Shuffle the training data and cut it into k equal folds. Train on k minus 1 folds, score on the remaining one, and repeat so every fold is held out once. You get k scores. Report their mean and standard deviation. The scikit-learn guide describes this procedure and the variants below (see the reference).

  • KFold: plain k folds, fine for balanced classes and regression.
  • StratifiedKFold: keeps the class proportions in every fold. Use it for classification, and above all when one class is rare, so no fold ends up with almost no positives.
  • GroupKFold: keeps all rows of one group (a customer, a patient) in the same fold.
  • TimeSeriesSplit: always trains on the past and scores on the future.

A typical choice is k of 5 or 10. Larger k means more fits and more compute.

How to do it

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

model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(model, X_train, y_train, cv=cv, scoring="f1")
print(f"F1 {scores.mean():.3f} +/- {scores.std():.3f}")

Putting the scaler inside a pipeline means it is refitted on each training fold, so nothing leaks from the held-out fold.

Before and after

Before: one 80/20 split gives 0.91 accuracy and the team celebrates. After: five stratified folds give 0.84, 0.91, 0.78, 0.89, 0.86. The mean is about 0.86 and the spread is wide, so the honest statement is "roughly 0.86, give or take 0.05".

What goes wrong

  • Preprocessing outside the pipeline. Scaling the whole training set before cross-validation lets held-out folds influence the scaler.
  • Ignoring the spread. Model A scores 0.86 plus or minus 0.07 and model B scores 0.85 plus or minus 0.01. The first difference is noise.
  • Plain KFold on a rare class. A fold with two positives gives a meaningless recall.
  • Using the test set inside the loop. Cross-validate on the training portion only and keep the test set for the end.

Examples

Reading fold scores

Model A  f1 per fold: 0.81 0.83 0.80 0.82 0.84   mean 0.82  std 0.02
Model B  f1 per fold: 0.90 0.71 0.88 0.69 0.92   mean 0.82  std 0.10

Same mean, very different behaviour. Model B depends heavily on which rows it trains on, so expect surprises in production. Prefer A, or find out why B swings.

Choosing the splitter

Fraud labels are 1 percent of 4,000 rows, so use StratifiedKFold: plain KFold could leave a fold with a handful of fraud cases. If the same customer has many transactions, switch to StratifiedGroupKFold so one customer never sits on both sides of a fold.

Key points

  • Cross-validation produces k scores from k different held-out folds; report the mean and the spread, not one number.
  • Use StratifiedKFold for classification so each fold keeps the class balance, especially with a rare class.
  • Use GroupKFold or TimeSeriesSplit when rows share an owner or are ordered in time.
  • Put preprocessing inside a Pipeline so it is refitted on each training fold.
  • Cross-validation replaces the fixed validation split but not the final test set.

Common mistakes

  • Reporting only the mean and hiding that the folds disagree widely.
  • Scaling or encoding the whole training set before cross-validating instead of using a Pipeline.
  • Using plain KFold for a rare positive class, leaving folds with almost no positives.
  • Shuffling time-ordered rows so folds train on the future.

Check yourself · 2 of 3

A fraud dataset has 4 percent positive rows. Which splitter keeps each fold representative?

Choose one answer

Check yourself · 3 of 3

Two models both average 0.85 accuracy across five folds. One has fold scores within 0.01 of each other and the other ranges from 0.70 to 0.95. What do you conclude?

Choose one answer

Practice items, not counted towards your mastery.

Start here