Single logo
  • Courses
  • Blog
  • About
Join for freeJoin free
Learning pathClassify and Evaluate: Logistic Regression to Cross-Validation
  1. 1
    Logistic Regression and the Sigmoid: Score, Squash, Decide
  2. 2
    Logistic Regression in scikit-learn: predict, predict_proba and Softmax
  3. 3
    Why Accuracy Lies: The Confusion Matrix, Baselines and Type I/II Errors
  4. 4
    Precision, Recall and F1 Score: Two Questions and One Balance
  5. 5
    ROC Curve, AUC and Choosing a Classification Threshold
  6. 6
    Handling Imbalanced Data: class_weight, SMOTE and the Resampling Leak
  7. 7
    Cross-Validation: KFold, StratifiedKFold, cross_val_score and cross_validate
  1. Blog
  2. /
  3. Machine Learning
  4. /
  5. Supervised Learning

Learning path: Classify and Evaluate: Logistic Regression to Cross-Validation · Step 7 of 7

Cross-Validation: KFold, StratifiedKFold, cross_val_score and cross_validate

The same model on five different splits scores F1 from 0.52 to 0.63. Cross-validation replaces one lucky number with a mean and a spread: KFold vs StratifiedKFold, cross_val_score, cross_validate on four models, then one honest test.

Chaand Sheikh

·27 November 2026Classification and Evaluation

What you will learn

  • Show why a single train-test split is partly luck
  • Use StratifiedKFold so every fold keeps its share of a rare class
  • Score one model with cross_val_score and report mean and spread
  • Compare many models on many metrics with cross_validate, then test the winner once

Before you start

  • Precision, Recall and F1 Score
  • Handling Imbalanced Data

A chef cooks one plate and a critic gives it 9 out of 10. Is the chef great, or was that a lucky plate? A fairer critic tastes five dishes: 9, 5, 7, 8 and 6. The average is 7, and you can also see how much the scores vary.

Cross-validation does the same for a model: five test parts instead of one, a mean, and a spread. We'll use the fraud data from Handling Imbalanced Data: 20,000 payments, 200 frauds.

One split is luck

import pandas as pd
from sklearn.dummy import DummyClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import f1_score
from sklearn.model_selection import (KFold, StratifiedKFold,
    cross_val_score, cross_validate, train_test_split)
from imblearn.over_sampling import SMOTE
from imblearn.pipeline import Pipeline

df = pd.read_csv("payments.csv")
X = df.drop(columns="fraud")
y = df["fraud"]
print(X.shape, int(y.sum()), "frauds")
(20000, 6) 200 frauds

Same model, same data. Only the random_state of the split changes:

for seed in [1, 2, 3, 4, 5]:
    Xa, Xb, ya, yb = train_test_split(
        X, y, test_size=0.25,
        stratify=y, random_state=seed)
    model = LogisticRegression().fit(Xa, ya)
    f1 = f1_score(yb, model.predict(Xb))
    print("split", seed, "F1", round(f1, 2))
split 1 F1 0.52
split 2 F1 0.55
split 3 F1 0.55
split 4 F1 0.63
split 5 F1 0.55

Nothing changed except which rows landed in the test part, and F1 moved from 0.52 to 0.63. Report split 4 and the model looks better than it is.

How k-fold cross-validation works

First, lock the test part away. Everything below uses the training rows only.

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, stratify=y, random_state=42)
print(X_train.shape, X_test.shape)
(15000, 6) (5000, 6)

Cut the 15,000 training rows into five equal folds of 3,000. In round 1, fold 1 is the test fold and the other four train the model. Round 2 tests on fold 2, and so on. Every row is tested exactly once and you get five scores.

Five folds, five rounds, five scores fold 1 fold 2 fold 3 fold 4 fold 5 round 1 test train train train train F1 0.54 round 2 train test train train train F1 0.57 round 3 train train test train train F1 0.54 round 4 train train train test train F1 0.70 round 5 train train train train test F1 0.38 mean F1 0.544, std 0.101 (each fold: 3,000 rows, 30 frauds)
5-fold stratified cross-validation of plain logistic regression on the training rows. Each fold takes one turn as the test fold. One fold says 0.70, another 0.38.

KFold vs StratifiedKFold

With a rare class there's a catch. This function counts the frauds in each test fold:

def frauds_per_fold(cv):
    return [int(y_train.iloc[t].sum())
            for _, t in cv.split(X_train, y_train)]

skf = StratifiedKFold(
    n_splits=5, shuffle=True, random_state=42)
print("KFold          ", frauds_per_fold(KFold(5)))
print("StratifiedKFold", frauds_per_fold(skf))
KFold           [33, 28, 31, 34, 24]
StratifiedKFold [30, 30, 30, 30, 30]

