Sub topic 3
Avoiding Leakage and Optimistic Scores
Assume you know basic Python, supervised learning, overfitting, and scikit-learn. Hyperparameter tuning must use only training data. Otherwise, the reported score can be too high.
Pipelines and nested cross-validation
Data leakage happens when information from validation or test data influences training. For example, scaling every row before cross-validation lets each training fold indirectly use statistics from its validation fold.
A pipeline keeps preprocessing inside each fold:
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.model_selection import GridSearchCV, cross_val_score
pipe = make_pipeline(StandardScaler(), SVC())
search = GridSearchCV(
pipe,
{"svc__C": [0.1, 1, 10]},
cv=3
)
scores = cross_val_score(search, X, y, cv=5)
print(scores.mean())Nested cross-validation uses an inner loop to select settings and an outer loop to estimate performance. The outer score measures the complete process, including tuning.
flowchart TD
A[All data] --> B[Outer training fold]
A --> C[Outer test fold]
B --> D[Inner cross-validation]
D --> E[Select hyperparameters]
E --> F[Fit and score on outer test fold]Bayesian optimization and sequential search
Bayesian optimization chooses the next trial using earlier results. A surrogate model estimates which settings are promising, while an acquisition rule balances exploration and exploitation. This can find good settings with fewer trials than a large grid.
Early stopping and pruning
Successive halving starts many trials with a small resource, such as few training epochs. It discards weak trials and gives more resources to survivors. Hyperband repeats this idea across several resource budgets. These methods save time when poor trials can be recognized early.
Planning budget and reproducibility
Set a limit on trials, training time, or total resources before tuning. Record the search space, metric, cross-validation scheme, software versions, data split, random seeds, and every result. A seed makes one run repeatable, but it does not prove that the result is stable.
Tuning with Optuna
Optuna provides sequential sampling and trial management:
import optuna
from sklearn.model_selection import cross_val_score
from sklearn.ensemble import RandomForestClassifier
def objective(trial):
model = RandomForestClassifier(
n_estimators=trial.suggest_int("trees", 50, 200),
max_depth=trial.suggest_int("depth", 2, 16),
random_state=0,
)
return cross_val_score(model, X_train, y_train, cv=5).mean()
study = optuna.create_study(direction="maximize")
study.optimize(objective, n_trials=30)
print(study.best_params, study.best_value)Interpreting results
Report the metric, mean and spread across folds, search budget, best settings, and untouched test score. A tiny improvement may not justify extra complexity or compute.
Exercise
Why does nested cross-validation reduce optimistic performance estimates?
Show answer
It evaluates each tuned model on outer-fold data that was not used to choose its hyperparameters.