Sub topic 3
Cross-validation for Honest Model Evaluation
Prerequisites: basic Python, feature and label arrays, and the idea of a supervised model.
Cross-validation
Cross-validation estimates how well a model generalizes by repeating train-and-evaluate splits. In k-fold cross-validation, the data is divided into k folds. Each fold becomes the evaluation fold once, while the other folds train the model. The mean score is more stable than one random split.
Keep a separate test set outside cross-validation. Use cross-validation to compare models or tune hyperparameters. Evaluate the chosen model on the test set once.
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42
)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(model, X_train, y_train, cv=cv)
print("CV accuracy:", scores.mean())
model.fit(X_train, y_train)
print("Test accuracy:", model.score(X_test, y_test))Fit preprocessing on training data only
Preprocessing transforms features before modeling. Examples include scaling, imputation, and feature selection. Fit each transformation separately inside every training fold. A pipeline enforces this rule. Fitting a scaler on all rows lets information from evaluation rows influence the model. This is data leakage.
Grouped and dependent samples
Random splitting is unsafe when rows belong to the same person, patient, device, or document. Related rows can appear in both training and evaluation data, making the score too high. Use GroupKFold and pass group identifiers so an entire group stays on one side of each fold.
Time-ordered data
For forecasting or other time-dependent tasks, future rows must not train a model evaluated on the past. Use TimeSeriesSplit, which trains on earlier observations and evaluates on later observations. Do not shuffle time-ordered data unless the task truly has no temporal dependence.
When the test set does not match the real world
A test score estimates performance only for data from a similar distribution. Distribution shift occurs when deployment data differs, such as new users, changing prices, or a new sensor. Use time-based or group-based evaluation when that matches deployment, and monitor performance after release.
Exercise
Why should scaling be inside the cross-validation pipeline?
Show answer
Each fold must learn scaling statistics from its training rows only; otherwise evaluation information leaks into training.