Plain KFold gives some folds more frauds than others, so some folds are easier. StratifiedKFold keeps the fraud share equal: exactly 30 in every fold. For classification, use it.

cross_val_score: five scores in one line

scores = cross_val_score(
    LogisticRegression(), X_train, y_train,
    cv=skf, scoring="f1")
print(scores.round(2))
print("mean", round(scores.mean(), 3),
      "std", round(scores.std(), 3))
[0.54 0.57 0.54 0.7  0.38]
mean 0.544 std 0.101

The model is fitted five times, once per round. Report 0.544 ± 0.101, not your luckiest fold. A mean and a spread beat one lucky number.

cross_validate: many models, many metrics

To compare models fairly, give every model the same folds. Here are four: the lazy baseline, plain logistic regression, the balanced one and a gentle SMOTE pipeline. Because SMOTE sits in a pipeline, it only touches the training folds.

models = {
    "dummy": DummyClassifier(
        strategy="most_frequent"),
    "plain": LogisticRegression(),
    "balanced": LogisticRegression(
        class_weight="balanced"),
    "smote_0.05": Pipeline([
        ("smote", SMOTE(sampling_strategy=0.05,
                        random_state=42)),
        ("lr", LogisticRegression())]),
}

metrics = ["recall", "f1", "roc_auc"]
rows = {}
for name, model in models.items():
    res = cross_validate(model, X_train, y_train,
                         cv=skf, scoring=metrics)
    rows[name] = {m: res["test_" + m].mean()
                  for m in metrics}
print(pd.DataFrame(rows).T.round(3))
            recall     f1  roc_auc
dummy         0.00  0.000    0.500
plain         0.38  0.544    0.877
balanced      0.78  0.100    0.890
smote_0.05    0.50  0.558    0.883

Four models × five folds = 20 fits. cross_validate returns each metric as test_<name>; we keep the mean.

  • The dummy catches no fraud at all.
  • Balanced has the best recall, 0.78, but its F1 falls to 0.100.
  • smote_0.05 wins on F1 with 0.558.

Only the winner meets the test part, once

best = models["smote_0.05"].fit(X_train, y_train)
pred = best.predict(X_test)
print("test F1:", round(f1_score(y_test, pred), 3))
test F1: 0.642

Refit the winner on all 15,000 training rows and open the test part once: F1 0.642. One honest final number.

Cross-validate on the training part, choose there, test once. If you go back and tweak after looking at the test score, the test part has become a validation part.

Common mistakes

  • Cross-validating on all the data. Lock the test part first; folds come from the training rows.
  • Plain KFold on a rare class. Folds get 24 to 34 frauds. Use StratifiedKFold.
  • Resampling before cross-validation. Put SMOTE in an imblearn Pipeline so each test fold stays real.
  • Reporting only the mean. A std of 0.101 says the score moves a lot from fold to fold.

Quick recap

ToolWhat it doesFraud data
StratifiedKFold(5, shuffle=True)folds with an equal class share30 frauds per fold
cross_val_scoreone model, one metric, k scoresF1 0.544 ± 0.101
cross_validatemany metrics per modelsmote_0.05 best F1, 0.558
Final test, oncewinner refit on all training rowsF1 0.642

Try it yourself

Add "precision" to metrics and set n_splits=10. Does the winner change?

The notebook and payments.csv are in the StudyEasy AI Community, free to join.

Built this? Share your solution in the StudyEasy AI Community.

Join free on Skool →
← Previous
Handling Imbalanced Data: class_weight, SMOTE and the Resampling Leak
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool
Go deeper with a course

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)

Related articles
Linear Regression and the Cost Function: Draw a Line, Score It

Draw a straight line through six kids' ages and weights, measure every miss, and turn the misses into one score, the mean squared error. Then let np.polyfit find the line with the lowest score.

Gradient Descent Explained: Feel the Slope, Step Downhill

Instead of handing over the best line, let the computer walk to it: measure the slope of the cost, step downhill with a learning rate, repeat. Shown step by step on six kids' ages and weights.

Linear Regression in scikit-learn: Fit, Predict and Read the Price Tags

Predict a yearly medical bill with scikit-learn's LinearRegression: first from age alone, then from every column inside a pipeline. Each coefficient reads like a price tag, and smoker_yes is by far the biggest.

Regression Metrics: MAE, RMSE, R-squared and the Baseline to Beat

Score a regression model honestly: MAE, MSE and RMSE from four darts, then the insurance model on 268 test people, a DummyRegressor baseline to beat, R-squared and adjusted R-squared, and a residual plot.

On this page
  • One split is luck
  • How k-fold cross-validation works
  • KFold vs StratifiedKFold
  • cross_val_score: five scores in one line
  • cross_validate: many models, many metrics
  • Only the winner meets the test part, once
  • Common mistakes
  • Quick recap
  • Try it yourself
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool
Go deeper with a course

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.