# Train/Test Split and Cross-Validation in Python

> How to use train_test_split and cross_val_score in Python, choose between KFold, StratifiedKFold, GroupKFold, and TimeSeriesSplit, and avoid data leakage during cross-validation.

Source: https://www.pythoncharts.com/machine-learning/train-test-split-cross-validation-python/ | Published: 2026-11-26 | Author: Alex Scott | Category: Machine Learning | Tags: machine learning, scikit-learn, train test split, cross validation, data leakage, model evaluation, matplotlib

Use `train_test_split(X, y, test_size=0.2, stratify=y, random_state=0)` to hold out a test set, and `cross_val_score(model, X_train, y_train, cv=5)` to estimate performance from five different validation folds of the training data. Pick the splitter to match how rows are related: stratified for classes, grouped for repeated subjects, and `TimeSeriesSplit` for data ordered in time.

## Quick Example

A single split gives a score that depends on which rows landed in the test set. This example repeats a split 200 times on 300 made-up loan applications, then compares those scores with one 5-fold cross-validation.

```python
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import (StratifiedKFold, cross_val_score,
                                     train_test_split)

X, y = make_classification(n_samples=300, n_features=8, n_informative=4,
                           weights=[0.75], class_sep=0.8, random_state=3)
model = LogisticRegression(max_iter=1000)

single = []
for seed in range(200):
    X_train, X_test, y_train, y_test = train_test_split(
        X, y, test_size=0.2, stratify=y, random_state=seed)
    single.append(model.fit(X_train, y_train).score(X_test, y_test))

folds = StratifiedKFold(n_splits=5, shuffle=True, random_state=3)
cv_scores = cross_val_score(model, X, y, cv=folds)

print(f"single splits: {min(single):.3f} to {max(single):.3f}")
print("5 folds:", cv_scores.round(3))
print(f"mean {cv_scores.mean():.3f}, standard deviation {cv_scores.std():.3f}")

fig, ax = plt.subplots(figsize=(8, 4.5), layout="constrained")
ax.hist(single, bins=np.arange(0.675, 1.0, 1 / 60), color="#94a3b8",
        edgecolor="white", label="200 single 80/20 splits")
ax.axvline(cv_scores.mean(), color="#be123c", lw=2.5,
           label=f"5-fold mean ({cv_scores.mean():.3f})")
ax.set(title="Test accuracy depends on the split", xlabel="Accuracy",
       ylabel="Number of splits")
ax.legend()
plt.show()
```

