Cross-Validation Folds: Choosing k and Spotting Bad Estimates
Machine LearningModel answerLast updated
Describe how k-fold cross-validation works, how the choice of k shifts bias, variance and cost, and which situations make a cross-validated score overly optimistic or unreliable.
You are evaluating a supervised model and want a trustworthy estimate of how well it will perform on unseen data.
Answer the following as you would in a technical conversation about machine learning fundamentals:
- Walk through the k-fold cross-validation procedure from start to finish. What exactly does the final number estimate?
- How does the choice of k affect the bias of the estimate, its variance, and the computational cost? Where do common values such as 5 and 10 fit, and what about leave-one-out?
- Describe the situations in which a cross-validated score can be misleading. Make sure you cover leakage, temporal ordering, grouped or duplicated records, and class imbalance, and say what you would do about each.
Be concrete: give small examples, say which metrics or splitters you would use, and mention any trade-offs you would weigh in practice.
Hints
Hint 1
Think about what fraction of the data each fold model is trained on, and how that compares with the model you eventually deploy.
Hint 2
As k grows, the training sets of different folds overlap more. Ask what that does to the correlation between fold scores, and therefore to the variance of their average.
Hint 3
For each failure mode, ask whether information from the validation rows could reach training: through preprocessing fitted on all data, through the same entity appearing on both sides, through future data predicting the past, or through selecting the best of many configurations on the same folds.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
What the interviewer wants to hear
A cross-validation (CV) score is a statistical estimate with its own bias and variance, and it can be wrong in predictable ways. A strong answer covers the mechanics, the effect of k, and the failure modes with fixes.
The procedure
- Shuffle the n examples (unless order matters, see temporal data) and split them into k disjoint folds of roughly equal size.
- For each fold i, fit the whole pipeline (imputation, scaling, feature selection, model) on the other k-1 folds, then score on fold i to get s_i.
- Report the mean of the s_i and also their spread (standard deviation or an interval).
- Once a configuration is chosen, refit it on all the data to produce the deployed model.
CV estimates the expected performance of the training procedure on a training set of about n(k-1)/k examples. It does not score the particular final model. Every example is validated exactly once and used for training k-1 times, so it uses data far more efficiently than one hold-out split, which matters most on small datasets.
Choosing k
Bias. Each fold model sees only (k-1)/k of the data. Since learning curves usually still rise with more data, fold models are slightly worse than the final one, so CV is pessimistically biased. With k=2 (50% of data) the pessimism can be large, with k=10 it is small, and leave-one-out (k=n) is nearly unbiased.
Variance. Larger k means heavily overlapping training sets (in LOOCV any two share n-2 points). The fold scores become highly correlated, and averaging correlated numbers reduces variance less than averaging independent ones. For unstable learners (deep trees, 1-NN) LOOCV can be noisy; for stable ones (ridge) it matters less. So variance is not monotonic in k: small k suffers from small training sets, very large k from correlated folds.
Cost. k full training runs; LOOCV is n runs. The exception is models with closed-form leave-one-out shortcuts, such as linear smoothers.
| k | Bias (pessimism) | Variance | Cost |
|---|---|---|---|
| 2-3 | High | Moderate to high | Low |
| 5-10 | Low | Moderate | Moderate |
| n (LOOCV) | Near none | Can be high for unstable models | Very high |
Practical guidance
- 5 or 10 folds is the usual sweet spot.
- Repeated k-fold (different random partitions, averaged) cuts the variance caused by one particular split.
- With millions of rows, a single hold-out set is already low-variance and k times the compute is wasteful.
- With very small data, use repeated 10-fold or LOOCV and report intervals.
When CV misleads
1. Leakage from preprocessing done outside the folds. Scaling, imputation, PCA, target encoding, feature selection and oversampling (e.g. SMOTE) fitted on all data before splitting leak validation information. The classic example: pick the top 100 of 10,000 features using all labels, then cross-validate, and you can get high accuracy on pure noise; oversampling first puts synthetic copies of validation points in training. Fix: put every data-dependent step in a pipeline refit inside each fold.
2. Non-independent samples. Multiple rows per user, patient or session, several images of one object, or near-duplicates mean random folds put the same entity on both sides, rewarding memorization. Fix: deduplicate and use group-aware splitting (GroupKFold) so each entity lives in one fold only.
3. Temporal data. Shuffling lets the model train on the future to predict the past, and autocorrelation makes neighbouring rows near-copies. Scores inflate and drift is hidden. Fix: forward-chaining or rolling-origin validation (e.g. TimeSeriesSplit), always training on the past and validating on the future. Add a gap or embargo when features use lagged windows or labels mature late (fraud, churn). Spatial data needs the analogous spatial blocking.
4. Class imbalance. With rare positives, a random fold may hold very few or zero positives, so fold scores swing and some metrics are undefined. Accuracy is also uninformative: 99% is trivial at a 1% positive rate. Fix: StratifiedKFold; metrics such as PR-AUC, recall at fixed precision or F1; resample only inside training folds; compute pooled or per-fold metrics consistently.
5. Tuning and reporting on the same folds. Picking the best of many configurations by CV score gives an optimistically biased number, more so with larger search spaces. Fix: nested CV (inner loop tunes, outer loop estimates) or a final untouched test set.
6. Distribution shift. CV assumes deployment data is i.i.d. with training data. If production brings new regions, products or user populations, CV answers the wrong question. Fix: build splits that mimic deployment, such as holding out whole regions or the most recent period.
7. Ignoring noise. A 0.3-point AUC gap may sit inside fold-to-fold variation. Fix: report spread, use repeated CV, compare models on identical folds (paired), and avoid naive t-tests across folds, which are overconfident because folds are correlated; a corrected resampled t-test helps.
Correct implementation pattern
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score
pipe = Pipeline([
("scale", StandardScaler()),
("select", SelectKBest(f_classif, k=50)),
("clf", LogisticRegression(max_iter=1000)),
])
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
scores = cross_val_score(pipe, X, y, cv=cv, scoring="average_precision")
print(scores.mean(), scores.std())
Because scaling and selection live inside the pipeline, they are refit on each training split and never see validation rows. For grouped data swap in GroupKFold (or StratifiedGroupKFold), and for time series use TimeSeriesSplit.
Common mistakes
- Fitting preprocessing or feature selection on the full dataset first.
- Using random folds on user-level, session-level or time-ordered data.
- Reporting only the mean, with no spread.
- Reporting the best tuned CV score as the expected performance.
- Treating the CV number as the score of the final refit model rather than of the procedure.
Summary
Use 5 or 10 folds by default, repeat when data is small, hold out when data is huge, and make the validation scheme mirror how the model will be used. Any step that learns from data must live inside the fold, and the split must respect groups, time and class balance.