Python & Data Science

Stratified K Fold Why Plain Cross Validation Break

You spend weeks building a fraud-detection model. The data is messy — 99% legitimate transactions, 1% fraud. You run a standard 5-fold cross-validation, and the model scores 99% accuracy. You deploy it with confidence. A month later, you check the logs: the model has flagged exactly zero fraudulent transactions. What happened?

This is a story I’ve seen play out more times than I can count. The model isn’t broken — your evaluation is. Standard k-fold cross-validation, the workhorse of model validation, silently fails when your classes are imbalanced. And the worst part? It gives you a beautiful score right up until the moment it fails in production.

Let’s dig into why this happens, how to fix it, and what to watch out for.

The Setup: You Train a Model, It Looks Great — Then Fails in Production

Imagine you’re building a fraud detector for a bank. Out of every 100 transactions, 99 are legitimate and 1 is fraud. That’s a 99:1 ratio — classic severe imbalance.

Standard 5-fold cross-validation randomly splits your data into 5 chunks. Each chunk has about 20% of the data. With 10,000 transactions, each fold has about 2,000 samples. But here’s the problem: with only 100 fraud cases total, each fold should have about 20 fraud samples on average. But random splits don’t guarantee that.

Let’s see what actually happens:

import numpy as np
from sklearn.model_selection import KFold

# Simulate a 99:1 imbalanced dataset
np.random.seed(42)
n_samples = 1000
n_fraud = 10  # 1% fraud

# Create labels: 0 = legitimate, 1 = fraud
y = np.array([0] * (n_samples - n_fraud) + [1] * n_fraud)
np.random.shuffle(y)

print("Overall class distribution:")
print(f"Class 0 (legitimate): {np.sum(y == 0)} ({np.mean(y == 0)*100:.1f}%)")
print(f"Class 1 (fraud): {np.sum(y == 1)} ({np.mean(y == 1)*100:.1f}%)")
print()

# Run standard 5-fold cross-validation
kf = KFold(n_splits=5, shuffle=True, random_state=42)

print("Class distribution in each fold (standard KFold):")
for fold, (train_idx, test_idx) in enumerate(kf.split(np.zeros(len(y)), y)):
    y_train = y[train_idx]
    y_test = y[test_idx]
    
    train_fraud = np.sum(y_train == 1)
    test_fraud = np.sum(y_test == 1)
    
    print(f"Fold {fold+1}:")
    print(f"  Train: {train_fraud} fraud samples ({train_fraud/len(y_train)*100:.2f}%)")
    print(f"  Test: {test_fraud} fraud samples ({test_fraud/len(y_test)*100:.2f}%)")
    
    if test_fraud == 0:
        print(f"  ⚠️ WARNING: Test fold has ZERO fraud samples!")
    if train_fraud == 0:
        print(f"  ⚠️ WARNING: Train fold has ZERO fraud samples!")
    print()

When you run this, you’ll likely see something alarming: one or more folds have zero fraud samples in the test set. That means the model is being evaluated on a test set that contains only legitimate transactions — it can predict “not fraud” for everything and get 100% accuracy on that fold. The cross-validation score becomes a meaningless average of some real scores and some perfect-but-useless scores.

This isn’t a model bug — it’s an evaluation bug. The CV metric is lying to you because the test set doesn’t represent the real-world class distribution.

What’s Actually Going On? The Anatomy of a Broken Split

Let’s make this concrete with a tiny example you can wrap your head around.

Think of a dataset with 100 samples: 99 are class A (legitimate) and 1 is class B (fraud). With 5-fold cross-validation, each fold has about 20 samples. That single class B sample can only end up in one fold. The other four folds have zero class B samples.

Here’s what that means for your model:

  • In 4 out of 5 folds, the model never sees class B during training (if B is in the test fold) or never gets evaluated on B (if B is in the training fold).
  • The CV score is an average of 4 meaningless scores and 1 real one.
  • The metric lies: Accuracy stays high because the model learns to always predict “class A” — which is correct 99% of the time. But that’s useless for catching fraud.

Now here’s the interesting part: the problem gets worse with more folds. Ten-fold CV on 100 samples means 10 samples per fold — the minority class might not appear at all in some folds.

Let’s see this in action with a small synthetic dataset:

import numpy as np
from sklearn.model_selection import KFold

# Tiny dataset: 100 samples, 99:1 ratio
np.random.seed(42)
n_samples = 100
n_minority = 1  # Just 1 minority sample

y = np.array([0] * (n_samples - n_minority) + [1] * n_minority)
np.random.shuffle(y)

print("Dataset: 100 samples, 99 class A, 1 class B")
print(f"Class distribution: {np.sum(y == 0)} class A, {np.sum(y == 1)} class B")
print()

