37. Model evaluation and tuning — Cheat sheet
The essentials of module 37 on one page. Every runnable block on this page is checked against its output.
Quick lookup
Section titled “Quick lookup”| I want to… | Use… | Example |
|---|---|---|
| see if a model under- or overfits | training vs validation score | cross_validate(..., return_train_score=True) |
| know if more data will help | learning curve | LearningCurveDisplay.from_estimator(model, X, y, cv=cv) |
| see one hyperparameter’s effect | validation curve | ValidationCurveDisplay.from_estimator(model, X, y, param_name="m__max_depth", param_range=r) |
| keep class shares equal per fold | StratifiedKFold |
StratifiedKFold(5, shuffle=True, random_state=42) |
| keep all rows of an entity together | GroupKFold |
cross_val_score(m, X, y, groups=ids, cv=GroupKFold(5)) |
| groups and a rare class | StratifiedGroupKFold |
StratifiedGroupKFold(5, shuffle=True, random_state=42) |
| validate on the future only | TimeSeriesSplit |
TimeSeriesSplit(n_splits=5, test_size=90, gap=7) |
| try every combination | GridSearchCV |
GridSearchCV(pipe, {"m__C": [0.1, 1, 10]}, cv=cv) |
| sample a fixed budget | RandomizedSearchCV |
RandomizedSearchCV(pipe, dists, n_iter=20, random_state=42) |
| sample on a log scale | scipy.stats.loguniform |
loguniform(1e-3, 1e2) |
| try many candidates cheaply | successive halving | HalvingRandomSearchCV(pipe, dists, factor=3) |
| search with Bayesian optimization | Optuna TPE | optuna.create_study(sampler=TPESampler(seed=42)) |
| list valid parameter names | get_params() |
pipe.get_params().keys() |
| weight a rare class | class_weight |
LogisticRegression(class_weight="balanced") |
| choose a threshold from a score or cost | TunedThresholdClassifierCV |
TunedThresholdClassifierCV(model, scoring=make_scorer(profit)) |
| use a fixed threshold | FixedThresholdClassifier |
FixedThresholdClassifier(model, threshold=0.3) |
| oversample or undersample safely | imbalanced-learn pipeline | imblearn.pipeline.make_pipeline(prep, SMOTE(), model) |
| estimate a tuned model honestly | nested CV | cross_val_score(GridSearchCV(...), X, y, cv=outer) |
| silence Optuna | logging level | optuna.logging.set_verbosity(optuna.logging.WARNING) |
Bias, variance and fit
Section titled “Bias, variance and fit”| Diagnosis | Training score | Validation score | Gap | Next step |
|---|---|---|---|---|
| Underfitting (high bias) | low | low | small | more features, more flexible model, less regularization |
| Good fit | high | close to training | small | stop tuning; test once |
| Overfitting (high variance) | very high | much lower | large | more data, regularize, simpler model |
| Model | More complex (more variance) | Simpler (more bias) |
|---|---|---|
| Polynomial | higher degree |
lower degree |
| Decision tree | higher max_depth, lower min_samples_leaf, lower ccp_alpha |
the opposite |
| KNN | lower n_neighbors |
higher n_neighbors |
| Logistic, SVM | higher C |
lower C |
| Ridge, Lasso | lower alpha |
higher alpha |
| Boosting | more and deeper trees, higher learning_rate |
the opposite |
Learning and validation curves
Section titled “Learning and validation curves”import numpy as npfrom sklearn.datasets import make_classificationfrom sklearn.model_selection import StratifiedKFold, learning_curve, validation_curvefrom sklearn.tree import DecisionTreeClassifier
X, y = make_classification(n_samples=1000, n_features=10, random_state=42)cv = StratifiedKFold(n_splits=3, shuffle=True, random_state=42)tree = DecisionTreeClassifier(random_state=42)
sizes, train_s, valid_s = learning_curve( tree, X, y, train_sizes=[0.2, 0.6, 1.0], cv=cv, n_jobs=1) # scores shape: (n_sizes, n_folds)print("sizes", sizes, "valid", valid_s.mean(axis=1).round(3))
train_s, valid_s = validation_curve( tree, X, y, param_name="max_depth", param_range=[2, 4, 8, 16], cv=cv, n_jobs=1)print("train", train_s.mean(axis=1).round(3), "valid", valid_s.mean(axis=1).round(3))sizes [133 399 666] valid [0.836 0.839 0.864]train [0.88 0.934 0.985 1. ] valid [0.872 0.9 0.87 0.869]| Function / class | Varies | Returns or draws |
|---|---|---|
learning_curve(est, X, y, train_sizes=...) |
number of training rows | sizes, train_scores, valid_scores |
LearningCurveDisplay.from_estimator(...) |
same | plot; .train_sizes, .train_scores, .test_scores |
validation_curve(est, X, y, param_name=..., param_range=...) |
one hyperparameter | train_scores, valid_scores |
ValidationCurveDisplay.from_estimator(...) |
same | plot; .train_scores, .test_scores |
score_type="both" |
— | draw training and validation curves |
Cross-validation splitters
Section titled “Cross-validation splitters”| Splitter | Use when | Arguments |
|---|---|---|
KFold(n_splits, shuffle, random_state) |
regression, independent rows | shuffle unless the rows are randomly ordered |
StratifiedKFold(...) |
classification | keeps class shares; default cv=5 for classifiers |
GroupKFold(n_splits, shuffle, random_state) |
many rows per customer, store, patient | groups= in split, fit, cross_val_score |
StratifiedGroupKFold(...) |
groups + rare class | as above |
LeaveOneGroupOut() |
few large groups (for example 12 stores) | one fold per group |
TimeSeriesSplit(n_splits, test_size, gap, max_train_size) |
ordered in time, predict the future | rows must be sorted by time |
RepeatedStratifiedKFold(n_splits, n_repeats, random_state) |
small data; steadier estimate | more fits |
from sklearn.model_selection import GroupKFold, TimeSeriesSplit
rows = np.arange(8).reshape(-1, 1)customer = np.array(["A", "A", "A", "B", "B", "C", "D", "D"])for _, valid_idx in GroupKFold(n_splits=2).split(rows, groups=customer): print("valid customers:", sorted(set(customer[valid_idx].tolist())))
for train_idx, valid_idx in TimeSeriesSplit(n_splits=2, test_size=2, gap=1).split(rows): print("train", train_idx.tolist(), "valid", valid_idx.tolist())valid customers: ['A', 'C']valid customers: ['B', 'D']train [0, 1, 2] valid [4, 5]train [0, 1, 2, 3, 4] valid [6, 7]flowchart LR
A{"Future from past?"} -->|yes| T["TimeSeriesSplit"]
A -->|no| B{"Repeated entities?"}
B -->|yes| G["GroupKFold /<br/>StratifiedGroupKFold"]
B -->|no| C{"Classification?"}
C -->|yes| S["StratifiedKFold"]
C -->|no| K["KFold"]
Grid, random and halving search
Section titled “Grid, random and halving search”| Argument | Meaning |
|---|---|
param_grid / param_distributions |
dict (or list of dicts) of "step__param" → values or distribution |
scoring |
"roc_auc", "average_precision", "neg_mean_absolute_error", a scorer, or a list/dict for several |
refit |
True (default) refits the best on all rows; with several metrics, the metric name to refit on |
cv |
an int or a splitter object |
n_iter, random_state |
random search budget and seed |
return_train_score |
also store training scores (for a gap) |
n_jobs |
parallel fits; 1 for simple, reproducible runs |
| Attribute | Holds |
|---|---|
best_params_ |
the winning dict |
best_score_ |
its mean CV score (optimistic) |
best_estimator_ |
the winner refitted on all rows passed to fit |
cv_results_ |
every candidate: params, mean_test_score, std_test_score, rank_test_score, param_<name> |
n_candidates_, n_resources_ |
halving only: candidates and resource per round |
| SciPy distribution | Draws | Typical use |
|---|---|---|
randint(low, high) |
whole numbers low … high - 1 |
max_depth, n_neighbors |
uniform(loc, scale) |
floats loc … loc + scale |
max_features, subsample |
loguniform(a, b) |
floats spread evenly per order of magnitude | C, alpha, learning_rate |
| list | uniform choice | categorical options |
from scipy.stats import loguniform, randintfrom sklearn.experimental import enable_halving_search_cv # noqa: F401from sklearn.model_selection import ( GridSearchCV, HalvingRandomSearchCV, RandomizedSearchCV,)
grid = GridSearchCV(tree, {"max_depth": [3, 5, 8]}, cv=cv, n_jobs=1).fit(X, y)dists = {"max_depth": randint(2, 12), "ccp_alpha": loguniform(1e-4, 1e-1)}rand = RandomizedSearchCV(tree, dists, n_iter=8, cv=cv, random_state=42, n_jobs=1)halving = HalvingRandomSearchCV(tree, dists, n_candidates=9, factor=3, min_resources=100, cv=cv, random_state=42, n_jobs=1)for name, search in [("grid", grid), ("random", rand.fit(X, y)), ("halving", halving.fit(X, y))]: n_results = len(search.cv_results_["params"]) print(f"{name:<8} best {search.best_score_:.3f}, {n_results} results")print("halving resources per round:", halving.n_resources_)grid best 0.903, 3 resultsrandom best 0.913, 8 resultshalving best 0.903, 13 resultshalving resources per round: [100, 300, 900]Optuna
Section titled “Optuna”import optunafrom sklearn.model_selection import cross_val_score
optuna.logging.set_verbosity(optuna.logging.WARNING) # no line per trial
def objective(trial): model = DecisionTreeClassifier( max_depth=trial.suggest_int("max_depth", 2, 12), min_samples_leaf=trial.suggest_int("min_samples_leaf", 1, 100, log=True), criterion=trial.suggest_categorical("criterion", ["gini", "entropy"]), random_state=42, ) return cross_val_score(model, X, y, cv=cv).mean()
study = optuna.create_study( direction="maximize", sampler=optuna.samplers.TPESampler(seed=42))study.optimize(objective, n_trials=10)print(study.best_params, round(study.best_value, 3)){'max_depth': 5, 'min_samples_leaf': 8, 'criterion': 'gini'} 0.903| Optuna | Meaning |
|---|---|
trial.suggest_int(name, low, high, log=False, step=1) |
integer, both ends included |
trial.suggest_float(name, low, high, log=False, step=None) |
float; log=True for scale-free knobs |
trial.suggest_categorical(name, choices) |
one item of a list |
create_study(direction="maximize") |
"minimize" for an error |
TPESampler(seed=42) |
reproducible; first 10 trials are random |
study.best_params, best_value, best_trial |
the winner (no refit: rebuild and fit yourself) |
study.trials_dataframe() |
one row per trial: value, params_<name>, state |
trial.report(score, step); if trial.should_prune(): raise optuna.TrialPruned() |
stop bad trials early (iterative models) |
Imbalanced classes
Section titled “Imbalanced classes”| Tool | Import | Note |
|---|---|---|
| class weights | class_weight="balanced" on the model |
weight of class c is n / (k × n_c); no extra rows |
| threshold for a score or cost | sklearn.model_selection.TunedThresholdClassifierCV |
scoring=make_scorer(profit); .best_threshold_ |
| fixed threshold | sklearn.model_selection.FixedThresholdClassifier |
changes predict only |
| copy rare rows | imblearn.over_sampling.RandomOverSampler |
fast; exact duplicates |
| synthesize rare rows | imblearn.over_sampling.SMOTE (numeric only), SMOTENC (mixed), SMOTEN (all categorical) |
interpolates numeric columns between neighbors |
| drop common rows | imblearn.under_sampling.RandomUnderSampler |
fast; loses data |
| pipeline with samplers | imblearn.pipeline.Pipeline, make_pipeline |
resamples during fit only |
Break-even threshold for a calibrated model: flag when .
from imblearn.over_sampling import SMOTEfrom imblearn.pipeline import make_pipeline as make_imb_pipelinefrom sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import TunedThresholdClassifierCV
X_imb, y_imb = make_classification( n_samples=2000, weights=[0.9], flip_y=0.02, random_state=42)smote_model = make_imb_pipeline(SMOTE(random_state=42), LogisticRegression())print("SMOTE CV recall:", cross_val_score( smote_model, X_imb, y_imb, cv=cv, scoring="recall").mean().round(3))# never tune for recall alone: it picks a tiny threshold; use F1 or a costtuned = TunedThresholdClassifierCV(LogisticRegression(), scoring="f1", cv=cv)print("F1 threshold:", round(tuned.fit(X_imb, y_imb).best_threshold_, 3))SMOTE CV recall: 0.845F1 threshold: 0.261Nested cross-validation
Section titled “Nested cross-validation”inner = StratifiedKFold(n_splits=3, shuffle=True, random_state=42)outer = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)search = GridSearchCV(tree, {"max_depth": [2, 4, 8]}, cv=inner) # tunesnested = cross_val_score(search, X, y, cv=outer) # evaluates the procedurefinal = search.fit(X, y) # the model you shipprint(f"nested {nested.mean():.3f} +/- {nested.std():.3f}")print(f"best_score_ {final.best_score_:.3f}")nested 0.905 +/- 0.020best_score_ 0.900| Item | Value |
|---|---|
| Fits | outer folds × inner folds × candidates (+ refits) |
| Estimates | the procedure “search, then refit”, not one model |
| Final model | the search fitted once on all training rows |
| Report | nested mean ± std; then one test-set score |
Gotchas
Section titled “Gotchas”best_score_is the maximum of noisy scores and is biased upward. Report a nested CV estimate or a test score.KFoldandStratifiedKFoldignoregroups=and warn. Use a group splitter.KFold(shuffle=True)ortrain_test_splitwith its default shuffling on time series leaks the future.GroupKFold(shuffle=True, random_state=...)needs scikit-learn 1.6 or newer.- A pipeline parameter needs its step prefix:
"logisticregression__C", not"C". uniform(a, b)coversatoa + b, notatob.- A best value at the edge of the grid means the optimum may be outside it.
cv_results_of a halving search has one row per candidate per round.- Resampling before CV inflates recall and F1. Samplers belong inside
imblearn.pipeline.Pipeline; a scikit-learnPipelinerejects them. - Plain
SMOTEon categorical data, as codes or one-hot columns, invents fractional categories. UseSMOTENCon the raw columns,RandomOverSampleror class weights. - Class weights and resampling shift probabilities upward. Tune the threshold on the final pipeline, or calibrate.
- Optuna does not refit. Rebuild the estimator with
study.best_paramsand fit it. study.optimize(..., n_jobs>1)is not reproducible, even with a seeded sampler.- Error scorers are negated (
neg_mean_absolute_error). Flip the sign before you report. - A threshold chosen on the test set is tuning on the test set. Choose it with CV on the training data.