2. Cross-Validation & Resampling
Standard K-Fold Cross Validation Mechanics & Variance Auditing
In machine learning, relying on a single train-test split can introduce severe evaluation bias. If your split happens to place unusually easy-to-predict samples in the test set, your model's performance score will be artificially inflated. Conversely, a difficult test split will make your model look worse than it is. This instability is known as evaluation variance.
To mitigate this, K-Fold Cross Validation systematically partitions your training dataset into K equal-sized, non-overlapping subsets (called folds). The evaluation cycle runs K times. In each iteration, one unique fold is held out as the validation set, while the remaining K-1 folds are combined to form the training set. Every data point gets to be in the validation set exactly once, and is used for training K-1 times.
After K iterations, you get K distinct validation scores. Variance auditing involves calculating both the mean and the standard deviation of these scores. A high standard deviation across your folds indicates that your model is highly sensitive to the specific composition of its training data (high variance/overfitting), whereas a low standard deviation indicates a stable, reliable model across different data subsets.
import numpy as np from sklearn.model_selection import KFold from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error # Generate simulated regression dataset np.random.seed(42) X = np.random.rand(100, 2) y = 3 * X[:, 0] + 5 * X[:, 1] + np.random.normal(0, 0.1, 100) # Initialize K-Fold splitter with 5 splits kf = KFold(n_splits=5, shuffle=True, random_state=42) scores = [] # Manually step through the folds to audit variance for fold, (train_idx, val_idx) in enumerate(kf.split(X)): X_train, X_val = X[train_idx], X[val_idx] y_train, y_val = y[train_idx], y[val_idx] model = LinearRegression() model.fit(X_train, y_train) preds = model.predict(X_val) mse = mean_squared_error(y_val, preds) scores.append(mse) print(f"Fold {fold + 1} - MSE: {mse:.4f}") mean_score = np.mean(scores) std_score = np.std(scores) print(f"\nMean Validation MSE: {mean_score:.4f}") print(f"Validation Score Std Dev (Variance Audit): {std_score:.4f}")
Stratified K-Fold for Classification & Maintaining Class Ratios
Standard K-Fold partition is purely random. While random splits work fine for balanced datasets, they break down catastrophically when dealing with imbalanced datasets. For instance, if you have a dataset where only 2% of the samples represent a positive fraud class, a standard random K-Fold split might yield some folds that contain absolutely zero positive examples. Your model cannot be validated on a class it never sees in its test set, leading to erratic evaluation metrics.
Stratified K-Fold solves this by preserving the original class distribution in each fold. If your global dataset is composed of 90% Class A and 10% Class B, Stratified K-Fold forces every single split to contain exactly 90% Class A and 10% Class B samples. This guarantees that each fold is a statistically representative microcosm of your overall dataset.
Here is a comparison of standard vs stratified splits to help choose the correct strategy:
| Feature | Standard K-Fold | Stratified K-Fold |
|---|---|---|
| Class Proportions | Random, can fluctuate significantly across folds. | Strictly preserved across all folds. |
| Primary Use Case | Regression, or highly balanced classification. | Classification tasks, especially with class imbalance. |
| Target Variable Type | Continuous or discrete variables. | Categorical target variables only. |
import numpy as np from sklearn.model_selection import StratifiedKFold # Generate simulated heavily imbalanced target array (90 zeros, 10 ones) y = np.array([0] * 90 + [1] * 10) # Create a dummy feature set of the same length X = np.random.rand(100, 2) # Initialize Stratified K-Fold splitter with 5 splits skf = StratifiedKFold(n_splits=5) for fold, (train_idx, val_idx) in enumerate(skf.split(X, y)): # Count labels in the validation split zeros_count = np.sum(y[val_idx] == 0) ones_count = np.sum(y[val_idx] == 1) # Ratio should be exactly 18 zeros to 2 ones per fold (since 100 samples / 5 folds = 20 per fold) print(f"Fold {fold + 1} -> Validation Class 0 Count: {zeros_count}, Class 1 Count: {ones_count}")
Time-Series Split Conventions & Preventing Contamination
Standard cross-validation techniques assume that data points are Independent and Identically Distributed (I.I.D.). However, time-series data completely violates this assumption. Values are temporally correlated, meaning past events influence future ones. If you use standard random cross-validation on a time series, you will accidentally train your model on future data to predict the past.
This is called look-ahead bias or future-looking contamination. It leads to overly optimistic cross-validation scores that are impossible to duplicate in production, where the future is completely unknown.
To prevent this, we use TimeSeriesSplit (also known as a Walk-Forward or Rolling-Window validation). In this configuration, the training set grows incrementally with each step, but always consists only of historical records. The validation set is always a chunk of sequential time steps that immediately follow the training window. No future data ever leaks into the training fold.
import numpy as np from sklearn.model_selection import TimeSeriesSplit # Generate 6 sequential time-series steps (e.g., monthly stock values) timesteps = np.array(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']) values = np.array([100, 105, 110, 108, 115, 120]) # Initialize Time Series Split with 3 splits tss = TimeSeriesSplit(n_splits=3) print("Visualizing Walk-Forward Split Indices:") for fold, (train_idx, val_idx) in enumerate(tss.split(values)): train_months = timesteps[train_idx] val_months = timesteps[val_idx] print(f"Fold {fold + 1}:") print(f" Train: {train_months}") print(f" Validate: {val_months}")
Using cross_val_score and cross_validate in Scikit-learn
Manually looping over splits is useful for custom scenarios, but Scikit-learn provides two high-level wrapper functions that streamline this process: cross_val_score and cross_validate.
cross_val_score takes your estimator, your full dataset, and your cross-validation strategy, runs the training loop, and returns an array of scores for a single evaluation metric. It is simple but limited.
For deep model analysis, cross_validate is the superior choice. Unlike cross_val_score, it allows you to evaluate multiple metrics simultaneously, returns training times and prediction times, and can optionally return the training scores. Auditing the difference between train scores and validation scores across your folds is critical for catching overfitting trends early.
import numpy as np from sklearn.datasets import make_classification from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import cross_validate # Create a synthetic classification dataset X, y = make_classification(n_samples=200, n_features=10, random_state=42) # Initialize a model model = RandomForestClassifier(n_estimators=10, random_state=42) # Use cross_validate to get extensive diagnostics results = cross_validate( model, X, y, cv=5, scoring=['accuracy', 'f1'], return_train_score=True ) # Inspect the results dictionary print("Diagnostics keys:", list(results.keys())) print(f"\nMean Validation Accuracy: {np.mean(results['test_accuracy']):.4f}") print(f"Mean Train Accuracy: {np.mean(results['train_accuracy']):.4f}") print(f"Mean Fit Time: {np.mean(results['fit_time']):.4f} seconds")
Knowledge Check
Ready to test your understanding of 2. Cross-Validation & Resampling?