# Show where the single class B sample ends up
kf = KFold(n_splits=5, shuffle=True, random_state=42)

print("Where does the single class B sample go?")
for fold, (train_idx, test_idx) in enumerate(kf.split(np.zeros(len(y)), y)):
    y_test = y[test_idx]
    minority_in_test = np.sum(y_test == 1)
    
    print(f"Fold {fold+1}: Test set has {minority_in_test} class B sample(s)")
    
    if minority_in_test == 0:
        print(f"  → The model is evaluated on a test set with NO class B samples")
        print(f"  → It can predict 'class A' for everything and get 100% accuracy")
    else:
        print(f"  → This fold actually tests the model's ability to detect class B")
    print()

This tiny example reveals the core problem: standard k-fold treats all samples equally, but when one class is rare, random splits can’t guarantee that rare class appears in every fold.

The Fix: Stratification — Preserving Class Ratios in Every Fold

Think of it this way: You have a bag of 99 red marbles and 1 blue marble. Standard k-fold grabs random handfuls — some have no blue. Stratified k-fold ensures every handful has exactly the same proportion of blue as the whole bag.

Definition: Stratified k-fold is a cross-validation technique that splits data so each fold maintains the same class distribution as the original dataset.

For classification, this means each fold’s class ratio matches the full dataset’s ratio (within rounding). For the 99:1 example, each fold will have approximately 99% class A and 1% class B.

The scikit-learn implementation is StratifiedKFold from sklearn.model_selection. It works exactly like KFold but guarantees balanced splits.

Here’s the catch: Stratification only works for classification problems. For regression, you need other techniques (like quantile-based binning).

Let’s see it in action:

import numpy as np
from sklearn.model_selection import StratifiedKFold

# Same 99:1 dataset as before
np.random.seed(42)
n_samples = 1000
n_fraud = 10

y = np.array([0] * (n_samples - n_fraud) + [1] * n_fraud)
np.random.shuffle(y)

print("Overall class distribution:")
print(f"Class 0 (legitimate): {np.sum(y == 0)} ({np.mean(y == 0)*100:.1f}%)")
print(f"Class 1 (fraud): {np.sum(y == 1)} ({np.mean(y == 1)*100:.1f}%)")
print()

# Use StratifiedKFold instead
skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)

print("Class distribution in each fold (StratifiedKFold):")
for fold, (train_idx, test_idx) in enumerate(skf.split(np.zeros(len(y)), y)):
    y_train = y[train_idx]
    y_test = y[test_idx]
    
    train_fraud = np.sum(y_train == 1)
    test_fraud = np.sum(y_test == 1)
    
    print(f"Fold {fold+1}:")
    print(f"  Train: {train_fraud} fraud samples ({train_fraud/len(y_train)*100:.2f}%)")
    print(f"  Test: {test_fraud} fraud samples ({test_fraud/len(y_test)*100:.2f}%)")
    print()

print("Notice: Every fold now has at least one fraud sample in both train and test!")

Every fold now has a proportional number of fraud samples. The model gets evaluated on a test set that actually looks like the real world.

Let’s See What Happens: Standard K-Fold vs. Stratified K-Fold on Real Data

Now let’s run a proper comparison. We’ll create a synthetic dataset with 98:2 imbalance (common in fraud, churn, or medical diagnosis), train a simple classifier, and compare the evaluation metrics from both methods.

import numpy as np
import pandas as pd
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import KFold, StratifiedKFold, cross_val_score
from sklearn.metrics import make_scorer, accuracy_score, precision_score, recall_score, f1_score

# Create a realistic imbalanced dataset
X, y = make_classification(
    n_samples=10000,
    n_features=20,
    n_informative=10,
    n_redundant=5,
    n_clusters_per_class=1,
    weights=[0.98, 0.02],  # 98% class 0, 2% class 1
    flip_y=0.05,
    random_state=42
)

print("Dataset shape:", X.shape)
print(f"Class distribution: {np.sum(y == 0)} class 0, {np.sum(y == 1)} class 1")
print(f"Minority class percentage: {np.mean(y == 1)*100:.2f}%")
print()

# Define scoring metrics
scoring = {
    'accuracy': make_scorer(accuracy_score),
    'precision': make_scorer(precision_score),
    'recall': make_scorer(recall_score),
    'f1': make_scorer(f1_score)
}

# Standard KFold
kf = KFold(n_splits=5, shuffle=True, random_state=42)
skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)

# Train a simple logistic regression
model = LogisticRegression(max_iter=1000, random_state=42)

print("=== Standard KFold Cross-Validation ===")
for metric_name, scorer in scoring.items():
    scores = cross_val_score(model, X, y, cv=kf, scoring=scorer)
    print(f"{metric_name.capitalize()}: {scores.mean():.4f} (+/- {scores.std()*2:.4f})")

