K-fold cross-validation: split data into k roughly equal folds, train on k-1 folds and validate on the remaining fold, repeat k times, average metrics. Stratified k-fold preserves class label proportions in each fold (important for imbalanced classification). TimeSeriesSplit respects temporal order and doesn't shuffle — it produces train/test splits where test sets are later in time.Stratified 5-fold example (classification):python
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import make_classification
import numpy as np
X, y = make_classification(n_samples=1000, n_classes=2, weights=[0.9,0.1], random_state=42)
clf = RandomForestClassifier(random_state=42)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(clf, X, y, cv=cv, scoring='roc_auc')
print("Stratified 5-fold AUC:", np.mean(scores))
Time-series CV example:python
from sklearn.model_selection import TimeSeriesSplit, cross_val_score
from sklearn.linear_model import Ridge
import numpy as np
# X must be ordered by time
n = 200
X = np.arange(n).reshape(n,1) # feature placeholder
y = np.sin(np.arange(n)/20) # target placeholder
tscv = TimeSeriesSplit(n_splits=5)
model = Ridge()
scores = cross_val_score(model, X, y, cv=tscv, scoring='neg_mean_squared_error')
print("TimeSeriesSplit MSE:", -np.mean(scores))
When to choose:- Use stratified CV for classification with imbalanced classes to get reliable per-fold class representation.- Use TimeSeriesSplit for temporal data where future information must not leak into training (forecasting, sequential logs).Common pitfalls:- Data leakage: fit preprocessing (scalers, imputers) inside CV pipeline, not on full data.- Shuffling time series or using random CV for temporal problems yields optimistic bias.- Small class counts: stratification may fail if a class has fewer than n_splits samples — consider fewer folds or grouped CV.- Ignoring grouped dependencies (users, sessions): use GroupKFold if observations are correlated.