How does Cross Validation work?
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 -fold cross-validation, the training set is divided into equally sized folds: for each iteration , fold 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 folds. Averaging metrics across all 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
- -Fold Cross-Validation: Partitions training data into equal folds (typically or ), training and validating separate models.
- Stratified -Fold: Preserves class label proportions across every fold—essential for classification, especially with imbalanced classes.
- Leave-One-Out CV (LOOCV): Extreme case , fitting models on examples; nearly unbiased but computationally costly ( 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 -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:
- Partition: Split the 1,000 examples into 5 balanced folds of 200 samples each.
- Iterate (5 rounds): In round 1, fit
StandardScalerandLogisticRegressionon folds 2–5 (800 rows) and score on fold 1 (200 rows). Repeat with each fold serving once as the validation split. - 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}")
Related Concepts
- Pipeline Leakage Prevention: Fitting scalers, PCA, or SMOTE on
X_trainbeforecross_val_scoreleaks validation-fold statistics into training folds; always place preprocessing inside a scikit-learnPipeline. - Bias-Variance of Choice: Small (e.g., ) trains on smaller subsets (higher pessimistic bias), while or 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 (, , dropout) that minimize out-of-sample error without overfitting a single validation split.