Skip to content
E
Educatum

How does Cross Validation work?

Curated by Educatum AI teamLast updated:
Basic Concepts
Direct Answer

Cross-validation evaluates generalization by partitioning training data into k disjoint folds, iteratively fitting the model (and any preprocessing steps) on k-1 folds while validating on the remaining fold, and averaging performance across all k splits. Using stratified folds for classification and wrapping scalers inside a pipeline prevents validation variance and data leakage.

Study Card: How does Cross Validation work?

Direct Answer

Cross-validation (CV) is a resampling procedure for estimating out-of-sample generalization error and tuning hyperparameters without touching the held-out test set. In kk-fold cross-validation, the training set is divided into kk equally sized folds: for each iteration i∈{1,…,k}i \in \{1, \dots, k\}, fold ii is held out as the validation split while the model and all preprocessing transforms (such as scalers, imputers, or feature selectors) are fit strictly on the remaining k−1k - 1 folds. Averaging metrics across all kk validation folds yields a far lower-variance performance estimate than a single arbitrary train/validation split, while keeping a separate test set untouched for final evaluation.

Key Terms

  • kk-Fold Cross-Validation: Partitions training data into kk equal folds (typically k=5k = 5 or 1010), training and validating kk separate models.
  • Stratified kk-Fold: Preserves class label proportions across every fold—essential for classification, especially with imbalanced classes.
  • Leave-One-Out CV (LOOCV): Extreme case k=Nk = N, fitting NN models on N−1N - 1 examples; nearly unbiased but computationally costly (NN fits) and can suffer high variance across overlapping training folds.
  • Time Series Split (TimeSeriesSplit): Expanding-window forward validation that strictly trains on past timestamps and validates on future timestamps to prevent temporal leakage.
  • Group kk-Fold (GroupKFold): Keeps all records sharing a group ID (e.g., patient, user, or document) in the same fold so correlated entities do not span train and validation.

Example

Suppose you have 1,000 training examples and run 5-fold stratified cross-validation:

  1. Partition: Split the 1,000 examples into 5 balanced folds of 200 samples each.
  2. Iterate (5 rounds): In round 1, fit StandardScaler and LogisticRegression on folds 2–5 (800 rows) and score on fold 1 (200 rows). Repeat with each fold serving once as the validation split.
  3. Aggregate & Refit: Report the mean and standard deviation across the 5 validation scores to select hyperparameters or compare models; then refit the winning pipeline on all 1,000 training rows before evaluating once on the held-out test set.

Code Implementation

import pandas as pd
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.model_selection import StratifiedKFold, cross_val_score, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

# Load dataset and carve out a strictly held-out test set first
data = load_breast_cancer()
X = pd.DataFrame(data.data, columns=data.feature_names)
y = data.target
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y
)

# Bundle StandardScaler + LogisticRegression inside a Pipeline so scaling
# is fit ONLY on the k-1 training folds inside every CV split (no fold leakage!)
pipeline = make_pipeline(
    StandardScaler(),
    LogisticRegression(max_iter=1000, random_state=42)
)

kfold = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
cv_scores = cross_val_score(pipeline, X_train, y_train, cv=kfold, scoring='accuracy')

print("Accuracy per fold:", [round(s, 4) for s in cv_scores])
print(f"Mean CV accuracy: {cv_scores.mean():.4f} +/- {cv_scores.std():.4f}")

# Refit final pipeline on full X_train and evaluate once on X_test
pipeline.fit(X_train, y_train)
test_accuracy = accuracy_score(y_test, pipeline.predict(X_test))
print(f"Held-out test accuracy: {test_accuracy:.4f}")
  • Pipeline Leakage Prevention: Fitting scalers, PCA, or SMOTE on X_train before cross_val_score leaks validation-fold statistics into training folds; always place preprocessing inside a scikit-learn Pipeline.
  • Bias-Variance of kk Choice: Small kk (e.g., k=2k = 2) trains on smaller subsets (higher pessimistic bias), while k=5k = 5 or 1010 provides a strong bias-variance and compute balance in practice.
  • Nested Cross-Validation: Uses an outer CV loop to measure generalization and an inner CV loop for hyperparameter tuning, preventing optimistic bias when reporting tuned model performance.
  • Regularization & Hyperparameter Tuning: CV directly identifies regularization strengths (λ\lambda, CC, dropout) that minimize out-of-sample error without overfitting a single validation split.
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.