Cross-validation and tuning
Cross-validation estimates how a whole modeling procedure performs on new data. Tuning repeats that estimate for many settings and keeps the best one. This page covers the splitters, the CV functions, learning and validation curves, the scikit-learn searches, Optuna, nested CV and imbalanced classes. The examples use data/customers.csv (churn). The blocks share one session:
import numpy as npimport pandas as pdfrom sklearn.compose import make_column_transformerfrom sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import StratifiedKFold, train_test_splitfrom sklearn.pipeline import Pipelinefrom sklearn.preprocessing import OneHotEncoder, StandardScalerfrom threadpoolctl import threadpool_limits
threadpool_limits(limits=1) # one thread for OpenMP and BLAS: fast on small data
customers = pd.read_csv("data/customers.csv")CAT = ["region", "plan", "contract", "payment_method"]NUM = ["age", "tenure_months", "monthly_charges", "support_tickets", "logins_last_30d"]X, y = customers[CAT + NUM], customers["churned"]X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.25, stratify=y, random_state=42 # the test set waits)prep = make_column_transformer( (OneHotEncoder(handle_unknown="ignore"), CAT), (StandardScaler(), NUM))pipe = Pipeline([("prep", prep), ("model", LogisticRegression(max_iter=1000))])cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42) # reuse everywhereQuick lookup
Section titled “Quick lookup”| I want to… | Use… | Notes |
|---|---|---|
| k folds for regression | KFold(5, shuffle=True, random_state=42) |
|
| k folds with equal class shares | StratifiedKFold(5, shuffle=True, random_state=42) |
classification |
| a steadier estimate on small data | RepeatedStratifiedKFold(n_splits=5, n_repeats=3, random_state=42) |
15 fits |
| keep each customer in one fold | GroupKFold(5) + groups=ids |
|
| groups and a rare class | StratifiedGroupKFold(5, shuffle=True, random_state=42) |
|
| one fold per store or site | LeaveOneGroupOut() |
few large groups |
| train on the past, test on the future | TimeSeriesSplit(n_splits=5, test_size=28, gap=0) |
rows sorted by time |
| a fixed validation set | PredefinedSplit(test_fold) |
-1 = always train |
| one CV score | cross_val_score(pipe, X, y, cv=cv, scoring="roc_auc") |
an array, one per fold |
| several metrics, times, train scores | cross_validate(..., scoring=[...], return_train_score=True) |
a dict of arrays |
| the fitted fold models | cross_validate(..., return_estimator=True) |
res["estimator"] |
| an out-of-fold prediction for every row | cross_val_predict(pipe, X, y, cv=cv, method="predict_proba") |
stacking, thresholds, plots |
| pass fit arguments | cross_validate(..., params={"model__sample_weight": w}) |
|
| does more data help? | learning_curve / LearningCurveDisplay.from_estimator |
|
| one hyperparameter’s effect | validation_curve / ValidationCurveDisplay.from_estimator |
|
| every combination | GridSearchCV(pipe, grid, cv=cv, scoring=...) |
|
| a fixed budget of random settings | RandomizedSearchCV(pipe, dists, n_iter=30, random_state=42) |
|
scale-free values (C, alpha, rates) |
scipy.stats.loguniform(1e-3, 1e2) |
|
| many candidates, cheap rounds first | HalvingRandomSearchCV(pipe, dists, factor=3) |
experimental import |
| search over different models | a list of grids that set the model step |
|
| skip a step in a search | {"prep__scale": ["passthrough", StandardScaler()]} |
|
| several metrics, refit on one | scoring={"auc": "roc_auc", "ap": "average_precision"}, refit="auc" |
|
| all results as a table | pd.DataFrame(search.cv_results_) |
|
| Bayesian optimization | optuna.create_study(sampler=TPESampler(seed=42)) |
set_verbosity(WARNING) |
| an honest score for a tuned model | cross_val_score(GridSearchCV(...), X, y, cv=outer) |
nested CV |
| weight a rare class | class_weight="balanced" |
no extra rows |
| oversample inside CV | imblearn.pipeline.make_pipeline(SMOTE(), model) |
never before the split |
| oversample mixed columns | SMOTENC(categorical_features=CAT) |
raw categories, before encoding |
| choose a threshold by CV | TunedThresholdClassifierCV(pipe, scoring="f1", cv=cv) |
see metrics |
Splitters
Section titled “Splitters”| Splitter | Use when | Key arguments | groups= |
|---|---|---|---|
KFold |
regression, independent rows | n_splits, shuffle, random_state |
— |
StratifiedKFold |
classification | as KFold |
— |
RepeatedKFold, RepeatedStratifiedKFold |
small data: average several shuffles | n_repeats |
— |
ShuffleSplit, StratifiedShuffleSplit |
many random train/validation splits | n_splits, test_size |
— |
GroupKFold |
several rows per entity | n_splits; shuffle from scikit-learn 1.6 |
required |
StratifiedGroupKFold |
groups and a rare class | n_splits, shuffle |
required |
GroupShuffleSplit |
a random group-aware hold-out | test_size |
required |
LeaveOneGroupOut, LeavePGroupsOut |
few large groups | n_groups |
required |
TimeSeriesSplit |
time-ordered rows | n_splits, test_size, gap, max_train_size |
— |
LeaveOneOut |
tiny data | — | — |
PredefinedSplit |
a validation set you fixed | test_fold |
— |
cv=5 (an int) |
quick checks | StratifiedKFold(5) for classifiers, else KFold(5), no shuffle |
— |
from sklearn.model_selection import GroupKFold, TimeSeriesSplit
rows = np.arange(10).reshape(-1, 1)store = np.array(["A", "A", "B", "B", "B", "C", "C", "D", "E", "E"])for k, (_, valid) in enumerate(GroupKFold(n_splits=3).split(rows, groups=store)): print(f"fold {k}: valid stores {sorted(set(store[valid].tolist()))}")ts = TimeSeriesSplit(n_splits=3, test_size=2, gap=1) # gap: rows skipped betweenfor train_idx, valid_idx in ts.split(rows): print("train", train_idx.tolist(), "valid", valid_idx.tolist())fold 0: valid stores ['B']fold 1: valid stores ['A', 'E']fold 2: valid stores ['C', 'D']train [0, 1, 2] valid [4, 5]train [0, 1, 2, 3, 4] valid [6, 7]train [0, 1, 2, 3, 4, 5, 6] valid [8, 9]flowchart LR
A{"Predict the future?"} -->|yes| T["TimeSeriesSplit"]
A -->|no| B{"Several rows per entity?"}
B -->|yes| G["GroupKFold /<br/>StratifiedGroupKFold"]
B -->|no| C{"Classification?"}
C -->|yes| S["StratifiedKFold"]
C -->|no| K["KFold"]
Cross-validation functions
Section titled “Cross-validation functions”from sklearn.model_selection import cross_val_predict, cross_val_score, cross_validate
auc = cross_val_score(pipe, X_train, y_train, cv=cv, scoring="roc_auc")print(f"ROC-AUC {auc.mean():.3f} ± {auc.std():.3f}", auc.round(3))res = cross_validate(pipe, X_train, y_train, cv=cv, scoring={"auc": "roc_auc", "ap": "average_precision"}, return_train_score=True)print(sorted(res))print(f"train AUC {res['train_auc'].mean():.3f}", f"valid AUC {res['test_auc'].mean():.3f}") # a small gap: no overfittingoof = cross_val_predict(pipe, X_train, y_train, cv=cv, method="predict_proba")[:, 1]print(oof.shape, oof[:3].round(3)) # each row predicted by a model that never saw itROC-AUC 0.812 ± 0.011 [0.804 0.81 0.828 0.821 0.797]['fit_time', 'score_time', 'test_ap', 'test_auc', 'train_ap', 'train_auc']train AUC 0.818 valid AUC 0.812(3750,) [0.003 0.208 0.022]| Function | Returns | Use for |
|---|---|---|
cross_val_score(est, X, y, cv, scoring) |
one array of fold scores | a quick estimate of one metric |
cross_validate(..., scoring=[...] or {...}) |
a dict: test_<name>, fit_time, score_time |
several metrics; return_train_score, return_estimator, return_indices |
cross_val_predict(..., method="predict_proba") |
one out-of-fold prediction per row | plots, thresholds, stacking (not a score: folds are pooled) |
n_jobs=-1 |
— | folds in parallel |
error_score="raise" |
— | fail loudly instead of a NaN score |
Learning and validation curves
Section titled “Learning and validation curves”from sklearn.ensemble import HistGradientBoostingClassifierfrom sklearn.model_selection import learning_curve, validation_curve
sizes, train_s, valid_s = learning_curve( pipe, X_train, y_train, train_sizes=[0.1, 0.3, 1.0], cv=cv, scoring="roc_auc")print("rows ", sizes, "\ntrain", train_s.mean(axis=1).round(3), "\nvalid", valid_s.mean(axis=1).round(3))hgb = Pipeline([("prep", prep), ("model", HistGradientBoostingClassifier( learning_rate=0.1, random_state=42))])train_s, valid_s = validation_curve( hgb, X_train, y_train, param_name="model__max_leaf_nodes", param_range=[2, 8, 32, 128], cv=cv, scoring="roc_auc",)print("train", train_s.mean(axis=1).round(3), "\nvalid", valid_s.mean(axis=1).round(3))rows [ 300 900 3000]train [0.832 0.833 0.818]valid [0.795 0.808 0.812]train [0.854 0.918 0.993 1. ]valid [0.84 0.842 0.826 0.814]| Pattern | Diagnosis | Next step |
|---|---|---|
| both curves low, close together | underfitting (bias) | more features, a more flexible model, less regularization |
| train high, validation much lower | overfitting (variance) | more data, regularize, a simpler model |
| validation still rising at the largest size | more data will help | collect rows |
| validation flat at the end | more data will not help much | better features or another model |
| validation peaks inside the range | a good value is near the peak | tune around it |
LearningCurveDisplay.from_estimator(...) and ValidationCurveDisplay.from_estimator(...) take the same arguments and draw the curves with bands of ±1 standard deviation.
Grid, random and halving search
Section titled “Grid, random and halving search”from scipy.stats import loguniform, randintfrom sklearn.experimental import enable_halving_search_cv # noqa: F401from sklearn.model_selection import ( GridSearchCV, HalvingRandomSearchCV, RandomizedSearchCV,)
grids = [ # one dict per model family; the "model" step is swapped {"model": [LogisticRegression(max_iter=1000)], "model__C": [0.01, 0.1, 1, 10]}, {"model": [HistGradientBoostingClassifier(random_state=42)], "model__learning_rate": [0.05, 0.1], "model__max_leaf_nodes": [8, 31]},]grid = GridSearchCV(pipe, grids, cv=cv, scoring="roc_auc").fit(X_train, y_train)print(grid.best_params_["model"], f"{grid.best_score_:.3f}")table = pd.DataFrame(grid.cv_results_).sort_values("rank_test_score")print(table[["rank_test_score", "mean_test_score", "std_test_score"]].head(3).round(3))
dists = {"model__learning_rate": loguniform(0.02, 0.3), "model__max_leaf_nodes": randint(4, 64), "model__l2_regularization": loguniform(1e-3, 10)}rand = RandomizedSearchCV(hgb, dists, n_iter=6, cv=cv, scoring="roc_auc", random_state=42).fit(X_train, y_train)print(f"random best {rand.best_score_:.3f}")print({k.split("__")[1]: np.round(v, 3).item() for k, v in rand.best_params_.items()})halving = HalvingRandomSearchCV(hgb, dists, n_candidates=9, factor=3, cv=cv, min_resources=400, # rows in the first round scoring="roc_auc", random_state=42)halving.fit(X_train, y_train)print("halving rows per round", halving.n_resources_, "candidates", halving.n_candidates_)HistGradientBoostingClassifier(random_state=42) 0.847 rank_test_score mean_test_score std_test_score4 1 0.847 0.0116 2 0.842 0.0115 3 0.835 0.007random best 0.842{'l2_regularization': 0.022, 'learning_rate': 0.029, 'max_leaf_nodes': 6}halving rows per round [400, 1200, 3600] candidates [9, 3, 1]| Search | Tries | Use when |
|---|---|---|
GridSearchCV(est, param_grid) |
every combination | 1–3 parameters, few values each |
RandomizedSearchCV(est, param_distributions, n_iter) |
n_iter random draws |
3+ parameters, continuous ranges |
HalvingGridSearchCV, HalvingRandomSearchCV |
many candidates on few rows, the best on more | many candidates; scores stable on small subsets |
| Optuna | each trial guided by earlier trials | expensive fits; conditional spaces |
| Argument | Meaning |
|---|---|
param_grid, param_distributions |
a dict (or list of dicts) of "step__param" → values or a distribution |
scoring |
a name, a scorer, or a dict for several metrics |
refit=True |
refit the best on all rows passed to fit; with several metrics: refit="auc" |
cv |
a splitter object (shuffled, seeded) |
n_iter, random_state |
random search budget and seed |
factor, resource, min_resources, n_candidates |
halving: keep 1/factor per round; the resource is rows by default |
return_train_score=True |
adds mean_train_score to see the gap |
n_jobs=-1 |
fits in parallel |
| Attribute | Holds |
|---|---|
best_params_, best_score_ |
the winner and its mean CV score (optimistic) |
best_estimator_ |
the winner refitted on all rows (with refit) |
cv_results_ |
params, mean_test_score, std_test_score, rank_test_score, param_<name> |
n_resources_, n_candidates_ |
halving: rows and candidates per round |
| SciPy distribution | Draws | Typical use |
|---|---|---|
randint(low, high) |
integers low … high - 1 |
max_depth, n_neighbors, leaves |
uniform(loc, scale) |
floats loc … loc + scale |
subsample, max_features |
loguniform(a, b) |
floats evenly per order of magnitude | C, alpha, learning_rate |
| a list | one item, uniformly | categorical options |
Optuna
Section titled “Optuna”import optunafrom sklearn.base import clone
optuna.logging.set_verbosity(optuna.logging.WARNING) # no log line per trial
def objective(trial: optuna.Trial) -> float: model = clone(hgb).set_params( model__learning_rate=trial.suggest_float("learning_rate", 0.02, 0.3, log=True), model__max_leaf_nodes=trial.suggest_int("max_leaf_nodes", 4, 64, log=True), model__min_samples_leaf=trial.suggest_int("min_samples_leaf", 5, 100), ) return cross_val_score(model, X_train, y_train, cv=cv, scoring="roc_auc").mean()
sampler = optuna.samplers.TPESampler(seed=42, n_startup_trials=4) # default 10study = optuna.create_study(direction="maximize", sampler=sampler)study.optimize(objective, n_trials=8) # 4 random trials, then 4 guided by TPErounded = {name: round(value, 3) for name, value in study.best_params.items()}print(round(study.best_value, 3), rounded)best = clone(hgb).set_params( **{f"model__{name}": value for name, value in study.best_params.items()})best.fit(X_train, y_train) # Optuna does not refit: you do0.847 {'learning_rate': 0.136, 'max_leaf_nodes': 4, 'min_samples_leaf': 98}| Optuna | Meaning |
|---|---|
trial.suggest_int(name, low, high, step=1, log=False) |
an integer, both ends included |
trial.suggest_float(name, low, high, log=False, step=None) |
a float; log=True for scale-free values |
trial.suggest_categorical(name, choices) |
one item of a list |
create_study(direction="maximize") |
"minimize" for an error |
TPESampler(seed=42) |
reproducible; the first n_startup_trials=10 trials are random, so a short run needs a lower value |
study.best_params, best_value, best_trial |
the winner |
study.trials_dataframe() |
one row per trial |
trial.report(value, step) + trial.should_prune() → raise optuna.TrialPruned() |
stop bad trials early with MedianPruner |
study.optimize(objective, n_trials=50, timeout=600) |
a trial or time budget |
Nested cross-validation
Section titled “Nested cross-validation”The inner loop tunes; the outer loop scores the whole “tune, then refit” procedure on folds the search never saw.
inner = StratifiedKFold(n_splits=3, shuffle=True, random_state=42)outer = StratifiedKFold(n_splits=5, shuffle=True, random_state=1)search = GridSearchCV(pipe, {"model__C": [0.01, 0.1, 1, 10]}, cv=inner, scoring="roc_auc")nested = cross_val_score(search, X_train, y_train, cv=outer, scoring="roc_auc")search.fit(X_train, y_train) # the model you shipprint(f"nested {nested.mean():.3f} ± {nested.std():.3f} | " f"best_score_ {search.best_score_:.3f}")print("best C", search.best_params_["model__C"])nested 0.811 ± 0.010 | best_score_ 0.812best C 0.1| Item | Value |
|---|---|
| fits | outer folds × inner folds × candidates (+ refits) |
| estimates | the procedure, not one fixed model |
| the model you ship | the search refitted on all training rows |
| report | nested mean ± std, then one test-set score |
Imbalanced classes
Section titled “Imbalanced classes”from imblearn.over_sampling import SMOTENCfrom imblearn.pipeline import make_pipeline as make_imb_pipeline
candidates = { "plain": pipe, "class_weight": clone(pipe).set_params(model__class_weight="balanced"), "SMOTENC": make_imb_pipeline( # resamples the training folds only SMOTENC(categorical_features=CAT, random_state=42), prep, LogisticRegression(max_iter=1000)),}for name, model in candidates.items(): res = cross_validate(model, X_train, y_train, cv=cv, scoring=["recall", "precision", "average_precision"]) print(f"{name:<12} recall {res['test_recall'].mean():.3f} " f"precision {res['test_precision'].mean():.3f} " f"AP {res['test_average_precision'].mean():.3f}")plain recall 0.285 precision 0.656 AP 0.554class_weight recall 0.783 precision 0.378 AP 0.547SMOTENC recall 0.766 precision 0.378 AP 0.538Weights and resampling move the threshold: recall rises, precision falls, and the ranking (AP) barely changes. A tuned threshold on the plain model often does the same job (TunedThresholdClassifierCV).
| Tool | Import | Notes |
|---|---|---|
| class weights | class_weight="balanced" or {0: 1, 1: 5} |
weight of class = ; most models |
| positive weight (boosting) | scale_pos_weight=n_neg / n_pos |
XGBoost, LightGBM |
| sample weights | fit(X, y, sample_weight=w); in CV: params={"model__sample_weight": w} |
any per-row weight |
| random oversampling | imblearn.over_sampling.RandomOverSampler |
duplicates rare rows |
| SMOTE | imblearn.over_sampling.SMOTE(k_neighbors=5) |
numeric features only |
| SMOTENC | SMOTENC(categorical_features=[...]) |
mixed numeric and categorical |
| SMOTEN | imblearn.over_sampling.SMOTEN |
all categorical |
| random undersampling | imblearn.under_sampling.RandomUnderSampler |
drops common rows; fast |
| pipeline with samplers | imblearn.pipeline.Pipeline, make_pipeline |
samplers run in fit only, never in predict |
| threshold | TunedThresholdClassifierCV, FixedThresholdClassifier |
often enough on its own |
Gotchas
Section titled “Gotchas”| Trap | Symptom | Fix |
|---|---|---|
cv=5 |
no shuffle; sorted data gives odd folds | a seeded splitter with shuffle=True |
| a new splitter per model | scores differ because of the folds | one splitter object for every model |
KFold with groups= |
the groups are ignored (and a warning) | GroupKFold or StratifiedGroupKFold |
| shuffled CV on time series | optimistic scores: the future leaks | TimeSeriesSplit |
| preprocessing fitted before CV | leakage, optimistic scores | every learned step in the pipeline |
| SMOTE before the split | recall and F1 far too high | the sampler inside imblearn.pipeline |
a sampler in a scikit-learn Pipeline |
TypeError: no transform |
imblearn.pipeline.Pipeline |
plain SMOTE on one-hot columns |
fractional categories | SMOTENC on raw categories, or class weights |
best_score_ reported as the result |
biased upward | nested CV or one test score |
| best value at the edge of the grid | the optimum may lie outside | widen the grid |
uniform(0.5, 1.0) |
draws 0.5 to 1.5 | uniform(loc, scale): uniform(0.5, 0.5) |
"C" instead of "model__C" |
ValueError: Invalid parameter |
the step prefix; sorted(pipe.get_params()) |
the neg_ scores |
negative values | flip the sign when you report |
Optuna n_jobs>1 |
not reproducible | n_jobs=1 with a seeded sampler |
| Optuna result used directly | the model is not fitted | rebuild with best_params and fit |
cross_val_predict scored as CV |
a pooled score, not the fold mean | cross_val_score for the estimate |
| tuning on the test set | an optimistic final score | tune with CV on the training set; test once |
| fold differences read as real | noise picked as the winner | compare paired fold scores; prefer the simpler model |
Learn more
Section titled “Learn more”- Module 37: model evaluation and tuning and its cheat sheet
- Module 34: the scikit-learn workflow for pipelines and
cross_validate - Module 40: time series for backtests with
TimeSeriesSplit - Master cheat sheet: metrics (scorer names, thresholds), boosting (early stopping) and scikit-learn API
- Decision guide: Which CV strategy