A single train/test split gives you one estimate of how well a model performs. But change the random seed and the score changes too – sometimes by a surprising amount, especially with smaller datasets. Was your model good, or did it just get a lucky split? Cross-validation answers that question by testing the model on several different splits and looking at the whole set of results.
This guide explains how k-fold cross-validation works, how to use it in scikit-learn, which variant to choose for classification, grouped and time-series data, how to tune hyperparameters with it, and how to avoid the leakage mistakes that make cross-validated scores misleading.
Step 1: See why one split is not enough
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
X, y = load_breast_cancer(return_X_y=True)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
scores = []
for seed in range(10):
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2, random_state=seed, stratify=y)
scores.append(model.fit(X_tr, y_tr).score(X_te, y_te))
print(np.round(scores, 3))
print("Range:", round(min(scores), 3), "to", round(max(scores), 3))
The same model on the same data gives noticeably different accuracy depending only on which rows land in the test set. Report just one of those numbers and you could be over- or under-selling the model. For background on splitting, see Train/Test Split Explained.
Step 2: How k-fold cross-validation works
- Shuffle the data and divide it into k equal parts (“folds”), commonly 5 or 10.
- Train on k−1 folds and test on the remaining fold.
- Repeat k times, so every fold is the test fold once.
- Report the mean and spread of the k scores.
Every row is used for testing exactly once and for training k−1 times, so you make much better use of limited data than a single split does.

Step 3: cross_val_score
from sklearn.model_selection import cross_val_score
cv_scores = cross_val_score(model, X, y, cv=5, scoring="accuracy")
print(np.round(cv_scores, 3))
print(f"Mean {cv_scores.mean():.3f}, standard deviation {cv_scores.std():.3f}")
Report results as mean ± standard deviation. The standard deviation tells you how stable performance is; if two models differ by less than this, the difference may not be meaningful.
For classifiers, passing an integer to cv automatically uses stratified k-fold, which keeps class proportions the same in every fold.
Step 4: Several metrics at once with cross_validate
from sklearn.model_selection import cross_validate
results = cross_validate(model, X, y, cv=5,
scoring=["accuracy", "precision", "recall", "roc_auc"],
return_train_score=True)
for metric in ["accuracy", "precision", "recall", "roc_auc"]:
print(f"{metric:9s} test {results['test_' + metric].mean():.3f} "
f"train {results['train_' + metric].mean():.3f}")
Comparing training and test scores is a quick overfitting check: a large gap means the model fits the training folds much better than unseen data. See Classification Metrics Explained for choosing metrics. Note that in this dataset label 1 means benign, so precision and recall here describe the benign class; in a real project, make sure the positive class is the one you care about.
Step 5: Control the folds explicitly
from sklearn.model_selection import StratifiedKFold, KFold, RepeatedStratifiedKFold
skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
print(cross_val_score(model, X, y, cv=skf).mean().round(3))
rskf = RepeatedStratifiedKFold(n_splits=5, n_repeats=3, random_state=42)
rep = cross_val_score(model, X, y, cv=rskf)
print(len(rep), "scores, mean", rep.mean().round(3), "std", rep.std().round(3))
- KFold – plain k-fold, suitable for regression.
- StratifiedKFold – preserves class balance; use for classification.
- RepeatedStratifiedKFold – repeats the whole process with different shuffles for an even more stable estimate, at extra computational cost.
Set shuffle=True unless the data is time-ordered; otherwise folds follow the original row order, which may be sorted in a way that biases results.
Step 6: Avoid leakage – put preprocessing in the pipeline
If you scale, impute or select features on the full dataset before cross-validation, each test fold has influenced the preprocessing, and scores are optimistic. The fix is to put every data-dependent step in a pipeline, so it is re-fitted on the training folds each time. That is why our model is make_pipeline(StandardScaler(), LogisticRegression()) rather than a model fitted on pre-scaled data.
Leakage is most dramatic with feature selection. Here is an extreme demonstration using pure random noise, where no real signal exists:
from sklearn.feature_selection import SelectKBest, f_classif
rng = np.random.default_rng(0)
X_noise = rng.normal(size=(100, 5000))
y_noise = rng.integers(0, 2, 100)
# WRONG: select features using all rows, then cross-validate
X_sel = SelectKBest(f_classif, k=20).fit_transform(X_noise, y_noise)
wrong = cross_val_score(LogisticRegression(max_iter=1000), X_sel, y_noise, cv=5).mean()
# RIGHT: selection happens inside each training fold
pipe = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression(max_iter=1000))
right = cross_val_score(pipe, X_noise, y_noise, cv=5).mean()
print(f"Leaky CV accuracy: {wrong:.2f} Correct CV accuracy: {right:.2f}")
The labels are random, so true accuracy is around 0.5. The leaky approach reports a far higher score because the selected features were chosen using the test folds’ labels. The correct pipeline reports roughly chance level, as it should.
Step 7: Tune hyperparameters with GridSearchCV
Cross-validation is the standard way to choose settings such as regularisation strength:
from sklearn.model_selection import GridSearchCV
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
search = GridSearchCV(model, {"logisticregression__C": [0.01, 0.1, 1, 10, 100]},
cv=5, scoring="roc_auc")
search.fit(X_train, y_train)
print("Best C:", search.best_params_, "CV AUC:", round(search.best_score_, 4))
print("Held-out test AUC:", round(search.score(X_test, y_test), 4))
Notice the workflow: hold back a test set first, tune with cross-validation on the training set only, then evaluate the chosen model once on the test set. Because you picked the best of several settings, the best CV score is slightly optimistic; the untouched test score is the honest estimate. For a fully rigorous estimate on small data, “nested” cross-validation wraps the whole search inside an outer CV loop.
The parameter name logisticregression__C is the pipeline step name (lowercased class name, created automatically by make_pipeline) plus a double underscore and the parameter.
Step 8: Grouped and time-series data
Standard k-fold assumes rows are independent. Two common situations break that:

- Several rows per entity (patients, customers, stores): use
GroupKFoldso that an entity never appears in both training and test folds. - Time-ordered data: use
TimeSeriesSplit, which always trains on the past and tests on the future.
from sklearn.model_selection import GroupKFold, TimeSeriesSplit
groups = np.repeat(np.arange(len(X) // 3 + 1), 3)[:len(X)] # pretend 3 rows per patient
g_scores = cross_val_score(model, X, y, cv=GroupKFold(n_splits=5), groups=groups)
print("GroupKFold mean:", g_scores.mean().round(3))
tscv = TimeSeriesSplit(n_splits=4)
for i, (tr, te) in enumerate(tscv.split(np.arange(20))):
print(f"Fold {i}: train rows {tr.min()}-{tr.max()}, test rows {te.min()}-{te.max()}")
The printout shows each time-series fold training on an expanding window of earlier rows and testing on the next block.
How many folds?
- 5 or 10 are sensible defaults.
- More folds mean larger training sets (less pessimistic estimates) but more computation.
- Very large datasets may need only a single validation split, since one split is already stable and CV is expensive.
- Leave-one-out (k = number of rows) is rarely worth it outside very small datasets.
Common mistakes
- Preprocessing outside the pipeline, leaking information into every fold.
- Reporting only the mean and hiding high variance.
- Using shuffled k-fold on time series.
- Ignoring groups, so the same person appears in train and test.
- Treating the best grid-search score as the final estimate. Confirm on a held-out test set.
- Comparing models on different folds. Use the same CV splitter (with a fixed random_state) for fair comparisons.
FAQ
Does cross-validation produce a final model?
No. It estimates performance. Afterwards, fit your chosen pipeline on all training data (GridSearchCV does this automatically with refit=True).
Should I still keep a test set?
Yes, whenever you use CV to make choices (models, features, hyperparameters). The test set gives an unbiased final check.
Can I use cross-validation for regression?
Yes; use KFold and regression metrics such as neg_mean_absolute_error (scikit-learn negates errors so that higher is always better). See Linear Regression in Python.
Next steps
Apply cross-validation to logistic regression, improve inputs with feature engineering, and make sure you are measuring the right thing with classification metrics.



