Sub topic 7
Choosing k: bias, variance, and cost
The value of k decides how much data each model trains on, how many models you fit, and how stable the final estimate is. This chapter explains those three effects and gives a rule for picking k. It assumes you know k-fold cross-validation (the previous chapters), the basics of bias and variance, and scikit-learn's cross_val_score.
What k controls
In k-fold cross-validation with n samples, each fold holds out about n/k samples for testing. The model then trains on the remaining n(k-1)/k samples. Changing k therefore changes two things at once:
- Training set size per fit. Larger k means each model sees more data.
- Number of fits. You train k models, so the cost grows roughly linearly with k.
The training fraction rises quickly at first and then flattens. Going from k=2 to k=5 adds 30 percentage points of training data. Going from k=10 to k=20 adds only 5.
Bias of the estimate
Cross-validation estimates the performance of a model trained on all n samples. Each fold's model is trained on fewer samples, so it is usually a little worse than the final model. The estimate is therefore pessimistic. This is a bias in the statistical sense: the estimate is systematically off in one direction.
How large the bias is depends on the learning curve, which plots score against training set size.
- If the curve is already flat at 80% of your data, k=5 gives almost no bias.
- If the curve is still rising steeply, a small k understates the final model's quality. This happens with small datasets and high-capacity models.
At k=2 each model trains on only half the data. For many models that is a large handicap. At k=10 or k=20 the bias is usually small compared with other sources of error.
Variance of the estimate
The variance of the estimate is how much it would change if you drew a different sample of data, or just used different random fold assignments. It has two sources.
- Test-set noise. Each fold's score is computed on only n/k samples. Small test folds give noisy fold scores. Averaging over k folds partly compensates, because the folds together cover every sample once.
- Training-set overlap. Any two training sets share a fraction (k-2)/(k-1) of their samples. At k=10 that is 8/9 of the data. At k=2 the training sets do not overlap at all. At high k the fitted models are therefore very similar, and their errors are strongly correlated. Averaging correlated quantities removes less noise than averaging independent ones.
The second effect is why leave-one-out (k=n) is often not the lowest-variance choice, even though it has the lowest bias. The next chapters cover it in more detail. In practice, the variance of the cross-validated estimate tends to be high for very small k, because of the small training sets and the instability of the fits. It often levels off, or rises slightly, for very large k. The exact shape depends on the model. Unstable models such as unpruned decision trees and k-nearest neighbors with small k behave differently from stable ones such as regularized linear models.
| k | Training fraction | Bias (pessimism) | Variance | Cost (fits) |
|---|---|---|---|---|
| 2 | 50% | High | Moderate to high | 2 |
| 5 | 80% | Moderate | Moderate | 5 |
| 10 | 90% | Low | Moderate | 10 |
| n (leave-one-out) | (n-1)/n | Lowest | Can be high, model dependent | n |
The table is a guide, not a law. Treat the variance column especially as a tendency.
Computational cost
Total cost is about k times the cost of one fit, plus scoring. This matters in three situations:
- Slow models. If one fit takes 10 minutes, k=10 takes 100 minutes before any tuning.
- Hyperparameter search. A grid with 30 settings and k=5 needs 150 fits. Nested cross-validation (covered later) multiplies this again.
- Models whose fit time grows faster than linearly in n. Kernel SVMs and Gaussian processes are examples. With these, larger k makes each fit more expensive, so cost grows faster than k.
For fast models on small data, cost is not a real constraint and you can choose k on statistical grounds.
Measuring the effect yourself
The first script runs several values of k on the same data and prints the training size, the mean and spread of the fold scores, and the wall-clock time.
import time
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))
for k in [2, 3, 5, 10, 20]:
cv = StratifiedKFold(n_splits=k, shuffle=True, random_state=0)
start = time.perf_counter()
scores = cross_val_score(model, X, y, cv=cv, scoring="accuracy")
elapsed = time.perf_counter() - start
train_size = len(y) * (k - 1) / k
print(
f"k={k:2d} train~{train_size:.0f} "
f"mean={scores.mean():.3f} std={scores.std():.3f} time={elapsed:.2f}s"
)Expect the mean to change only slightly across k on this dataset. The learning curve for a regularized linear model on 569 samples is nearly flat, so bias is small. The time grows with k. The std printed here is the spread of the fold scores. It is not the uncertainty of the mean, which is smaller. The chapter on reporting results covers that distinction.
A single run cannot show the variance caused by random fold assignment. To see it, repeat the whole cross-validation with different shuffles and look at how much the mean moves.
import numpy as np
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))
for k in [2, 5, 10]:
means = []
for seed in range(20):
cv = StratifiedKFold(n_splits=k, shuffle=True, random_state=seed)
means.append(cross_val_score(model, X, y, cv=cv).mean())
means = np.array(means)
print(f"k={k:2d} mean of means={means.mean():.4f} std across seeds={means.std():.4f}")The "std across seeds" column shows how much of your reported number is an accident of the split. If it is comparable to the difference between two models you are comparing, the comparison is not trustworthy. That is the case for repeated cross-validation, which a later chapter covers.
A practical rule for choosing k
Start with k=5 or k=10. Both are standard because empirical studies and long experience show they give estimates with a good balance of bias and variance at moderate cost. Then adjust using the situation:
- Small dataset (a few hundred samples or fewer) and a fast model. Use k=10, or repeat 5-fold or 10-fold several times. Training size matters most here, because the learning curve is likely still rising.
- Large dataset (hundreds of thousands of samples or more). Use k=3 to 5, or even a single holdout split. Each test fold is already large and the learning curve is flat, so extra folds buy little.
- Expensive model or large hyperparameter grid. Use k=3 to 5 inside the search, and spend the saved time on a sound design such as nested cross-validation.
- Imbalanced classes. Make sure each test fold contains enough minority examples. With 40 positives and k=10, each test fold has only about 4, and the fold scores are very noisy. Use stratified splitting and consider a smaller k.
- Grouped or time-ordered data. The number of groups or time windows limits k.
GroupKFoldcannot use more folds than there are groups.
Common mistakes
- Comparing scores across different k. A 5-fold score and a 20-fold score differ partly because of bias. Fix k when comparing models.
- Choosing k to make the score look better. Trying many values of k and reporting the best one is a form of selection on the test data. Choose k once, before looking at results, on the grounds above.
- Treating the fold scores as independent. They share training data, so the usual standard error formula std/sqrt(k) is too optimistic. Present it as a rough guide only.
- Ignoring that k is not a hyperparameter of the model. It changes the measurement, not the model. Do not tune it with the same cross-validation that evaluates the model.
Exercise
A dataset has 200 samples and a model that takes 2 seconds to fit. You want to compare two candidate models and you need a stable estimate. Which k would you pick, and what would you do to reduce the effect of random fold assignment? Give the number of fits and the total fitting time for your plan.
Show answer
Use k=10, because with only 200 samples the training set size matters and 10 folds train on 90% of the data. To reduce the effect of the random split, repeat the 10-fold procedure, for example 5 times with different seeds (RepeatedStratifiedKFold if the task is classification). That gives 10 x 5 = 50 fits, or about 100 seconds per model. Use the same splits for both models so the comparison is paired.
Exercise
Why does leave-one-out cross-validation have the lowest bias but not necessarily the lowest variance?
Show answer
Each model trains on n-1 samples, so it is almost the same as the final model and the pessimistic bias is smallest. But any two training sets share n-2 samples, so the n fitted models and their errors are highly correlated. Averaging highly correlated scores reduces variance less than averaging independent ones, so the estimate can still be noisy, especially for unstable models.