print()
print("=== Stratified KFold Cross-Validation ===")
for metric_name, scorer in scoring.items():
    scores = cross_val_score(model, X, y, cv=skf, scoring=scorer)
    print(f"{metric_name.capitalize()}: {scores.mean():.4f} (+/- {scores.std()*2:.4f})")

What you’ll likely see:

  • Standard KFold accuracy might be around 98% — looks great! But the recall (how many frauds we actually catch) might be near zero.
  • Stratified KFold gives a more honest picture: accuracy might be lower (say 85%), but recall will be meaningful (maybe 0.70-0.80).

The standard CV said 98% accuracy, but that’s because the model learned to always predict “not fraud.” The stratified CV’s lower accuracy is more useful — and its recall tells you the model actually catches a decent proportion of frauds.

When Stratification Isn’t Enough: The Limits of This Technique

Stratification ensures fair evaluation, not balanced training. The model still sees imbalanced data during training — it may still be biased toward the majority class.

This is the hardest part: Many beginners think stratification “fixes” imbalance. It doesn’t. It fixes the evaluation. You still need resampling (SMOTE, undersampling) or cost-sensitive learning to train a good model.

Stratification + resampling order matters: Always split first (with stratification), then resample within the training fold. Never resample before splitting — that leaks information from test to train.

What about multi-class or multi-label? StratifiedKFold works for multi-class (it preserves the distribution of each class). For multi-label, use IterativeStratification or StratifiedGroupKFold.

Small datasets: With very small datasets and extreme imbalance (e.g., 1% minority with only 10 total samples), stratification may fail because a single sample can’t be split across folds. scikit-learn raises an error. Let’s see that:

import numpy as np
from sklearn.model_selection import StratifiedKFold

# Tiny dataset: 10 samples, 1 minority class sample
np.random.seed(42)
y = np.array([0] * 9 + [1] * 1)

print("Tiny dataset: 10 samples, 1 minority class sample")
print(f"Class distribution: {np.sum(y == 0)} class 0, {np.sum(y == 1)} class 1")
print()

skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)

try:
    for fold, (train_idx, test_idx) in enumerate(skf.split(np.zeros(len(y)), y)):
        print(f"Fold {fold+1}: Train size {len(train_idx)}, Test size {len(test_idx)}")
except ValueError as e:
    print(f"Error: {e}")
    print()
    print("Workaround: Use RepeatedStratifiedKFold or reduce number of splits")
    
    # Workaround: Use fewer splits
    skf_2 = StratifiedKFold(n_splits=2, shuffle=True, random_state=42)
    print("\nWith 2 splits instead of 5:")
    for fold, (train_idx, test_idx) in enumerate(skf_2.split(np.zeros(len(y)), y)):
        y_test = y[test_idx]
        print(f"Fold {fold+1}: Test set has {np.sum(y_test == 1)} minority sample(s)")

Putting It All Together: A Complete Workflow for Imbalanced Classification

Let’s walk through a complete, end-to-end example that combines everything we’ve learned.

import numpy as np
import pandas as pd
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import StratifiedKFold
from sklearn.metrics import precision_score, recall_score, f1_score, roc_auc_score

# Step 1: Create a realistic imbalanced dataset
X, y = make_classification(
    n_samples=5000,
    n_features=15,
    n_informative=8,
    n_redundant=3,
    weights=[0.97, 0.03],  # 97% class 0, 3% class 1
    random_state=42
)

print("Step 1: Data Exploration")
print(f"Total samples: {len(y)}")
print(f"Class distribution:")
print(f"  Class 0: {np.sum(y == 0)} ({np.mean(y == 0)*100:.1f}%)")
print(f"  Class 1: {np.sum(y == 1)} ({np.mean(y == 1)*100:.1f}%)")
print()

# Step 2: Set up StratifiedKFold
skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)

# Step 3 & 4: For each fold, train and evaluate
precision_scores = []
recall_scores = []
f1_scores = []
roc_auc_scores = []

print("Step 2-5: Running Stratified Cross-Validation")
print("=" * 50)