![Histogram of test accuracy over 200 random splits, spreading from about 0.72 to 0.95 around the 5-fold mean of 0.85](https://www.pythoncharts.com/machine-learning/train-test-split-cross-validation-python/images/train-test-split-score-spread.png)

The same model scores anywhere from 0.72 to 0.95 depending on the random seed, and 95% of the splits fall between 0.78 and 0.92. Each test set has only 60 rows. Cross-validation uses every row for validation once, and its average is a steadier estimate than any one split.

## Hold Out a Test Set with train_test_split

Split once at the start, tune with cross-validation on the training part, and score the test part a single time at the end.

```python
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, stratify=y, random_state=0)
print(X_train.shape, X_test.shape)
print(f"positive share: train {y_train.mean():.3f}, test {y_test.mean():.3f}")

scores = cross_val_score(model, X_train, y_train, cv=5, scoring="roc_auc")
final = model.fit(X_train, y_train)
print(f"cross-validated AUC {scores.mean():.3f}")
print(f"test accuracy {final.score(X_test, y_test):.3f}")
```

The main arguments:

- `test_size` is a share (`0.2`) or a row count (`100`). The default is 0.25.
- `stratify=y` keeps the class proportions the same in both parts.
- `random_state` makes the split repeatable.
- `shuffle=True` is the default. Set `shuffle=False` for time-ordered data.

When `cv` is a number and the model is a classifier, scikit-learn uses `StratifiedKFold` without shuffling. If your rows are sorted in some way, pass `StratifiedKFold(5, shuffle=True, random_state=0)`.

## KFold vs StratifiedKFold vs GroupKFold vs TimeSeriesSplit

Plotting which rows each splitter uses shows the difference quickly. This data has 40 rows in order, a rare class bunched near the end, and eight customers with five rows each.

```python
from matplotlib.colors import ListedColormap
from matplotlib.patches import Patch
from sklearn.model_selection import GroupKFold, KFold, TimeSeriesSplit

n = 40
labels = np.array([0] * 28 + [1] * 12)
groups = np.repeat(np.arange(8), 5)
splitters = [("KFold(4)", KFold(4)),
             ("StratifiedKFold(4)", StratifiedKFold(4)),
             ("GroupKFold(4)", GroupKFold(4)),
             ("TimeSeriesSplit(4)", TimeSeriesSplit(4))]
colors = ListedColormap(["#e2e8f0", "#2563eb", "#f59e0b"])

fig, axes = plt.subplots(5, 1, figsize=(9, 7), sharex=True, layout="constrained",
                         height_ratios=[4, 4, 4, 4, 2])
for ax, (name, splitter) in zip(axes, splitters):
    picture = np.zeros((4, n))  # 0 = unused
    group_ids = groups if isinstance(splitter, GroupKFold) else None
    splits = splitter.split(np.zeros(n), labels, group_ids)
    for fold, (train, valid) in enumerate(splits):
        picture[fold, train] = 1
        picture[fold, valid] = 2
    ax.pcolormesh(picture, cmap=colors, vmin=0, vmax=2, edgecolors="white", lw=1)
    ax.set_title(name, loc="left", fontsize=11)
    ax.set_yticks(np.arange(4) + 0.5, [f"Fold {i + 1}" for i in range(4)])
    ax.invert_yaxis()

axes[4].pcolormesh([labels, groups % 2], cmap="Greys", vmin=-0.3, vmax=2,
                   edgecolors="white", lw=1)
axes[4].set_yticks([0.5, 1.5], ["Class", "Group"])
axes[4].invert_yaxis()
axes[4].set_xlabel("Row number")
fig.legend(handles=[Patch(color="#2563eb", label="Train"),
                    Patch(color="#f59e0b", label="Validation"),
                    Patch(color="#e2e8f0", label="Unused")],
           loc="outside upper center", ncols=3, frameon=False)
plt.show()
```

![Diagram of train and validation rows for four folds of KFold, StratifiedKFold, GroupKFold and TimeSeriesSplit, with the class and group of each row underneath](https://www.pythoncharts.com/machine-learning/train-test-split-cross-validation-python/images/cross-validation-splits.png)

Reading the panels:

- **KFold** cuts the rows into blocks in order. The classes sit at the end, so folds 1 and 2 validate on no positives at all.
- **StratifiedKFold** takes a share of each class for every fold.
- **GroupKFold** keeps all five rows of a customer on the same side of the split.
- **TimeSeriesSplit** trains only on rows that come before the validation block.

| Splitter | Use it when | What goes wrong otherwise |
|---|---|---|
| `KFold` | Rows are independent, such as most regression data | Sorted rows give unrepresentative folds unless you shuffle |
| `StratifiedKFold` | Classification, especially with a rare class | Some folds get few or no positives |
| `GroupKFold` | Several rows per user, patient, or device | The model recognizes subjects it trained on |
| `TimeSeriesSplit` | Order in time matters | The model learns from the future |
| `StratifiedGroupKFold` | Both groups and class imbalance | Either of the two problems above |

## Group Leakage: Why Random Folds Can Score Too High

When one subject has many rows, random folds put some of them in training and some in validation. This example has 60 patients with 15 readings each. The readings identify the patient, and the diagnosis is random, so nothing here can predict a new patient.

```python
from sklearn.ensemble import RandomForestClassifier

rng = np.random.default_rng(21)
patient = np.repeat(np.arange(60), 15)
diagnosis = np.repeat(rng.permutation([0, 1] * 30), 15)
signature = rng.normal(0, 1, (60, 5))  # each patient's own baseline
readings = signature[patient] + rng.normal(0, 0.3, (900, 5))

forest = RandomForestClassifier(random_state=21)
random_folds = cross_val_score(
    forest, readings, diagnosis, cv=KFold(5, shuffle=True, random_state=21))
patient_folds = cross_val_score(
    forest, readings, diagnosis, groups=patient, cv=GroupKFold(5))

fig, ax = plt.subplots(figsize=(7, 4.5), layout="constrained")
for x, (scores, color) in enumerate([(random_folds, "#dc2626"),
                                     (patient_folds, "#2563eb")]):
    ax.bar(x, scores.mean(), color=color, alpha=0.25)
    ax.scatter(np.full(5, x), scores, color=color, zorder=3)
    ax.text(x + 0.12, scores.mean() + 0.015, f"mean {scores.mean():.2f}")
ax.axhline(0.5, color="#334155", ls="--", lw=1, label="Coin flip")
ax.set_xticks([0, 1], ["KFold (rows mixed)", "GroupKFold (new patients)"])
ax.set(title="Same model, same data, two ways to split", ylabel="Accuracy",
       ylim=(0, 1.08))
ax.legend(loc="upper right")
plt.show()
```

![Bar chart showing accuracy of 0.85 with rows mixed across folds and 0.45 when whole patients are held out](https://www.pythoncharts.com/machine-learning/train-test-split-cross-validation-python/images/group-leakage-comparison.png)

With rows mixed, the forest scores 0.85 by recognizing each patient's baseline and recalling their diagnosis. On patients it hasn't seen, it scores 0.45, which is no better than a coin flip. The second number is the one that matches how the model would be used.

## Put Preprocessing Inside the Cross-Validation

Any step that learns from the data, such as feature selection, scaling, or imputation, must be fit on the training folds only. Here every column is random noise. Selecting the 20 columns most related to `y` before splitting makes the noise look predictive.

```python
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.pipeline import make_pipeline

noise = rng.normal(size=(200, 2000))
coin = rng.permutation([0, 1] * 100)

picked = SelectKBest(f_classif, k=20).fit_transform(noise, coin)
leaky = cross_val_score(model, picked, coin, cv=5)

pipeline = make_pipeline(SelectKBest(f_classif, k=20), model)
honest = cross_val_score(pipeline, noise, coin, cv=5)

fig, ax = plt.subplots(figsize=(8, 4), layout="constrained")
width = 0.38
fold = np.arange(1, 6)
ax.bar(fold - width / 2, leaky, width, color="#dc2626",
       label=f"Select, then split (mean {leaky.mean():.2f})")
ax.bar(fold + width / 2, honest, width, color="#2563eb",
       label=f"Pipeline (mean {honest.mean():.2f})")
ax.axhline(0.5, color="#334155", ls="--", lw=1)
ax.set(title="Accuracy on pure noise", xlabel="Fold", ylabel="Accuracy",
       ylim=(0, 1.25))
ax.set_yticks(np.arange(0, 1.01, 0.2))
ax.legend(loc="upper left", ncols=2, frameon=False)
plt.show()
```

![Accuracy on random noise by fold, averaging 0.78 when features are selected before splitting and 0.51 with a pipeline](https://www.pythoncharts.com/machine-learning/train-test-split-cross-validation-python/images/feature-selection-leakage.png)

The leaky version reports 0.78 on data with no signal. The pipeline reruns feature selection inside each training fold and scores 0.51, which is correct. Pass a pipeline to `cross_val_score` or `GridSearchCV` and this takes care of itself.

## Cross-Validate Time Series with TimeSeriesSplit

For forecasting, each validation block has to come after its training data. `TimeSeriesSplit` grows the training window fold by fold. `test_size` fixes the length of each block, and `gap` leaves rows out between training and validation.

```python
from sklearn.linear_model import Ridge

day = np.arange(730)
weekday = np.eye(7)[day % 7]
season = np.column_stack([np.sin(2 * np.pi * day / 365),
                          np.cos(2 * np.pi * day / 365)])
features = np.column_stack([day, weekday, season])
sales = (200 + 0.15 * day + weekday @ [0, -8, -5, 2, 20, 45, 30]
         + season @ [25, -15] + rng.normal(0, 12, 730))

splitter = TimeSeriesSplit(n_splits=4, test_size=60)
fig, ax = plt.subplots(figsize=(9, 4.5), layout="constrained")
ax.plot(day, sales, color="#94a3b8", lw=1, label="Daily sales")
for fold, (train, valid) in enumerate(splitter.split(features), start=1):
    forecast = Ridge().fit(features[train], sales[train]).predict(features[valid])
    error = np.abs(forecast - sales[valid]).mean()
    ax.plot(day[valid], forecast, color="#c2410c", lw=1.5,
            label="Forecast" if fold == 1 else None)
    ax.axvline(valid[0], color="#334155", ls=":", lw=1)
    ax.text(valid[0] + 3, 150, f"Fold {fold}\nMAE {error:.1f}", fontsize=8)
ax.set(title="Each fold forecasts the next 60 days", xlabel="Day",
       ylabel="Sales", ylim=(135, None))
ax.legend(loc="upper left")
plt.show()
```

![Two years of daily sales with four consecutive 60-day forecasts, mean absolute error between about 8 and 10](https://www.pythoncharts.com/machine-learning/train-test-split-cross-validation-python/images/time-series-cross-validation.png)

Each model trains on all earlier days and forecasts the next 60. The mean absolute error stays between about 8 and 10 units, close to the noise built into the data. The first fold starts at day 490 because `test_size=60` and four folds reserve the last 240 days for validation.

## Practical Tips

- Use `cross_validate` instead of `cross_val_score` to get several metrics, fit times, or training scores at once.
- Report the spread of the fold scores along with the mean. Folds share training data, so the standard deviation is not a proper confidence interval.
- A score from `GridSearchCV.best_score_` was used to pick the settings, so it runs optimistic. Use the held-out test set, or nested cross-validation.
- With very little data, `RepeatedStratifiedKFold` averages over several shuffles.
- To see whether more data would help, plot a [learning curve](https://www.pythoncharts.com/machine-learning/learning-curve-validation-curve-python/).

## Similar Topics

- [Learning Curve and Validation Curve in Python](https://www.pythoncharts.com/machine-learning/learning-curve-validation-curve-python/)
- [Random Forest Classifier in Python: A Complete Example](https://www.pythoncharts.com/machine-learning/random-forest-classifier-python/)
- [How to Plot a ROC Curve and Calculate AUC in Python](https://www.pythoncharts.com/machine-learning/roc-curve-auc-python/)
