Cross-validation in Python answers a simple question: how well will this model do on data it has not seen, and how sure are we? A single train-test split gives one number that depends on luck. This guide shows how large that luck is on a real dataset, then compares k-fold, stratified and repeated cross-validation, uses them to compare two models, and ends with the two mistakes that make scores look better than they are.
The data is the Titanic passenger list (891 rows, 38.4% survived, 177 missing ages). We predict survival from class, sex, age, family size and fare with a random forest. Code was run with scikit-learn 1.9.1 and pandas 3.0.5.

One split is one roll of the dice
import pandas as pd, numpy as np
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.impute import SimpleImputer
from sklearn.pipeline import make_pipeline
url = "https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv"
d = pd.read_csv(url)
X = pd.DataFrame({"pclass": d.Pclass, "female": (d.Sex == "female").astype(int), "age": d.Age,
"sibsp": d.SibSp, "parch": d.Parch, "fare": d.Fare})
y = d.Survived
model = make_pipeline(SimpleImputer(strategy="median"),
RandomForestClassifier(300, min_samples_leaf=3, random_state=0, n_jobs=2))
for seed in range(5):
Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.2, random_state=seed)
print(seed, round(model.fit(Xtr, ytr).score(Xte, yte), 3))Output:
0 0.849
1 0.81
2 0.799
3 0.782
4 0.844The same model, the same data and the same settings give accuracy from 0.782 to 0.849 depending only on the random seed of the split. That is a 6.7-point spread, bigger than the difference between many models people argue about. With 179 test rows per split, each row is worth about half a percentage point. Anyone who reports “84.9%” from the first seed is reporting the best of these five by accident.
K-fold cross-validation in Python
K-fold cross-validation cuts the data into k parts, trains on k-1 and tests on the remaining one, and repeats until every part has been the test set once. Every row is tested exactly once, and you get k scores instead of one.
from sklearn.model_selection import KFold, StratifiedKFold, cross_val_score
kf = cross_val_score(model, X, y, cv=KFold(5, shuffle=True, random_state=0))
print("KFold ", kf.round(3), "mean", kf.mean().round(3), "sd", kf.std().round(3))
sk = cross_val_score(model, X, y, cv=StratifiedKFold(5, shuffle=True, random_state=0))
print("StratifiedKFold", sk.round(3), "mean", sk.mean().round(3), "sd", sk.std().round(3))
print("KFold, no shuffle:", cross_val_score(model, X, y, cv=KFold(5)).round(3))Output:
KFold [0.849 0.826 0.82 0.82 0.803] mean 0.824 sd 0.015
StratifiedKFold [0.866 0.854 0.809 0.792 0.792] mean 0.823 sd 0.031
KFold, no shuffle: [0.782 0.826 0.871 0.803 0.871]Both give a mean near 0.82 (0.824 and 0.823), so the average is stable even though the five fold scores range from 0.792 to 0.866 under the stratified version. Stratified folds keep the share of survivors the same in every fold; that matters most when one class is rare (see imbalanced data in Python). Without shuffling, the folds follow the file order, and the scores moved to 0.782, 0.826, 0.871, 0.803 and 0.871. That works here only because the file order is unrelated to the outcome. If your data is sorted by date, customer or label, always set shuffle=True, unless the order is the point (time series).
Repeated cross-validation: a better error bar
One run of 5-fold CV still depends on how the folds were drawn. Repeating the whole procedure with different random folds gives more scores and a more honest spread.
from sklearn.model_selection import RepeatedStratifiedKFold
rep = cross_val_score(model, X, y, cv=RepeatedStratifiedKFold(n_splits=5, n_repeats=10, random_state=0))
print(len(rep), "scores, mean", rep.mean().round(3), "sd", rep.std().round(3))
print("range", rep.min().round(3), "to", rep.max().round(3))Output:
50 scores, mean 0.827 sd 0.025
range 0.764 to 0.871Fifty scores (5 folds, 10 repeats) give a mean of 0.827 and a standard deviation of 0.025 between folds. The standard deviation of folds is not the uncertainty of the mean, since the folds share training data, but it shows that an individual 179-row test set can easily land two or three points away from the average. That is the number to remember when someone reports a gain of one point.
Compare two models fairly
To compare models, give them the same folds so they are tested on identical rows.
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from scipy import stats
cv = RepeatedStratifiedKFold(n_splits=5, n_repeats=5, random_state=0)
logit = make_pipeline(SimpleImputer(strategy="median"), StandardScaler(), LogisticRegression(max_iter=1000))
a = cross_val_score(model, X, y, cv=cv)
b = cross_val_score(logit, X, y, cv=cv)
print("forest", a.mean().round(4), "| logistic", b.mean().round(4))
print("forest better in", (a > b).sum(), "of", len(a), "folds")
print("paired t-test p:", stats.ttest_rel(a, b).pvalue)Output:
forest 0.8263 | logistic 0.793
forest better in 22 of 25 folds
paired t-test p: 9.42970666882283e-07The forest averages 0.8263 and logistic regression 0.7930, a gap of 3.3 points, and the forest is ahead in 22 of 25 folds. The paired t-test gives p of about 0.000001, but treat that number with suspicion: the 25 scores overlap in their training data, so they are not independent and the test overstates the certainty. The fold count (22 of 25) and the 3-point gap are the more honest evidence here. This is one dataset with six features, so it says nothing about forests versus logistic regression in general. For the details of each model see random forests explained and logistic regression in Python.
Mistake 1: tuning and scoring on the same folds
When you search for the best hyperparameters with cross-validation, the best score is selected from many tries and is biased upward. To see the size of the bias, use data where the true accuracy is 50%: 100 rows of random noise with random labels.
from sklearn.model_selection import GridSearchCV
from sklearn.svm import SVC
rng = np.random.default_rng(0)
Xn = rng.normal(size=(100, 200)); yn = rng.integers(0, 2, 100)
grid = {"C": [0.01, 0.1, 1, 10, 100], "gamma": [1e-4, 1e-3, 1e-2, 1e-1]}
gs = GridSearchCV(SVC(), grid, cv=5).fit(Xn, yn)
print("best CV score on pure noise:", round(gs.best_score_, 3))
nested = cross_val_score(GridSearchCV(SVC(), grid, cv=5), Xn, yn, cv=StratifiedKFold(5, shuffle=True, random_state=1))
print("nested CV score:", nested.mean().round(3))Output:
best CV score on pure noise: 0.53
nested CV score: 0.5On pure noise the grid search reports 0.53 as its best score, three points above chance, purely from picking the luckiest setting out of 20. Nested cross-validation, where the search runs inside each outer training fold, reports 0.50, which is the truth. The bias here is small because the grid is small. With bigger grids and smaller datasets it grows. If you report a score, report one that was not used to choose the settings.
Mistake 2: ignoring groups
If one person, patient or household appears in several rows, a random split puts some of them in training and others in test, and the model recognises them. In the Titanic data, 344 passengers share a ticket number with someone else. Group folds keep each ticket in one fold.
from sklearn.model_selection import StratifiedGroupKFold
print("passengers sharing a ticket:", d.Ticket.duplicated(keep=False).sum(), "of", len(d))
sg = cross_val_score(model, X, y, cv=StratifiedGroupKFold(5, shuffle=True, random_state=0), groups=d.Ticket)
print("grouped by ticket:", sg.mean().round(3), "| ordinary stratified:", sk.mean().round(3))Output:
passengers sharing a ticket: 344 of 891
grouped by ticket: 0.823 | ordinary stratified: 0.823Here the grouped score (0.823) is the same as the ordinary one (0.823), so ticket sharing did not inflate the result for this model and these features. I expected a drop and did not find one; that is a finding too. With features that identify a person, such as a name, the difference could be large, and I did not test that. The check is cheap, so do it when your rows are not independent. Time-ordered data needs another approach again, TimeSeriesSplit, which always tests on later rows than it trains on; the Titanic file has no dates, so we did not run it here.
Which cross-validation should you use?
For a quick default, use stratified 5-fold or 10-fold for classification and plain shuffled k-fold for regression. Repeat it when the dataset is small or the decision is close. Use group folds when rows belong to the same entity, nested CV when you tune and report, and a time-based split when the future must not leak into the past. Keep all preprocessing inside the pipeline so it is fitted on each training fold only, as shown in train test split in Python. Metrics other than accuracy are covered in the scikit-learn model tutorial.
The full list of splitters is in the scikit-learn cross-validation guide. The Titanic file is from the datasciencedojo datasets repository. Not tested here: leave-one-out, bootstrap validation and corrected resampled t-tests.
FAQ
What is cross-validation in Python?
A way to estimate how a model performs on unseen data by training and testing it several times on different parts of the dataset. In scikit-learn, cross_val_score does it in one call.
How many folds should I use?
Five or ten is the usual choice. More folds means more training data per fold but more compute. We used 5 folds, repeated up to 10 times.
What is the difference between KFold and StratifiedKFold?
StratifiedKFold keeps the class proportions the same in every fold. It matters most for rare classes. On the Titanic data both averaged 0.82.
Is cross-validation better than a train-test split?
It uses all rows for testing and gives several scores, so it is more reliable. On the same model, five random splits ranged from 0.782 to 0.849. You should still keep a final test set if you tune many settings.