for fold, (train_idx, test_idx) in enumerate(skf.split(X, y)):
    X_train, X_test = X[train_idx], X[test_idx]
    y_train, y_test = y[train_idx], y[test_idx]
    
    # Verify stratification worked
    train_ratio = np.mean(y_train == 1)
    test_ratio = np.mean(y_test == 1)
    
    # Train a Random Forest
    model = RandomForestClassifier(n_estimators=100, random_state=42)
    model.fit(X_train, y_train)
    
    # Predict
    y_pred = model.predict(X_test)
    y_pred_proba = model.predict_proba(X_test)[:, 1]
    
    # Compute metrics
    precision = precision_score(y_test, y_pred)
    recall = recall_score(y_test, y_pred)
    f1 = f1_score(y_test, y_pred)
    roc_auc = roc_auc_score(y_test, y_pred_proba)
    
    precision_scores.append(precision)
    recall_scores.append(recall)
    f1_scores.append(f1)
    roc_auc_scores.append(roc_auc)
    
    print(f"Fold {fold+1}:")
    print(f"  Train minority ratio: {train_ratio:.3f} (expected ~0.03)")
    print(f"  Test minority ratio: {test_ratio:.3f} (expected ~0.03)")
    print(f"  Precision: {precision:.3f}")
    print(f"  Recall: {recall:.3f}")
    print(f"  F1-score: {f1:.3f}")
    print(f"  ROC-AUC: {roc_auc:.3f}")
    print()

# Step 6: Average metrics
print("=" * 50)
print("Average Metrics Across All Folds:")
print(f"Precision: {np.mean(precision_scores):.3f} (+/- {np.std(precision_scores)*2:.3f})")
print(f"Recall: {np.mean(recall_scores):.3f} (+/- {np.std(recall_scores)*2:.3f})")
print(f"F1-score: {np.mean(f1_scores):.3f} (+/- {np.std(f1_scores)*2:.3f})")
print(f"ROC-AUC: {np.mean(roc_auc_scores):.3f} (+/- {np.std(roc_auc_scores)*2:.3f})")
print()

print("Interpretation:")
print(f"The model catches {np.mean(recall_scores)*100:.0f}% of actual fraud cases (recall)")
print(f"But only {np.mean(precision_scores)*100:.0f}% of its fraud predictions are correct (precision)")
print(f"The F1 of {np.mean(f1_scores):.2f} tells us there's a trade-off between catching fraud and avoiding false alarms")

What We Learned and Where to Go Next

Let’s recap the key takeaways:

  1. Standard k-fold cross-validation breaks on imbalanced data because random splits can produce folds with zero minority-class samples, leading to misleading evaluation metrics.

  2. Stratified k-fold fixes the evaluation by preserving the class distribution in every fold, giving you an honest estimate of model performance.

  3. Stratification is not a cure for imbalance — it’s a cure for bad evaluation. You still need resampling or cost-sensitive methods to train a good model.

  4. Always split first, then resample. Never leak information from the test set into the training process.

Next up: How to combine stratified cross-validation with SMOTE (Synthetic Minority Oversampling) to both evaluate fairly and train effectively.

Check Your Understanding

Remember: What is the key difference between KFold and StratifiedKFold?

Understand: Explain in your own words why standard k-fold can give a misleading accuracy score on imbalanced data.

Apply: You have a dataset with 95% class A and 5% class B. You want to use 10-fold cross-validation. Can you use StratifiedKFold? What potential issue might arise?

Analyze: A colleague says “I used stratified k-fold and my F1 score improved from 0.3 to 0.7, so stratification made my model better.” Is this statement correct? Why or why not?

Evaluate: Given a multi-label classification problem with 100 labels and severe imbalance, would StratifiedKFold work? What alternative would you suggest?

  • Cross-Validation Explained: A Gentle Introduction — Start here if you need a refresher on the basics of k-fold cross-validation before diving into stratification.
  • SMOTE: Synthetic Minority Oversampling Explained — Learn how to combine stratified evaluation with oversampling to train better models on imbalanced data.
  • Precision vs. Recall: When Accuracy Lies — A deeper dive into why accuracy is a terrible metric for imbalanced problems and how to choose the right evaluation metric.

Apply What You Learned is for Supporter and Insider subscribers.

Subscribe to unlock the exercises on this post.

See plans
  • Python Engineering Under review

    Eigenvalues And Eigenvectors What They Actually Re

    Imagine you're a teacher with 100 students. Each student took two exams: Math and Reading. You notice something right away — students who do well on Math tend to do well on Reading. The scores are correlated.

  • Python Engineering Under review

    Encoding Categorical Variables One Hot Label Targe

    Let’s make this concrete. Imagine you’re building a model to predict house prices. You’ve got a column called `Neighborhood` with values like “CollgCr,” “Veenker,” and “Edwards.

  • Python Engineering Under review

    Degrees Of Freedom The Statistics Concept Nobody E

    Let's start with a simple analogy. Imagine you're building a three-legged stool. You can choose the length of the first two legs freely — any height you want. But once those two are set, the third leg's length is forced.

  • Python Engineering Under review

    Chi-Square Tests: When Your Data Is Categorical, Not Continuous

    Imagine you run a cozy little coffee shop. Every day, you track two things: what day of the week it is, and whether each customer orders a **hot** or an **iced** coffee. After a month, you have a pile of data.

Looking for something else?

Search every article by title, summary or topic.