37. Model evaluation and tuning
A model that scores well on the rows it trained on can still fail on the next customer. This module teaches you to measure the score that matters, the score on new data, and to improve it without fooling yourself. You learn why models fail (too simple or too flexible), how to split data so that the evaluation looks like real use, how to search for good settings and how to report a final number that you can trust.
The examples use data/customers.csv (which subscribers churn), data/sales.csv (order lines with repeat customers) and data/web_traffic.csv (daily website visits). The data dictionary describes every column. One simulated dataset shows the bias–variance trade-off, because only a simulation tells you the true answer.
What you will learn
Section titled “What you will learn”- Explain bias, variance and irreducible error, and recognize underfitting and overfitting from training and validation scores.
- Read learning curves and validation curves to decide if you need more data, a simpler model or a more flexible one.
- Choose a cross-validation strategy that matches how the model will be used: k-fold, stratified, group or time-series splits.
- Tune hyperparameters with
GridSearchCV,RandomizedSearchCV(with SciPy distributions), successive halving and Optuna. - Handle imbalanced classes with class weights, threshold tuning and imbalanced-learn resampling inside a pipeline.
- Estimate the performance of a tuned model honestly with nested cross-validation.
Prerequisites
Section titled “Prerequisites”- 33. Feature engineering: data leakage and why every step learns from training rows only.
- 34. The scikit-learn workflow:
Pipeline,ColumnTransformer,cross_val_score,cross_validateandKFold. - 35. Regression: mean squared error (MSE), mean absolute error (MAE), polynomial regression, Ridge.
- 36. Classification: ROC-AUC, precision, recall, F1, decision trees and the decision threshold.
- 28. Visualization: Matplotlib figures and axes.
This module does not re-teach basic cross-validation. It starts where module 34 stops: which split to use, how to tune and how to trust the result.
Concepts
Section titled “Concepts”Generalization: the score that matters
Section titled “Generalization: the score that matters”A model is useful only if it works on data that it has never seen. This ability is generalization. The error on the training rows is the training error. The error on new rows from the same source is the generalization error. You cannot measure the generalization error directly, so you estimate it on rows that the model did not train on.
The difference between the training score and the validation score is the generalization gap. A small gap means that the model behaves on new data as it does on its training data. A large gap means that the model learned details of the training rows that do not repeat.
Data plays three roles in an honest evaluation:
| Role | Used for | Rule |
|---|---|---|
| Training data | fitting the model’s parameters | the model sees it |
| Validation data (or cross-validation folds) | comparing models and choosing hyperparameters | many decisions use it, so its score becomes optimistic |
| Test data | one final estimate | touch it once, at the end |
Every decision that looks at a score is a small piece of fitting. If you look at the test score 50 times and keep the best model, the test score is no longer an honest estimate. The rest of this module protects the estimate at each step.
Bias and variance
Section titled “Bias and variance”Picture four archers. One archer’s arrows land in a tight group, but far from the center: low spread, a systematic offset. Another archer’s arrows land all over the target, but their average is the center: no offset, a large spread. A model behaves the same way when you train it on different samples of data.
- Bias is the systematic error of a model: the difference between its average prediction (over many possible training sets) and the true value. A model with high bias is too simple for the pattern. A straight line fitted to a curve has high bias.
- Variance (of a model) is how much its predictions change when you train it on a different sample. A model with high variance is too sensitive to the particular training rows. A 13th-degree polynomial fitted to 15 points has high variance.
- Irreducible error is the noise in the target itself. No model can remove it: two customers with identical features can still make different choices.
For squared error, the expected error at a point splits exactly into these three parts:
Here is the true pattern, is the prediction of a model trained on one random training set, is the average over many training sets, and is the variance of the noise. A more flexible model lowers the bias and raises the variance. The bias–variance trade-off is the search for the flexibility where their sum is smallest. Example 1 measures each term on simulated data.
Underfitting and overfitting
Section titled “Underfitting and overfitting”Model complexity is how flexible a model is: how many different shapes it can fit. Each model family has its own complexity knobs:
| Model | More complex when… | Less complex when… |
|---|---|---|
| Polynomial regression | degree goes up |
degree goes down |
| Decision tree | max_depth goes up, min_samples_leaf goes down |
max_depth goes down, min_samples_leaf goes up |
| k-nearest neighbors | n_neighbors goes down |
n_neighbors goes up |
| Logistic regression, SVM | C goes up (less regularization) |
C goes down |
| Ridge, Lasso | alpha goes down |
alpha goes up |
| Gradient boosting | more trees, deeper trees, higher learning rate | fewer, shallower trees, lower learning rate |
A model underfits when it is too simple to capture the pattern. A model overfits when it is so flexible that it learns the noise of the training rows. The two scores tell you which problem you have:
| Diagnosis | Training score | Validation score | Gap | What to try |
|---|---|---|---|---|
| Underfitting (high bias) | low | low | small | more features, a more flexible model, less regularization |
| Good fit | high | close to training | small | stop tuning; check the test set once |
| Overfitting (high variance) | very high | much lower | large | more data, regularization, a simpler model, fewer features |
“Low” and “high” are relative to what the problem allows. A churn model with a validation ROC-AUC of 0.81 is not underfitting if the noise in the data caps every model near 0.83.
Learning curves
Section titled “Learning curves”A learning curve plots the training score and the validation score against the number of training rows. scikit-learn computes it with learning_curve or draws it with LearningCurveDisplay. For each training size, it cross-validates the model on a subset of that size.
The shape answers one question: will more data help?
- High variance: a large gap that shrinks as the training set grows. More data helps.
- High bias: both curves meet early and stay flat at a low score. More data does not help. Change the model or the features.
Validation curves
Section titled “Validation curves”A validation curve plots the training score and the validation score against the values of one hyperparameter. scikit-learn computes it with validation_curve or draws it with ValidationCurveDisplay. On the left side of the curve (low complexity), both scores are low: underfitting. On the right side (high complexity), the training score keeps rising while the validation score falls: overfitting. The best value sits near the peak of the validation curve.
A learning curve varies the data. A validation curve varies one setting. Use both before a wide search: they show which knob matters and in which range.
Cross-validation strategies
Section titled “Cross-validation strategies”Module 34 introduced k-fold cross-validation: split the rows into parts (folds), train on folds, score on the remaining fold, repeat times and average. The splitter decides which rows go together into a fold. The rule for choosing one:
The validation split must look like the real use of the model.
| Splitter | Use it when | Key arguments |
|---|---|---|
KFold |
regression, rows are independent | n_splits, shuffle=True, random_state |
StratifiedKFold |
classification, especially with rare classes | same; keeps the class shares in every fold |
GroupKFold |
several rows belong to one entity (customer, store, patient) and the model will meet new entities | n_splits, groups= in split, fit or cross_val_score |
StratifiedGroupKFold |
groups and rare classes together | as GroupKFold, plus stratification |
TimeSeriesSplit |
rows are ordered in time and the model predicts the future | n_splits, test_size, gap, max_train_size |
Stratified k-fold keeps the share of each class (for example 19% churners) equal in every fold. Without stratification, a fold of a rare class can get too few positive rows, and its score jumps around.
Group k-fold keeps all rows of one group in the same fold. A group is the entity that several rows share, such as one customer with 20 order lines. If one customer’s lines land in both the training and the validation fold, the model can recognize the customer instead of learning the pattern. This is group leakage. It inflates the score, and the model then fails on new customers. Example 3 measures the effect on data/sales.csv.
Time-series split (also called walk-forward validation) trains on the past and validates on the period that follows. Each split moves the validation window forward and adds the earlier window to the training data. Shuffled k-fold on time series lets the model train on Tuesday and Thursday to predict Wednesday, which it can never do in production. The gap argument skips rows between training and validation. Use it when a feature or the target spans several days, or when new data arrives with a delay.
flowchart TD
A["How will the model be used?"] --> B{"Predicts the future<br/>from the past?"}
B -->|yes| T["TimeSeriesSplit"]
B -->|no| C{"Many rows per entity,<br/>new entities later?"}
C -->|yes| D{"Rare class?"}
D -->|yes| SG["StratifiedGroupKFold"]
D -->|no| G["GroupKFold"]
C -->|no| E{"Classification?"}
E -->|yes| S["StratifiedKFold"]
E -->|no| K["KFold"]
Hyperparameter search
Section titled “Hyperparameter search”A hyperparameter is a setting that you choose before training, such as max_depth (module 03 defined the word). Hyperparameter tuning is the search for the settings that give the best cross-validated score. The search space is the set of values that the search may try. Four methods are common:
| Method | How it picks candidates | Strength | Weakness |
|---|---|---|---|
Grid search (GridSearchCV) |
every combination of listed values | simple, exhaustive, easy to read | cost multiplies with each hyperparameter |
Random search (RandomizedSearchCV) |
n_iter random draws from distributions |
fixed budget; tries many distinct values of each knob | can miss a narrow optimum |
Successive halving (HalvingGridSearchCV, HalvingRandomSearchCV) |
many candidates on few rows, then the best third on more rows, and so on | cheap way to try many candidates | small-resource scores can mislead |
| Bayesian optimization (Optuna) | learns from past trials which regions score well | finds good values in fewer trials | sequential; more code |
Random search often beats grid search for the same budget. Usually only one or two hyperparameters matter much. A 4 × 4 grid tries only 4 distinct values of each knob in 16 fits. Sixteen random draws try up to 16 distinct values of each knob. You describe the search space with SciPy distributions:
| Distribution | Draws | Use it for |
|---|---|---|
randint(2, 15) |
whole numbers 2 to 14 (the upper bound is excluded) | max_depth, min_samples_leaf |
uniform(0.1, 0.8) |
floats from 0.1 to 0.9 (loc, loc + scale) |
fractions such as max_features |
loguniform(1e-3, 1e2) |
floats spread evenly on a log scale | C, alpha, learning_rate |
a list such as ["gini", "entropy"] |
one item, uniformly | categorical choices |
Successive halving treats the number of training rows (or trees) as a budget, called the resource. It scores all candidates with a small resource, keeps the best 1 / factor of them, multiplies the resource by factor and repeats. It is still experimental in scikit-learn, so you enable it with an extra import.
Bayesian optimization builds a model of “score as a function of the hyperparameters” from the trials so far and picks the next candidate where a good score is likely. Optuna is a library for it. Its words: an objective is your function that takes a trial (one evaluation) and returns a score. A study runs many trials. A sampler proposes the values. The default sampler is TPE (Tree-structured Parzen Estimator): it splits past trials into good and bad ones and samples where good trials are dense. With TPESampler(seed=42), a study is reproducible.
In a pipeline, a hyperparameter name is the step name, two underscores and the parameter: "tree__max_depth". After the search, best_params_ holds the winner, best_score_ its mean cross-validated score, cv_results_ every candidate, and best_estimator_ the winning pipeline refitted on all the data that you passed to fit.
Imbalanced classes
Section titled “Imbalanced classes”A dataset has class imbalance when one class is much rarer than the other. About 19% of the customers in data/customers.csv churn. A model that predicts “no churn” for everybody is 81% accurate and useless. Imbalance is not a bug in the data. It is a reason to pick the metric, the threshold and the training procedure with care.
| Lever | What it does | Tool |
|---|---|---|
| A fitting metric | measures what you care about | recall, precision, F1, average precision (PR-AUC), a cost (module 36) |
| Class weights | makes each error on the rare class cost more during training | class_weight="balanced" or a dict |
| Threshold tuning | changes the probability above which you predict “churn” | TunedThresholdClassifierCV, FixedThresholdClassifier |
| Resampling | changes the training rows: copies or synthesizes rare rows, or drops common rows | imbalanced-learn: RandomOverSampler, SMOTE, RandomUnderSampler |
A class weight multiplies the loss of each row of a class. "balanced" gives each class the weight , where is the number of rows, the number of classes and the rows of class . For churn, a churner then weighs about 2.6 and a stayer about 0.62.
Threshold tuning keeps the model and moves the cut-off. A classifier outputs a probability. predict uses 0.5 by default, which is rarely the business optimum. When a retention offer costs 40 and a saved customer is worth 200, the offer pays off as soon as the churn probability is above 40 / 200 = 0.2. This cut-off is the break-even threshold: the cost of the action divided by the value of a caught positive. It holds when the probabilities are calibrated. TunedThresholdClassifierCV finds the threshold that maximizes a score with cross-validation.
imbalanced-learn (imported as imblearn) is a library of resampling methods that follows the scikit-learn API. Oversampling adds rows of the rare class. Undersampling removes rows of the common class. SMOTE (Synthetic Minority Over-sampling Technique) creates a new rare-class row on the line between a rare row and one of its rare-class neighbors :
SMOTE interpolates every column, so use it only on numeric features. For a mix of numeric and categorical columns, SMOTENC interpolates the numeric ones and copies the most common category among the neighbors. Resampling must happen only inside the training folds. If you resample before cross-validation, copies or near-copies of one row land in both the training and the validation fold, and the score is inflated. The imblearn.pipeline.Pipeline class runs a sampler during fit only and skips it during predict and score. The scikit-learn Pipeline does not accept samplers.
Nested cross-validation
Section titled “Nested cross-validation”best_score_ is the best of many noisy cross-validated scores. The maximum of noisy numbers is biased upward, like the winner of a lottery who thinks he is a good forecaster. This selection bias grows with the number of candidates and shrinks with the size of the data. So best_score_ is an optimistic estimate of how the tuned model will perform.
Nested cross-validation fixes this with two loops. The inner loop runs the whole search on the training part of each outer split. The outer loop scores the tuned model on its outer validation fold, which the search never saw. The mean of the outer scores estimates the performance of the whole procedure “search, then refit”.
flowchart TD
D["Training data"] --> O["Outer CV: split into 5 folds"]
O --> OT["Outer train: 4 folds"]
O --> OV["Outer validation: 1 fold"]
OT --> I["Inner CV: GridSearchCV<br/>tries every candidate"]
I --> B["Best candidate,<br/>refit on outer train"]
B --> S["Score on outer validation"]
OV --> S
S --> R["Repeat for 5 outer folds,<br/>average the 5 scores"]
In code, nested CV is one line: pass a search object to cross_val_score. It costs fits. The final model is the search fitted once on all training data. Nested CV evaluates the procedure that produces it.
Worked examples
Section titled “Worked examples”Example 1 — Simulate bias and variance with polynomial degree
Section titled “Example 1 — Simulate bias and variance with polynomial degree”Goal: Fit polynomials of growing degree to noisy data from a known curve, and measure training error, test error, bias and variance. A simulation is the only setting in which you know the true curve, so you can compute each term exactly.
Step 1 — Create the hidden curve and noisy samples
Section titled “Step 1 — Create the hidden curve and noisy samples”import matplotlib.pyplot as pltimport numpy as npimport pandas as pdfrom sklearn.linear_model import LinearRegressionfrom sklearn.metrics import mean_squared_errorfrom sklearn.pipeline import make_pipelinefrom sklearn.preprocessing import MinMaxScaler, PolynomialFeatures
pd.set_option("display.width", 100)pd.set_option("display.max_columns", 12)pd.set_option("display.precision", 3)
def true_curve(x): """The pattern that a perfect model would learn.""" return np.sin(2 * x) + 0.5 * x
NOISE_SD = 0.3rng = np.random.default_rng(42)X_sim = np.linspace(0, 3, 15).reshape(-1, 1)y_sim = true_curve(X_sim.ravel()) + rng.normal(0, NOISE_SD, 15)X_new = rng.uniform(0, 3, 500).reshape(-1, 1)y_new = true_curve(X_new.ravel()) + rng.normal(0, NOISE_SD, 500)print(X_sim.shape, X_new.shape)print(y_sim[:5].round(3))(15, 1) (500, 1)[0.091 0.211 1.195 1.563 0.833]The training set has 15 points on a regular grid. The 500 new points come from the same curve with the same noise, so they play the role of future data. The noise standard deviation is 0.3, so the noise variance, the irreducible error, is . No model can get an expected test MSE below 0.09.
Step 2 — Fit three degrees and look at the fits
Section titled “Step 2 — Fit three degrees and look at the fits”def poly_model(degree): return make_pipeline( MinMaxScaler(feature_range=(-1, 1)), PolynomialFeatures(degree), LinearRegression(), )
grid = np.linspace(0, 3, 300).reshape(-1, 1)fig, axes = plt.subplots(1, 3, figsize=(11, 3.4), sharey=True)for ax, degree in zip(axes, [1, 4, 13]): model = poly_model(degree).fit(X_sim, y_sim) ax.plot(grid, true_curve(grid.ravel()), color="0.6", lw=2, label="true curve") ax.plot(grid, model.predict(grid), color="#2a78d6", lw=2, label="model") ax.scatter(X_sim, y_sim, color="#eb6834", s=25, zorder=3, label="training data") ax.set_title(f"degree {degree}") ax.set_ylim(-1.5, 3) ax.set_xlabel("x")axes[0].set_ylabel("y")axes[0].legend(loc="upper left", frameon=False)fig.tight_layout()plt.show()
MinMaxScaler(feature_range=(-1, 1)) maps to the range −1 to 1 before the powers are computed. Without it, million and the powers differ so much in size that the least-squares solution becomes numerically unstable. The straight line misses the wave: high bias. The degree-13 curve chases each noisy point: high variance.
Step 3 — Sweep the degree and record both errors
Section titled “Step 3 — Sweep the degree and record both errors”rows = []for degree in range(1, 14): model = poly_model(degree).fit(X_sim, y_sim) rows.append( { "degree": degree, "train_mse": mean_squared_error(y_sim, model.predict(X_sim)), "test_mse": mean_squared_error(y_new, model.predict(X_new)), } )errors = pd.DataFrame(rows)print(errors.to_string(index=False)) degree train_mse test_mse 1 0.214 0.308 2 0.214 0.307 3 0.053 0.120 4 0.052 0.123 5 0.050 0.121 6 0.050 0.121 7 0.044 0.129 8 0.033 0.140 9 0.016 0.194 10 0.010 0.198 11 0.007 0.171 12 0.006 0.279 13 0.003 1.583The training error falls with every degree, because a more flexible model can always fit the same points at least as well. The test error falls until degree 3–6 and then rises. The training error alone always recommends the most complex model. Only data the model did not train on reveals overfitting.
Step 4 — Plot the error curves
Section titled “Step 4 — Plot the error curves”fig, ax = plt.subplots(figsize=(7, 4))ax.plot(errors["degree"], errors["train_mse"], "o-", color="#2a78d6", label="training")ax.plot(errors["degree"], errors["test_mse"], "o-", color="#eb6834", label="test")ax.axhline(NOISE_SD**2, color="0.5", ls="--", lw=1)ax.text(13, 0.08, "noise variance 0.09", color="0.3", ha="right", va="top")ax.set_yscale("log")ax.set_xlabel("polynomial degree (model complexity)")ax.set_ylabel("mean squared error (log scale)")ax.legend(frameon=False)fig.tight_layout()plt.show()
The left side of the U is underfitting, the right side is overfitting. The training error is below the noise line from degree 3 on. Even a good model fits some of the noise of its own training points, which is why a training score is always optimistic. At degree 13 the training error is almost zero: the model has memorized the noise.
Step 5 — Decompose the error over 200 training sets
Section titled “Step 5 — Decompose the error over 200 training sets”x_eval = np.linspace(0, 3, 200).reshape(-1, 1)f_eval = true_curve(x_eval.ravel())rows = []for degree in [1, 3, 5, 9, 13]: preds = [] for _ in range(200): y_draw = true_curve(X_sim.ravel()) + rng.normal(0, NOISE_SD, 15) preds.append(poly_model(degree).fit(X_sim, y_draw).predict(x_eval)) preds = np.array(preds) # shape (200 training sets, 200 points) bias_sq = ((preds.mean(axis=0) - f_eval) ** 2).mean() variance = preds.var(axis=0).mean() rows.append( { "degree": degree, "bias^2": bias_sq, "variance": variance, "noise": NOISE_SD**2, "expected_mse": bias_sq + variance + NOISE_SD**2, } )print(pd.DataFrame(rows).to_string(index=False, float_format="{:.4f}".format)) degree bias^2 variance noise expected_mse 1 0.1836 0.0116 0.0900 0.2851 3 0.0042 0.0206 0.0900 0.1147 5 0.0002 0.0307 0.0900 0.1209 9 0.0009 0.0637 0.0900 0.1546 13 0.0008 3.6415 0.0900 3.7323Each of the 200 repetitions draws new noise and trains a new model. The mean of the 200 predictions at a point is . Its distance from the true curve is the bias. The spread of the 200 predictions is the variance. The bias collapses between degree 1 and 3. After that, the variance grows quickly. The expected MSE is smallest where the sum of the two is smallest, near degree 3–5, which matches the test error of Step 3.
Common mistakes:
- Choosing the model with the lowest training error. It always picks the most complex model.
- Computing high-degree polynomial features on unscaled inputs. The columns differ by orders of magnitude and the fit becomes unstable.
- Expecting the test error to reach zero. It cannot go below the noise variance.
Example 2 — Diagnose churn models with learning and validation curves
Section titled “Example 2 — Diagnose churn models with learning and validation curves”Goal: A retention team asks if more history will improve its churn model. Use learning curves to compare a logistic regression with an unpruned decision tree, and a validation curve to pick the tree depth.
Step 1 — Load the customers and build the preprocessing
Section titled “Step 1 — Load the customers and build the preprocessing”from sklearn.compose import make_column_selector, make_column_transformerfrom sklearn.impute import SimpleImputerfrom sklearn.model_selection import StratifiedKFold, train_test_splitfrom sklearn.preprocessing import OneHotEncoder, StandardScaler
customers = pd.read_csv("data/customers.csv")X = customers.drop(columns=["customer_id", "signup_date", "churned"])y = customers["churned"]X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.25, stratify=y, random_state=42)preprocess = make_column_transformer( ( OneHotEncoder(handle_unknown="ignore", sparse_output=False), make_column_selector(dtype_include="str"), ), ( make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), make_column_selector(dtype_include="number"), ),)cv3 = StratifiedKFold(n_splits=3, shuffle=True, random_state=42)print(X_train.shape, X_test.shape)print(f"churn rate: train {y_train.mean():.3f}, test {y_test.mean():.3f}")(3750, 12) (1250, 12)churn rate: train 0.193, test 0.193The preprocessing one-hot encodes the four text columns and imputes and scales the numeric ones, as in module 34. stratify=y keeps the churn rate equal in both parts. Every curve in this example uses only the training part. The test part waits for the end.
Step 2 — Draw learning curves for two models
Section titled “Step 2 — Draw learning curves for two models”from sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import LearningCurveDisplayfrom sklearn.tree import DecisionTreeClassifier
models = { "logistic regression": make_pipeline(preprocess, LogisticRegression(max_iter=1000)), "unpruned tree": make_pipeline(preprocess, DecisionTreeClassifier(random_state=42)),}fig, axes = plt.subplots(1, 2, figsize=(11, 4), sharey=True)for ax, (name, model) in zip(axes, models.items()): display = LearningCurveDisplay.from_estimator( model, X_train, y_train, train_sizes=np.linspace(0.1, 1.0, 5), cv=cv3, scoring="roc_auc", score_type="both", n_jobs=1, ax=ax, ) ax.set_title(name) ax.set_ylabel("") ax.legend(display.lines_, ["training", "validation"], frameon=False) print(name) print(" sizes:", display.train_sizes) print(" train:", display.train_scores.mean(axis=1).round(3)) print(" valid:", display.test_scores.mean(axis=1).round(3))axes[0].set_ylabel("ROC-AUC")fig.tight_layout()plt.show()logistic regression sizes: [ 250 812 1375 1937 2500] train: [0.84 0.839 0.823 0.823 0.82 ] valid: [0.78 0.809 0.811 0.812 0.812]unpruned tree sizes: [ 250 812 1375 1937 2500] train: [1. 1. 1. 1. 1.] valid: [0.614 0.632 0.642 0.644 0.639]
LearningCurveDisplay.from_estimator trains each model on 10%, 32%, 55%, 77% and 100% of each training fold and scores it on the validation fold. score_type="both" draws both curves. The display labels the validation curve “Test” by default, so the code sets clearer legend labels. The display object keeps the numbers in train_sizes, train_scores and test_scores (one row per size, one column per fold).
The two models fail in opposite ways. The logistic regression curves come within about 0.01 of each other near 0.81 from roughly 1,400 rows on. More rows will not help it: the next gain must come from better features or a more flexible model. The tree scores a perfect 1.0 on its training rows and about 0.64 on validation. It memorizes. More rows barely move its validation score; it needs limits on its growth.
Step 3 — Choose the tree depth with a validation curve
Section titled “Step 3 — Choose the tree depth with a validation curve”from sklearn.model_selection import ValidationCurveDisplay
tree = make_pipeline(preprocess, DecisionTreeClassifier(random_state=42))depths = np.arange(1, 13)display = ValidationCurveDisplay.from_estimator( tree, X_train, y_train, param_name="decisiontreeclassifier__max_depth", param_range=depths, cv=cv3, scoring="roc_auc", score_type="both", n_jobs=1,)display.ax_.set_xlabel("max_depth")display.ax_.set_ylabel("ROC-AUC")display.ax_.legend(display.lines_, ["training", "validation"], frameon=False)curve = pd.DataFrame( { "max_depth": depths, "train": display.train_scores.mean(axis=1), "valid": display.test_scores.mean(axis=1), })print(curve.round(3).to_string(index=False))print("best depth:", curve.loc[curve["valid"].idxmax(), "max_depth"])plt.show() max_depth train valid 1 0.676 0.676 2 0.746 0.734 3 0.789 0.773 4 0.819 0.785 5 0.847 0.784 6 0.871 0.786 7 0.898 0.755 8 0.925 0.714 9 0.944 0.678 10 0.961 0.641 11 0.976 0.607 12 0.984 0.606best depth: 6
make_pipeline names each step after its class in lowercase, so the depth is decisiontreeclassifier__max_depth. At depth 1 and 2, both scores are low and close: underfitting. From depth 7 on, the training score keeps climbing while the validation score drops: overfitting. Depths 4 to 6 are nearly tied. When scores tie, prefer the simpler model, here depth 4 or 5. It is cheaper, easier to explain and less likely to overfit.
Step 4 — Check the diagnosis once on the test set
Section titled “Step 4 — Check the diagnosis once on the test set”from sklearn.metrics import roc_auc_score
for depth in [None, 5]: model = make_pipeline( preprocess, DecisionTreeClassifier(max_depth=depth, random_state=42) ).fit(X_train, y_train) auc = roc_auc_score(y_test, model.predict_proba(X_test)[:, 1]) print(f"max_depth={depth}: test ROC-AUC {auc:.3f}")max_depth=None: test ROC-AUC 0.679max_depth=5: test ROC-AUC 0.791The test scores agree with the validation curve. The depth limit raises the ROC-AUC from about 0.68 to about 0.79. The curves predicted this result without any look at the test set.
Common mistakes:
- Reading only the validation score. The gap to the training score tells you whether the model underfits or overfits.
- Calling
learning_curveon all rows, test set included. The curves are a model-selection tool and belong to the training data. - Using a parameter name without the step prefix.
max_depthalone raisesValueError: Invalid parameter 'max_depth' for estimator Pipeline(...).
Example 3 — Catch group leakage in order lines
Section titled “Example 3 — Catch group leakage in order lines”Goal: An analyst builds a churn model on order lines: each row of data/sales.csv is joined with the customer’s profile, and the label is whether that customer churned. Show that shuffled k-fold inflates the score because the same customers appear in training and validation, and measure the honest score with GroupKFold.
Step 1 — Join the order lines with the customer profiles
Section titled “Step 1 — Join the order lines with the customer profiles”sales = pd.read_csv( "data/sales.csv", usecols=["customer_id", "unit_price", "quantity", "discount"])lines = sales.merge(customers, on="customer_id", how="left")features = [ "age", "tenure_months", "monthly_charges", "support_tickets", "logins_last_30d", "unit_price", "quantity", "discount",]X_lines = lines[features]y_lines = lines["churned"]groups = lines["customer_id"]lines_per_customer = groups.value_counts()print(X_lines.shape, "customers:", groups.nunique())print("lines per customer: median", lines_per_customer.median(), "max", lines_per_customer.max())print(f"churn rate per line: {y_lines.mean():.3f}")(20228, 8) customers: 3254lines per customer: median 4.0 max 70churn rate per line: 0.12720,228 lines come from only 3,254 customers. The median customer has 4 lines, and one customer has 70. Every line of a customer carries the same profile values and the same label.
Step 2 — Score a random forest with shuffled k-fold
Section titled “Step 2 — Score a random forest with shuffled k-fold”from sklearn.ensemble import RandomForestClassifierfrom sklearn.model_selection import GroupKFold, KFold, cross_val_score
forest = RandomForestClassifier(n_estimators=50, random_state=42, n_jobs=1)kfold = KFold(n_splits=3, shuffle=True, random_state=42)naive = cross_val_score(forest, X_lines, y_lines, cv=kfold, scoring="roc_auc")print("KFold ROC-AUC:", naive.round(3), "mean", naive.mean().round(3))KFold ROC-AUC: [0.988 0.99 0.994] mean 0.991A ROC-AUC of 0.99 for churn is too good to be true. The customer-level models of Example 2 reach about 0.81 with more information per customer. When a score looks too good, suspect leakage first.
Step 3 — Count the customers shared by both sides of a split
Section titled “Step 3 — Count the customers shared by both sides of a split”train_idx, valid_idx = next(kfold.split(X_lines))valid_customers = groups.iloc[valid_idx].unique()shared = np.isin(valid_customers, groups.iloc[train_idx].unique())print(f"validation customers also in training: {shared.mean():.1%}")validation customers also in training: 88.1%kfold.split yields pairs of index arrays. next takes the first split. 88% of the customers in the validation fold also have lines in the training folds. The forest recognizes a customer by the exact combination of age, tenure and monthly charges, and repeats the label it saw in training. It does not learn why customers churn.
Step 4 — Keep each customer in one fold with GroupKFold
Section titled “Step 4 — Keep each customer in one fold with GroupKFold”group_kfold = GroupKFold(n_splits=3, shuffle=True, random_state=42)honest = cross_val_score( forest, X_lines, y_lines, cv=group_kfold, groups=groups, scoring="roc_auc")print("GroupKFold ROC-AUC:", honest.round(3), "mean", honest.mean().round(3))train_idx, valid_idx = next(group_kfold.split(X_lines, y_lines, groups))shared = np.isin(groups.iloc[valid_idx].unique(), groups.iloc[train_idx].unique())print(f"validation customers also in training: {shared.mean():.1%}")GroupKFold ROC-AUC: [0.743 0.71 0.743] mean 0.732validation customers also in training: 0.0%groups=groups tells the splitter which rows belong together. Now no customer is on both sides, and the score drops from 0.99 to about 0.73. That is what the model will deliver for new customers. GroupKFold accepts shuffle=True from scikit-learn 1.6; older versions assign groups to folds in a fixed order.
Step 5 — Keep the churn share stable with StratifiedGroupKFold
Section titled “Step 5 — Keep the churn share stable with StratifiedGroupKFold”from sklearn.model_selection import StratifiedGroupKFold
strat_group = StratifiedGroupKFold(n_splits=3, shuffle=True, random_state=42)for fold, (_, valid_idx) in enumerate(strat_group.split(X_lines, y_lines, groups)): rate = y_lines.iloc[valid_idx].mean() print(f"fold {fold}: {len(valid_idx)} lines, churn rate {rate:.3f}")scores = cross_val_score( forest, X_lines, y_lines, cv=strat_group, groups=groups, scoring="roc_auc")print("StratifiedGroupKFold ROC-AUC mean:", scores.mean().round(3))fold 0: 6743 lines, churn rate 0.127fold 1: 6743 lines, churn rate 0.127fold 2: 6742 lines, churn rate 0.127StratifiedGroupKFold ROC-AUC mean: 0.74StratifiedGroupKFold keeps whole customers together and still balances the churn rate across folds. Use it when the class is rare and the groups differ in size, so a plain GroupKFold could put most churners into one fold.
Common mistakes:
- Passing
groups=to aKFoldorStratifiedKFold. They ignore it and warnThe groups parameter is ignored by KFold. Use a group splitter. - Grouping by the wrong key. Group by the entity that will be new in production: the customer for a churn model, the store for a model that will run in new stores.
- Shuffling the rows and then using a row-level split (
KFold,train_test_split) on grouped data. Shuffling does not keep groups together; only a group splitter does.
Example 4 — Validate a traffic forecast with TimeSeriesSplit
Section titled “Example 4 — Validate a traffic forecast with TimeSeriesSplit”Goal: The marketing team wants a model that predicts tomorrow’s website visits from recent visits and the planned marketing spend. Compare shuffled k-fold with walk-forward validation on data/web_traffic.csv, and draw the folds.
Step 1 — Build lag features
Section titled “Step 1 — Build lag features”traffic = pd.read_csv("data/web_traffic.csv", parse_dates=["date"])traffic["visits"] = traffic["visits"].interpolate()traffic = traffic.assign( lag_1=traffic["visits"].shift(1), lag_7=traffic["visits"].shift(7), day_of_week=traffic["date"].dt.day_of_week,).dropna()X_traffic = traffic[["lag_1", "lag_7", "day_of_week", "marketing_spend"]]y_traffic = traffic["visits"]print(traffic[["date", "visits", "lag_1", "lag_7", "day_of_week"]].head(3))print(X_traffic.shape) date visits lag_1 lag_7 day_of_week7 2022-01-08 2912.0 3155.0 2718.0 58 2022-01-09 3281.0 2912.0 3104.0 69 2022-01-10 4126.0 3281.0 3615.0 0(1089, 4)A lag feature is a past value of the target: lag_1 is yesterday’s visits and lag_7 the visits one week ago. interpolate() fills the 5 tracking outages. dropna() removes the first 7 days, which have no lag_7. The rows stay in date order. Module 40 covers lag features and forecasting in depth.
Step 2 — Draw the walk-forward folds
Section titled “Step 2 — Draw the walk-forward folds”from sklearn.model_selection import TimeSeriesSplit
tscv = TimeSeriesSplit(n_splits=5)dates = traffic["date"].reset_index(drop=True)fig, ax = plt.subplots(figsize=(10, 3.2))for fold, (train_idx, valid_idx) in enumerate(tscv.split(X_traffic)): first, last_train = dates[train_idx[0]], dates[train_idx[-1]] ax.barh(fold, last_train - first, left=first, color="#2a78d6", height=0.6) first, last = dates[valid_idx[0]], dates[valid_idx[-1]] ax.barh(fold, last - first, left=first, color="#eb6834", height=0.6) print(f"split {fold}: train {len(train_idx):>4} days to {last_train.date()}," f" validate {len(valid_idx)} days to {last.date()}")ax.set_yticks(range(5), [f"split {i}" for i in range(5)])ax.invert_yaxis()ax.legend(["train", "validate"], loc="upper right", frameon=False)ax.set_xlabel("date")fig.tight_layout()plt.show()split 0: train 184 days to 2022-07-10, validate 181 days to 2023-01-07split 1: train 365 days to 2023-01-07, validate 181 days to 2023-07-07split 2: train 546 days to 2023-07-07, validate 181 days to 2024-01-04split 3: train 727 days to 2024-01-04, validate 181 days to 2024-07-03split 4: train 908 days to 2024-07-03, validate 181 days to 2024-12-31
Each split trains on all days before its validation window. The validation windows do not overlap, and together they cover the last five-sixths of the period. By default, the validation size is n_samples // (n_splits + 1) = 181 days.
Step 3 — Compare shuffled k-fold with walk-forward validation
Section titled “Step 3 — Compare shuffled k-fold with walk-forward validation”from sklearn.ensemble import RandomForestRegressor
forest_reg = RandomForestRegressor( n_estimators=100, min_samples_leaf=3, random_state=42, n_jobs=1)for name, cv in [("shuffled KFold", KFold(5, shuffle=True, random_state=42)), ("TimeSeriesSplit", tscv)]: mae = -cross_val_score( forest_reg, X_traffic, y_traffic, cv=cv, scoring="neg_mean_absolute_error" ) print(f"{name:<16} MAE per fold {mae.round(0)} mean {mae.mean():.0f}")shuffled KFold MAE per fold [279. 268. 228. 232. 366.] mean 274TimeSeriesSplit MAE per fold [302. 291. 276. 372. 705.] mean 389scikit-learn scorers follow “greater is better”, so error metrics come negated (neg_mean_absolute_error) and the minus sign turns them back into an error. Shuffled k-fold reports an MAE about 30% lower than walk-forward validation. With shuffling, the model trains on the days around each validation day and interpolates. In production it must extrapolate into a future with more traffic than it has ever seen. A random forest cannot predict values above its training range, so the last split, with the record traffic of late 2024, has the largest error.
Step 4 — Fix the validation window and leave a gap
Section titled “Step 4 — Fix the validation window and leave a gap”tscv_gap = TimeSeriesSplit(n_splits=4, test_size=90, gap=7)for fold, (train_idx, valid_idx) in enumerate(tscv_gap.split(X_traffic)): print(f"split {fold}: train ends {dates[train_idx[-1]].date()}," f" validation {dates[valid_idx[0]].date()} to {dates[valid_idx[-1]].date()}")mae = -cross_val_score( forest_reg, X_traffic, y_traffic, cv=tscv_gap, scoring="neg_mean_absolute_error")print("MAE per quarter:", mae.round(0))split 0: train ends 2023-12-30, validation 2024-01-07 to 2024-04-05split 1: train ends 2024-03-29, validation 2024-04-06 to 2024-07-04split 2: train ends 2024-06-27, validation 2024-07-05 to 2024-10-02split 3: train ends 2024-09-25, validation 2024-10-03 to 2024-12-31MAE per quarter: [255. 471. 413. 796.]test_size=90 makes each validation window one quarter. Each window still scores one-day-ahead forecasts, because lag_1 holds the real visits of the day before. The MAE per split is the average one-day-ahead error over a quarter, which shows how the error changes through the year. gap=7 drops the 7 days between training and validation, so each validation window starts 8 days after the last training day. A gap keeps training rows whose targets or rolling features overlap the validation period out of training. It does not delay the features of the validation rows. To simulate a model that forecasts days ahead, build the lags with shift(d) or more, and add a gap of at least .
Common mistakes:
- Shuffling time-ordered rows, in
KFold(shuffle=True)or intrain_test_split. UseTimeSeriesSplit, ortrain_test_split(..., shuffle=False)for one split. - Building rolling or lag features after a shuffle. Compute them on the sorted series first.
- Reading only the mean of the folds. The last fold is the closest to production. A rising error across splits is a warning that the pattern drifts.
Example 5 — Tune a churn tree with grid, random and halving search
Section titled “Example 5 — Tune a churn tree with grid, random and halving search”Goal: Tune the decision tree of Example 2 with three search methods, compare their budgets and best scores, and confirm the winners once on the test set.
Step 1 — Run a grid search
Section titled “Step 1 — Run a grid search”from sklearn.model_selection import GridSearchCVfrom sklearn.pipeline import Pipeline
tree_pipe = Pipeline( [("prep", preprocess), ("tree", DecisionTreeClassifier(random_state=42))])param_grid = { "tree__max_depth": [3, 5, 7, 10], "tree__min_samples_leaf": [1, 20, 50, 100],}grid_search = GridSearchCV(tree_pipe, param_grid, cv=cv3, scoring="roc_auc", n_jobs=1)grid_search.fit(X_train, y_train)print("best:", grid_search.best_params_, f"CV ROC-AUC {grid_search.best_score_:.3f}")results = pd.DataFrame(grid_search.cv_results_)print(results.pivot_table( index="param_tree__max_depth", columns="param_tree__min_samples_leaf", values="mean_test_score",).round(3))best: {'tree__max_depth': 7, 'tree__min_samples_leaf': 50} CV ROC-AUC 0.803param_tree__min_samples_leaf 1 20 50 100param_tree__max_depth3 0.773 0.770 0.771 0.7685 0.784 0.784 0.795 0.7877 0.755 0.783 0.803 0.78810 0.641 0.761 0.794 0.787The grid has 4 × 4 = 16 candidates. With 3 folds, the search makes 48 fits, plus one refit of the winner on all training rows. cv_results_ is a dictionary with one entry per candidate. A pivot table of the mean scores shows the landscape: deep trees need large leaves, and shallow trees barely care about the leaf size.
Step 2 — Run a random search with SciPy distributions
Section titled “Step 2 — Run a random search with SciPy distributions”from scipy.stats import loguniform, randintfrom sklearn.model_selection import RandomizedSearchCV
param_dist = { "tree__max_depth": randint(2, 15), "tree__min_samples_leaf": randint(1, 200), "tree__max_features": [None, "sqrt", 0.5], "tree__ccp_alpha": loguniform(1e-5, 1e-2),}random_search = RandomizedSearchCV( tree_pipe, param_dist, n_iter=20, cv=cv3, scoring="roc_auc", random_state=42, n_jobs=1,)random_search.fit(X_train, y_train)for name, value in random_search.best_params_.items(): print(f"{name}: {value:.5f}" if isinstance(value, float) else f"{name}: {value}")print(f"CV ROC-AUC {random_search.best_score_:.3f}")tree__ccp_alpha: 0.00008tree__max_depth: 7tree__max_features: Nonetree__min_samples_leaf: 89CV ROC-AUC 0.795randint(2, 15) draws whole numbers from 2 to 14. loguniform(1e-5, 1e-2) spreads the draws evenly over the orders of magnitude, so 0.00001–0.0001 gets as many draws as 0.001–0.01. ccp_alpha is the cost-complexity pruning strength: a larger value removes more branches. A list is sampled uniformly. For 60 fits, the 20 draws try many more distinct depths and leaf sizes than the 4 of each in the grid. random_state=42 makes the draws repeatable.
Step 3 — Try more candidates with successive halving
Section titled “Step 3 — Try more candidates with successive halving”from sklearn.experimental import enable_halving_search_cv # noqa: F401from sklearn.model_selection import HalvingRandomSearchCV
halving = HalvingRandomSearchCV( tree_pipe, param_dist, n_candidates=27, factor=3, min_resources=300, cv=cv3, scoring="roc_auc", random_state=42, n_jobs=1,)halving.fit(X_train, y_train)print("candidates per round:", halving.n_candidates_)print("rows per round: ", halving.n_resources_)print(f"best CV ROC-AUC {halving.best_score_:.3f}")candidates per round: [27, 9, 3]rows per round: [300, 900, 2700]best CV ROC-AUC 0.784The first round scores 27 candidates on 300 rows each. The best third (9) go on with 900 rows, and the best 3 with 2,700 rows. The enable_halving_search_cv import switches on the experimental classes. # noqa: F401 tells the linter that the unused-looking import is intentional. The best score comes from the last round, so it is not directly comparable with a search on all rows.
Step 4 — Look at the test scores of all three (a demo only)
Section titled “Step 4 — Look at the test scores of all three (a demo only)”searches = {"grid": grid_search, "random": random_search, "halving": halving}for name, search in searches.items(): test_auc = roc_auc_score(y_test, search.predict_proba(X_test)[:, 1]) n_candidates = len(search.cv_results_["params"]) print(f"{name:<8} candidates {n_candidates:>3} CV {search.best_score_:.3f}" f" test {test_auc:.3f}")grid candidates 16 CV 0.803 test 0.800random candidates 20 CV 0.795 test 0.792halving candidates 39 CV 0.784 test 0.792A fitted search behaves like its best estimator: predict_proba uses best_estimator_, refitted on all training rows. The three methods land within about 0.01 of each other on the test set. Their CV scores already showed the same picture: for a tree with two important knobs, a small grid is enough. Random search and halving pay off when there are more hyperparameters or fits are slow. For halving, cv_results_ counts every round, so its 39 rows include the repeated candidates.
Common mistakes:
- Writing
uniform(0.1, 0.9)for the range 0.1 to 0.9. SciPy’s arguments arelocandscale, so this covers 0.1 to 1.0. Writeuniform(0.1, 0.8). - Sampling
Cor a learning rate withuniform. Most draws land in the top order of magnitude. Useloguniform. - Trusting a best value at the edge of the grid. If the best
max_depthis the largest value you tried, widen the range and search again.
Example 6 — Search smarter with Optuna
Section titled “Example 6 — Search smarter with Optuna”Goal: Tune the same tree with Optuna’s TPE sampler, inspect the trials and confirm the result on the test set.
Step 1 — Write the objective function
Section titled “Step 1 — Write the objective function”import optunafrom sklearn.base import clone
optuna.logging.set_verbosity(optuna.logging.WARNING)
def objective(trial): params = { "tree__max_depth": trial.suggest_int("max_depth", 2, 15), "tree__min_samples_leaf": trial.suggest_int( "min_samples_leaf", 1, 200, log=True ), "tree__ccp_alpha": trial.suggest_float("ccp_alpha", 1e-5, 1e-2, log=True), "tree__criterion": trial.suggest_categorical("criterion", ["gini", "entropy"]), } model = clone(tree_pipe).set_params(**params) scores = cross_val_score(model, X_train, y_train, cv=cv3, scoring="roc_auc") return scores.mean()The objective receives a trial and asks it for values. suggest_int and suggest_float define ranges, log=True samples on a log scale, and suggest_categorical picks from a list. The search space lives in the code, so it can depend on earlier choices (for example, ask for a kernel width only if the kernel is "rbf"). clone creates a fresh, unfitted copy of the pipeline for each trial. set_verbosity(WARNING) silences the log line that Optuna prints for every trial.
Step 2 — Run a reproducible study
Section titled “Step 2 — Run a reproducible study”sampler = optuna.samplers.TPESampler(seed=42)study = optuna.create_study(direction="maximize", sampler=sampler)study.optimize(objective, n_trials=30)print("best trial:", study.best_trial.number)print("best params:", {k: round(v, 5) if isinstance(v, float) else v for k, v in study.best_params.items()})print(f"best CV ROC-AUC: {study.best_value:.3f}")best trial: 24best params: {'max_depth': 13, 'min_samples_leaf': 74, 'ccp_alpha': 0.00072, 'criterion': 'gini'}best CV ROC-AUC: 0.798direction="maximize" matches a score (use "minimize" for an error). The first trials of TPE are random (10 by default). After them, TPE proposes values near the good trials. TPESampler(seed=42) fixes its random choices, so the study gives the same trials on every run, as long as the trials run one at a time.
Step 3 — Inspect the trials
Section titled “Step 3 — Inspect the trials”trials = study.trials_dataframe()top = trials.sort_values("value", ascending=False).head(5)print(top[["number", "value", "params_max_depth", "params_min_samples_leaf", "params_criterion"]].to_string(index=False))first_half = trials["value"].iloc[:15].mean()second_half = trials["value"].iloc[15:].mean()print(f"mean score: trials 0-14 {first_half:.3f}, trials 15-29 {second_half:.3f}") number value params_max_depth params_min_samples_leaf params_criterion 24 0.798 13 74 gini 22 0.795 12 50 gini 15 0.794 13 92 gini 16 0.794 15 51 gini 12 0.793 14 82 ginimean score: trials 0-14 0.742, trials 15-29 0.783trials_dataframe() returns one row per trial with its score (value) and its parameters (params_...). The later trials score higher on average than the early, mostly random ones: TPE spends its budget where the good trials are. The best trials agree on large leaves (50 to 92 rows) and the Gini criterion, and they allow deep trees. With large leaves and some pruning, the depth limit matters less. The grid showed the same pattern: depth 10 with leaves of 50 rows scored almost as well as depth 7.
Step 4 — Refit the best parameters and test once
Section titled “Step 4 — Refit the best parameters and test once”best_params = {f"tree__{name}": value for name, value in study.best_params.items()}optuna_model = clone(tree_pipe).set_params(**best_params).fit(X_train, y_train)test_auc = roc_auc_score(y_test, optuna_model.predict_proba(X_test)[:, 1])print(f"Optuna tree: test ROC-AUC {test_auc:.3f}")Optuna tree: test ROC-AUC 0.793Optuna does not refit for you. You add the tree__ prefix back to the parameter names, set them on a fresh pipeline and fit on all training rows. The test score is in the same range as the other searches. On this small problem, every reasonable search finds the same plateau. The difference between the methods grows with the number of hyperparameters and the cost of one fit.
Common mistakes:
- Leaving Optuna’s logging on. Each trial prints a line to stderr, which floods notebooks and logs.
- Running
study.optimize(..., n_jobs=4)and expecting reproducible results. Parallel trials finish in a different order on each run. - Reusing the same fitted model object in every trial. Clone or build a new estimator inside the objective.
Example 7 — Handle class imbalance in a churn model
Section titled “Example 7 — Handle class imbalance in a churn model”Goal: The retention team can call customers at risk. A call with an offer costs 40, and a churner who is caught is worth 200. Compare the default model with class weights, a tuned threshold and resampling on out-of-fold predictions, show the leak that resampling before cross-validation causes, and test the chosen model once.
Step 1 — Score the default model with out-of-fold predictions
Section titled “Step 1 — Score the default model with out-of-fold predictions”from sklearn.metrics import confusion_matrix, f1_score, precision_score, recall_scorefrom sklearn.model_selection import cross_val_predict
def campaign_profit(y_true, y_pred): """Value of the calls: +160 per caught churner, -40 per wasted call.""" tn, fp, fn, tp = confusion_matrix(y_true, y_pred, labels=[0, 1]).ravel() return 160 * tp - 40 * fp
cv5 = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)oof_profit, strategies = {}, {}
def report(name, model): """Print out-of-fold metrics on the training set for the churn class.""" pred = cross_val_predict(model, X_train, y_train, cv=cv5) oof_profit[name] = int(campaign_profit(y_train, pred)) strategies[name] = model print(f"{name:<15} precision {precision_score(y_train, pred):.3f}" f" recall {recall_score(y_train, pred):.3f}" f" F1 {f1_score(y_train, pred):.3f} flagged {pred.mean():.1%}" f" profit {oof_profit[name]}")
logistic = make_pipeline(preprocess, LogisticRegression(max_iter=1000))report("default", logistic)default precision 0.671 recall 0.288 F1 0.403 flagged 8.3% profit 29200cross_val_predict returns, for every training customer, the prediction of the model that did not train on that customer. These out-of-fold predictions let you compare strategies without touching the test set. campaign_profit turns a confusion matrix into money: a caught churner is worth 200 − 40 = 160, a wasted call costs 40.
At the default threshold of 0.5, the model flags only about 9% of customers and finds only about 30% of the churners (recall). Two thirds of its flags are right (precision). The model ranks customers well (ROC-AUC 0.81); the threshold of 0.5 does not fit the campaign’s costs.
Step 2 — Weight the rare class
Section titled “Step 2 — Weight the rare class”from sklearn.utils.class_weight import compute_class_weight
weights = compute_class_weight("balanced", classes=np.array([0, 1]), y=y_train)print("balanced weights:", weights.round(3))weighted = make_pipeline( preprocess, LogisticRegression(max_iter=1000, class_weight="balanced"))report("class weights", weighted)balanced weights: [0.619 2.597]class weights precision 0.385 recall 0.788 F1 0.517 flagged 39.4% profit 54640"balanced" gives a churner a weight of 2.6 and a stayer a weight of 0.62, so both classes contribute equally to the loss. The model now flags many more customers and catches most churners, at the cost of a lower precision. The F1 score and the profit go up.
Step 3 — Tune the threshold for the business cost
Section titled “Step 3 — Tune the threshold for the business cost”from sklearn.metrics import make_scorerfrom sklearn.model_selection import TunedThresholdClassifierCV
tuned = TunedThresholdClassifierCV( logistic, scoring=make_scorer(campaign_profit), cv=cv5, random_state=42)report("tuned threshold", tuned)tuned.fit(X_train, y_train)print(f"threshold chosen on all training rows: {tuned.best_threshold_:.3f}")tuned threshold precision 0.403 recall 0.740 F1 0.522 flagged 35.3% profit 53840threshold chosen on all training rows: 0.195TunedThresholdClassifierCV fits the model on each of its own training folds, tries 100 thresholds on the matching validation folds and keeps the threshold with the best mean profit. Then it refits the model on all rows it received. Inside report, this whole procedure runs once per outer fold, so the out-of-fold profit is an honest estimate.
A call pays off when , that is when . The tuned threshold lands close to this break-even point, because a logistic regression gives fairly honest probabilities.
Step 4 — Resample with SMOTENC inside an imbalanced-learn pipeline
Section titled “Step 4 — Resample with SMOTENC inside an imbalanced-learn pipeline”from imblearn.over_sampling import SMOTE, SMOTENCfrom imblearn.pipeline import make_pipeline as make_imb_pipelinefrom imblearn.under_sampling import RandomUnderSampler
X_onehot = preprocess.fit_transform(X_train)X_smote, _ = SMOTE(random_state=42).fit_resample(X_onehot, y_train)dummies = X_smote[len(X_train):, :14] # synthetic rows, one-hot columnsfractional = ((dummies > 0) & (dummies < 1)).any(axis=1).mean()print(f"SMOTE on one-hot columns: {fractional:.1%} of synthetic rows have" " fractional dummies")
categorical = ["region", "plan", "contract", "payment_method", "has_autopay"]impute_charges = make_column_transformer( (SimpleImputer(strategy="median"), ["total_charges"]), remainder="passthrough", verbose_feature_names_out=False,).set_output(transform="pandas")X_nc, y_nc = SMOTENC(categorical_features=categorical, random_state=42).fit_resample( impute_charges.fit_transform(X_train), y_train)print("SMOTENC plans:", sorted(X_nc["plan"].unique().tolist()), "| autopay:", sorted(X_nc["has_autopay"].unique().tolist()), "| classes:", np.bincount(y_nc))
smotenc_model = make_imb_pipeline( impute_charges, SMOTENC(categorical_features=categorical, random_state=42), preprocess, LogisticRegression(max_iter=1000),)under_model = make_imb_pipeline( preprocess, RandomUnderSampler(random_state=42), LogisticRegression(max_iter=1000))report("SMOTENC", smotenc_model)report("undersampling", under_model)SMOTE on one-hot columns: 68.1% of synthetic rows have fractional dummiesSMOTENC plans: ['basic', 'premium', 'standard'] | autopay: [0, 1] | classes: [3028 3028]SMOTENC precision 0.385 recall 0.749 F1 0.508 flagged 37.5% profit 51920undersampling precision 0.369 recall 0.774 F1 0.500 flagged 40.4% profit 51200preprocess puts its 14 one-hot columns first (4 regions, 3 plans, 3 contracts and 4 payment methods). Plain SMOTE on these columns interpolates between two customers and invents rows such as “0.3 basic plan, 0.7 premium plan”. That is not a customer that can exist.
SMOTENC (SMOTE for nominal and continuous features) interpolates only the numeric columns. For each categorical column, it copies the most common value among the neighbors. It needs the raw categories, so the pipeline imputes total_charges first, then resamples, then encodes. has_autopay is 0/1, so it is listed as categorical too. The synthetic rows contain only real plans and autopay values, and both classes have 3,028 rows.
RandomUnderSampler drops stayers until both classes have 722 rows. For a logistic regression, both samplers give about the same result as class weights, which are cheaper and need no extra library. Resampling helps more with models that have no class_weight option.
Step 5 — See the leak when you resample before cross-validation
Section titled “Step 5 — See the leak when you resample before cross-validation”from sklearn.model_selection import cross_validate
continuous = ["age", "tenure_months", "monthly_charges", "total_charges", "support_tickets", "logins_last_30d", "avg_session_minutes"]X_cont = SimpleImputer(strategy="median").fit_transform(X_train[continuous])X_leaky, y_leaky = SMOTE(random_state=42).fit_resample(X_cont, y_train)scoring = ["recall", "f1"]leaky = cross_validate(forest, X_leaky, y_leaky, cv=cv5, scoring=scoring)safe = cross_validate( make_imb_pipeline(SMOTE(random_state=42), forest), X_cont, y_train, cv=cv5, scoring=scoring,)for name, res in [("SMOTE before CV", leaky), ("SMOTE inside CV", safe)]: print(f"{name}: recall {res['test_recall'].mean():.3f}," f" F1 {res['test_f1'].mean():.3f}")SMOTE before CV: recall 0.867, F1 0.872SMOTE inside CV: recall 0.443, F1 0.464This step uses only the 7 continuous columns, so plain SMOTE is valid here. The leaky version creates synthetic churners from all training rows first. Each synthetic row lies between two real churners, and cross-validation then puts the synthetic row and its parents into different folds. The forest has seen near-copies of each validation churner, so the leaky recall is far too high.
Part of the F1 gap has a second cause. The leaky validation folds are 50% churners (half of them synthetic), and precision and F1 rise with the share of positives. Recall does not depend on that share, so compare recall to see the pure leakage effect. Both numbers of the leaky version are fiction.
Step 6 — Test the chosen strategy once
Section titled “Step 6 — Test the chosen strategy once”for name, profit in oof_profit.items(): print(f"{name:<15} out-of-fold profit {profit}")best_strategy = max(oof_profit, key=oof_profit.get)print("chosen:", best_strategy)chosen_model = strategies[best_strategy].fit(X_train, y_train)pred = chosen_model.predict(X_test)print(f"test: precision {precision_score(y_test, pred):.3f}," f" recall {recall_score(y_test, pred):.3f}," f" profit {campaign_profit(y_test, pred)} on {len(y_test)} customers")default out-of-fold profit 29200class weights out-of-fold profit 54640tuned threshold out-of-fold profit 53840SMOTENC out-of-fold profit 51920undersampling out-of-fold profit 51200chosen: class weightstest: precision 0.374, recall 0.768, profit 17240 on 1250 customersClass weights and the tuned threshold nearly tie: they differ by 800 out of about 54,000, which is within the noise of 3,750 customers. They are close for a reason. With balanced weights, a weighted probability of 0.5 corresponds to an unweighted probability of about 0.62 / (0.62 + 2.6) ≈ 0.19, almost the break-even threshold. Both strategies call nearly the same customers. The rule picks the higher out-of-fold profit, class weights.
Only now does the test set come out, once, for the chosen model. Its precision and recall agree with the out-of-fold numbers of Step 2. The test profit is for 1,250 customers, a third of the 3,750 training customers, so it is about a third of the out-of-fold profit.
Common mistakes:
- Calling
fit_resampleon the whole dataset and then cross-validating. Always resample insideimblearn.pipeline.Pipeline. - Putting a sampler into a scikit-learn
Pipeline. It raisesTypeError, because a sampler has notransformmethod. Import the pipeline fromimblearn.pipeline. - Judging an imbalanced model by accuracy. Report precision, recall, F1, average precision or a cost.
- Applying plain SMOTE to categorical data, as codes or as one-hot columns. It interpolates and invents categories such as “0.3 basic, 0.7 premium”. Use
SMOTENCon the raw columns (orSMOTENwhen all features are categorical),RandomOverSampleror class weights. - Comparing strategies on the test set. Compare them on out-of-fold predictions, then test the winner once.
Example 8 — Estimate the tuned model honestly with nested cross-validation
Section titled “Example 8 — Estimate the tuned model honestly with nested cross-validation”Goal: Show that best_score_ is optimistic, measure the honest score of a tuning procedure with nested cross-validation, and see how stable the chosen hyperparameters are.
Step 1 — Tune a model on pure noise
Section titled “Step 1 — Tune a model on pure noise”from sklearn.neighbors import KNeighborsClassifier
noise_rng = np.random.default_rng(42)X_noise = noise_rng.normal(size=(120, 20))y_noise = noise_rng.permutation(np.repeat([0, 1], 60))knn_grid = {"n_neighbors": list(range(1, 41)), "weights": ["uniform", "distance"]}inner = StratifiedKFold(n_splits=3, shuffle=True, random_state=42)noise_search = GridSearchCV(KNeighborsClassifier(), knn_grid, cv=inner)noise_search.fit(X_noise, y_noise)n_candidates = len(noise_search.cv_results_["params"])print(f"class share: {y_noise.mean():.2f}, candidates: {n_candidates}")print(f"best_score_: {noise_search.best_score_:.3f} with {noise_search.best_params_}")class share: 0.50, candidates: 80best_score_: 0.633 with {'n_neighbors': 25, 'weights': 'uniform'}The 120 rows have 20 random features and labels that are half 0 and half 1 in random order. No model can beat 50% accuracy on new data. Yet the best of 80 candidates reports about 63%. With 80 tries, one candidate gets lucky on these particular folds. The search reports its luck as skill.
Step 2 — Score the same search with nested cross-validation
Section titled “Step 2 — Score the same search with nested cross-validation”outer = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)nested_noise = cross_val_score(noise_search, X_noise, y_noise, cv=outer)print("outer scores:", nested_noise.round(3))print(f"nested estimate: {nested_noise.mean():.3f}")X_fresh = noise_rng.normal(size=(2000, 20))y_fresh = noise_rng.integers(0, 2, size=2000)print(f"accuracy on 2,000 fresh rows: {noise_search.score(X_fresh, y_fresh):.3f}")outer scores: [0.542 0.417 0.458 0.5 0.583]nested estimate: 0.500accuracy on 2,000 fresh rows: 0.507cross_val_score treats the search as one estimator. For each outer split, it runs the full grid search on 96 rows and scores the winner on the 24 held-out rows. The winner’s luck does not carry over to rows it never saw, so the estimate falls back to about 50%, the truth. The fresh rows confirm it: the tuned model is no better than a coin.
Step 3 — Run nested cross-validation on the churn tree
Section titled “Step 3 — Run nested cross-validation on the churn tree”from sklearn.model_selection import cross_validate
small_grid = {"tree__max_depth": [4, 6, 8], "tree__min_samples_leaf": [10, 50, 100]}churn_search = GridSearchCV(tree_pipe, small_grid, cv=inner, scoring="roc_auc")churn_search.fit(X_train, y_train)nested = cross_validate( churn_search, X_train, y_train, cv=outer, scoring="roc_auc", return_estimator=True)print(f"non-nested best_score_: {churn_search.best_score_:.3f}")print("outer scores:", nested["test_score"].round(3))print(f"nested estimate: {nested['test_score'].mean():.3f}" f" +/- {nested['test_score'].std():.3f}")for est in nested["estimator"]: print(" chosen:", est.best_params_)non-nested best_score_: 0.803outer scores: [0.815 0.808 0.79 0.828 0.806]nested estimate: 0.809 +/- 0.012 chosen: {'tree__max_depth': 6, 'tree__min_samples_leaf': 50} chosen: {'tree__max_depth': 6, 'tree__min_samples_leaf': 50} chosen: {'tree__max_depth': 8, 'tree__min_samples_leaf': 50} chosen: {'tree__max_depth': 6, 'tree__min_samples_leaf': 50} chosen: {'tree__max_depth': 6, 'tree__min_samples_leaf': 50}The search runs 5 outer × 3 inner × 9 candidates = 135 fits, plus refits. With 3,750 rows and 9 candidates, the selection bias is small: the non-nested and nested scores are close. Here the nested estimate is even slightly higher. The bias is smaller than the fold-to-fold noise (± 0.012), so the sign of the difference can flip from one dataset or seed to the next. The spread of the outer scores (about ± 0.01) is a useful error bar. return_estimator=True keeps the search fitted on each outer training part. The chosen depths and leaf sizes vary a little, which shows that several settings are nearly tied.
Step 4 — Report the estimate and the final model
Section titled “Step 4 — Report the estimate and the final model”final_model = churn_search.best_estimator_test_auc = roc_auc_score(y_test, final_model.predict_proba(X_test)[:, 1])print("final hyperparameters:", churn_search.best_params_)print(f"nested CV estimate {nested['test_score'].mean():.3f}," f" test ROC-AUC {test_auc:.3f}")final hyperparameters: {'tree__max_depth': 6, 'tree__min_samples_leaf': 50}nested CV estimate 0.809, test ROC-AUC 0.807The final model is the search refitted on all training rows. Nested CV estimated how well this procedure works. The test set, used once, confirms the estimate. In a report, give the nested estimate with its spread and the single test score.
Common mistakes:
- Reporting
best_score_as the expected performance. It is the maximum of noisy estimates and is optimistic, badly so with many candidates and few rows. - Using the same
cvobject with the same random state for the inner and outer loops and thinking that this leaks. It does not: the inner loop only ever sees the outer training part. - Expecting nested CV to return one best set of hyperparameters. It evaluates a procedure. Fit the search once on all training data to get the final model.
Pitfalls
Section titled “Pitfalls”| Mistake | Symptom | Fix |
|---|---|---|
| Choosing the model with the best training score | the most complex model wins; test score disappoints | compare validation scores; check the gap |
| Shuffled k-fold on rows that share a customer or store | CV score far above the score on new entities | GroupKFold or StratifiedGroupKFold with groups= |
| Shuffled k-fold on time series | CV error much lower than the error in production | TimeSeriesSplit, optionally with gap |
Passing groups= to KFold |
UserWarning: The groups parameter is ignored by KFold |
use a group splitter |
| Plain k-fold on a rare class | fold scores jump; a fold may have almost no positives | StratifiedKFold |
| Parameter names without the step prefix | ValueError: Invalid parameter 'max_depth' for estimator Pipeline |
"tree__max_depth"; list names with pipe.get_params().keys() |
uniform(a, b) meant as the range a to b |
samples from a to a + b | uniform(loc=a, scale=b - a) |
uniform for C, alpha or a learning rate |
almost no small values are tried | loguniform or suggest_float(..., log=True) |
| Best value at the edge of the grid | the optimum may lie outside the range | widen the range and search again |
| Resampling before cross-validation | F1 or recall far higher in CV than on the test set | sampler inside imblearn.pipeline.Pipeline |
| Plain SMOTE on one-hot or coded categories | synthetic rows with fractional dummies such as 0.3 basic, 0.7 premium | SMOTENC on the raw columns, RandomOverSampler or class weights |
A sampler in a scikit-learn Pipeline |
TypeError about a missing transform |
from imblearn.pipeline import make_pipeline |
| Default threshold 0.5 on a rare class | low recall, few positives predicted | TunedThresholdClassifierCV with a business scorer |
Reporting best_score_ as the final estimate |
real performance is lower than reported | nested CV, then one look at the test set |
| Optuna logs every trial | stderr flooded with Trial N finished lines |
optuna.logging.set_verbosity(optuna.logging.WARNING) |
Where this is used beyond data science
Section titled “Where this is used beyond data science”- Web and product engineering: A/B testing platforms split users, not page views, into groups for the same reason as
GroupKFold: one user’s many visits are not independent evidence. - Operations and finance: backtesting a trading rule or a capacity forecast is walk-forward validation. A backtest that shuffles days leaks the future and overstates returns.
- Tooling and automation: Optuna tunes anything with a score, not only models: database connection pool sizes, compiler flags, cache sizes or the batch size of a data pipeline, measured by a benchmark.
- Alerting and security: spam filters, fraud rules and monitoring alerts pick a threshold from the cost of a false alarm and the cost of a missed event, exactly as in Example 7.
Summary
Section titled “Summary”- The expected error is bias² + variance + irreducible noise. Simple models have high bias, flexible models high variance.
- Underfitting: low training and validation scores, small gap. Overfitting: high training score, much lower validation score.
- Learning curves (score vs rows) tell you if more data will help. Validation curves (score vs one hyperparameter) show where underfitting turns into overfitting.
- The CV split must mimic production:
StratifiedKFoldfor rare classes,GroupKFoldwhen entities repeat,TimeSeriesSplitwhen you predict the future. GridSearchCVis exhaustive,RandomizedSearchCVsamples from SciPy distributions on a fixed budget, successive halving tries many candidates cheaply, and Optuna’s TPE learns where to search.- For imbalanced classes, pick a fitting metric, then use class weights, a tuned threshold or resampling. Resample only inside training folds with an imbalanced-learn pipeline.
best_score_is optimistic. Nested CV estimates the performance of the whole tuning procedure. The test set confirms it once.
Self-check questions
Section titled “Self-check questions”Q1. A model has a training ROC-AUC of 0.99 and a validation ROC-AUC of 0.70. Is it underfitting or overfitting, and name two fixes.
Answer
It overfits: the training score is very high and the gap is large (high variance). Fixes: regularize or simplify the model (for a tree, a smaller max_depth or a larger min_samples_leaf), get more training data, or remove noisy features.
Q2. A learning curve shows training and validation scores that meet at 0.72 after 2,000 rows and stay flat up to 8,000 rows. Will collecting 20,000 more rows help?
Answer
Probably not. Converged, flat curves mean high bias: the model has learned all it can with these features. Try a more flexible model, less regularization or better features instead.
Q3. Why can the training MSE of a polynomial fall below the noise variance, while the test MSE cannot?
Answer
On the training rows, a flexible model can bend through the noise itself, so its error there can drop toward zero. On new rows the noise is different and unpredictable, so the expected error is at least the noise variance , plus bias² and variance.
Q4. You predict whether a store will hit its monthly target, with one row per store and month, and the model will run on new stores next year. Which splitter do you use?
Answer
GroupKFold with groups=store_id (or StratifiedGroupKFold if the “hit” class is rare). The model will meet stores it has never seen, so each validation fold must contain only stores that are absent from training. If the model will instead run on the same stores in future months, a time-based split is the better match.
Q5. What does TimeSeriesSplit(n_splits=4, test_size=30, gap=5) guarantee about the validation rows of each split?
Answer
Each validation window has 30 consecutive rows. All of them come after every training row, and 5 rows between the end of training and the start of validation are left out. The validation windows are the last 4 × 30 rows of the data, in order.
Q6. A grid has 5 values of C and 4 values of l1_ratio, and you use 5-fold CV. How many fits does GridSearchCV make? How would you cut the cost and still explore C well?
Answer
5 × 4 = 20 candidates × 5 folds = 100 fits, plus 1 refit = 101. Use RandomizedSearchCV with C drawn from loguniform(1e-3, 1e2) and a smaller n_iter, or successive halving, or fewer folds during the search.
Q7. Why does RandomizedSearchCV with n_iter=16 often beat a 4 × 4 grid?
Answer
Usually only a few hyperparameters matter. The grid tries only 4 distinct values of each one. Random search tries up to 16 distinct values of each one for the same 16 candidates, so it explores the important knob much more finely.
Q8. Your colleague runs SMOTE().fit_resample(X, y) and then cross_val_score(model, X_res, y_res). The recall is 0.92 in CV and 0.55 in production. Explain and fix.
Answer
SMOTE created synthetic rows from all rows before the split. Synthetic rows and their parent rows then land in different folds, so validation rows are near-copies of training rows. Fix: put the sampler inside imblearn.pipeline.make_pipeline(SMOTE(), model) and cross-validate that pipeline, so resampling happens on training folds only.
Q9. A call costs 10 and a caught churner is worth 50. Above which predicted churn probability should you call, if the model’s probabilities are calibrated?
Answer
A caught churner gains 50 − 10 = 40, a wasted call loses 10. Call when , that is . In general the break-even threshold is cost / value.
Q10. What does nested cross-validation estimate, and what does it not give you?
Answer
It estimates the performance of the whole procedure “tune with this search, then refit”, on data that the search never saw. It does not give you one final model or one set of hyperparameters: each outer fold may choose differently. You get the final model by fitting the search once on all training data.
Q11. Why is best_score_ more optimistic with 500 candidates on 300 rows than with 9 candidates on 30,000 rows?
Answer
best_score_ is the maximum of noisy estimates. More candidates give more chances for a lucky score, and fewer rows make each estimate noisier. Both raise the selection bias.
Track your progress
Section titled “Track your progress”Next steps
Section titled “Next steps”- Exercises: 28 exercises on curves, CV strategies, searches, imbalance and nested CV, with hints and full solutions.
- Mini-project: build and honestly evaluate a churn model for a retention campaign with a cost-based threshold.
- Cheat sheet: splitters, search classes, distributions, Optuna and imbalanced-learn on one page.
- Next module: 38. Ensembles combines many models with bagging, boosting, voting and stacking.