37. Model evaluation and tuning — Exercises
These exercises practice every idea of the Model evaluation and tuning lesson. They use customers.csv, sales.csv, web_traffic.csv and houses.csv (see the data dictionary), plus small simulated datasets.
How to work:
- Read the task and the expected output.
- Put the setup block below at the top of your script (for example
exercise.py). Then copy the starter code under it and replace each to-do comment with your code. - Run the script with
python exercise.pyfrom your project folder. Compare your output with the expected output. - Stuck? Open one hint at a time. Open the solution only after a real attempt.
Each solution ends with assert checks. Several exercises ask you to interpret a result or choose a method. Write your answer in one or two sentences before you open the solution.
Every exercise runs after this block:
import numpy as npimport pandas as pdfrom sklearn.compose import make_column_selector, make_column_transformerfrom sklearn.impute import SimpleImputerfrom sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import StratifiedKFold, train_test_splitfrom sklearn.pipeline import make_pipelinefrom sklearn.preprocessing import OneHotEncoder, StandardScaler
pd.set_option("display.width", 100)pd.set_option("display.max_columns", 12)pd.set_option("display.precision", 3)
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)NUMERIC = X.select_dtypes("number").columns.tolist()cv3 = StratifiedKFold(n_splits=3, shuffle=True, random_state=42)
def make_preprocess(): """One-hot encode the text columns; impute and scale the numeric ones.""" return 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"), ), )X_train has 3,750 customers and X_test 1,250, both with a churn rate of 19.3%. NUMERIC lists the 8 numeric feature columns. make_preprocess() returns a fresh preprocessing step each time you call it.
Warm-up
Section titled “Warm-up”M37-W01 · Diagnose from two scores
Section titled “M37-W01 · Diagnose from two scores”Write the code: write a function diagnose(train_score, valid_score) that returns "overfitting" when the gap train_score - valid_score is larger than 0.08, "underfitting" when the gap is at most 0.08 and the validation score is below 0.70, and "good fit" otherwise. Apply it to the four churn models in the starter.
stump: underfittingdepth 5: good fitdeep tree: overfittinglogistic: good fitscores = { "stump": (0.68, 0.67), "depth 5": (0.85, 0.79), "deep tree": (1.00, 0.64), "logistic": (0.82, 0.81),}
def diagnose(train_score, valid_score): # TODO: return "overfitting", "underfitting" or "good fit" ...
# TODO: print "name: diagnosis" for each modelHint 1
Check the gap first. A large gap means overfitting whatever the validation score is.
Hint 2
gap = train_score - valid_scoreif gap > 0.08: return "overfitting"Solution
scores = { "stump": (0.68, 0.67), "depth 5": (0.85, 0.79), "deep tree": (1.00, 0.64), "logistic": (0.82, 0.81),}
def diagnose(train_score, valid_score, max_gap=0.08, low=0.70): gap = train_score - valid_score if gap > max_gap: return "overfitting" if valid_score < low: return "underfitting" return "good fit"
for name, (train_score, valid_score) in scores.items(): print(f"{name}: {diagnose(train_score, valid_score)}")
assert diagnose(1.00, 0.64) == "overfitting"assert diagnose(0.68, 0.67) == "underfitting"assert diagnose(0.82, 0.81) == "good fit"stump: underfittingdepth 5: good fitdeep tree: overfittinglogistic: good fitHow it works:
- The gap measures how much better the model does on its own training rows. A gap above 0.08 means the model learned details that do not repeat: overfitting.
- With a small gap, a low validation score means that the model is too simple for the pattern: underfitting.
- The thresholds are parameters with defaults, so you can adapt them to a problem where 0.70 is a good score.
Alternative: for many models in a DataFrame, use np.select on whole columns:
table = pd.DataFrame(scores, index=["train", "valid"]).Tgap = table["train"] - table["valid"]table["diagnosis"] = np.select( [gap > 0.08, table["valid"] < 0.70], ["overfitting", "underfitting"], "good fit")print(table)assert table.loc["depth 5", "diagnosis"] == "good fit" train valid diagnosisstump 0.68 0.67 underfittingdepth 5 0.85 0.79 good fitdeep tree 1.00 0.64 overfittinglogistic 0.82 0.81 good fitM37-W02 · Predict the output: class shares per fold
Section titled “M37-W02 · Predict the output: class shares per fold”Predict the output: 20 rows are sorted by their label, 16 stayers then 4 churners. Predict how many churners land in each validation fold for KFold(4) without shuffling and for StratifiedKFold(4).
Acceptance criteria:
- Write your prediction for both lines before you run the code.
- Run the code. Your prediction matches the Output in the solution.
- You can explain why one splitter gives a fold with all 4 churners.
from sklearn.model_selection import KFold, StratifiedKFold
labels = np.array([0] * 16 + [1] * 4)rows = np.zeros((20, 1))for splitter in [KFold(n_splits=4), StratifiedKFold(n_splits=4)]: counts = [int(labels[valid].sum()) for _, valid in splitter.split(rows, labels)] print(type(splitter).__name__, counts)Hint 1
Without shuffling, KFold cuts the rows into 4 consecutive blocks of 5.
Hint 2
StratifiedKFold gives each fold the same share of each class: 4 churners over 4 folds.
Solution
from sklearn.model_selection import KFold, StratifiedKFold
labels = np.array([0] * 16 + [1] * 4)rows = np.zeros((20, 1))for splitter in [KFold(n_splits=4), StratifiedKFold(n_splits=4)]: counts = [int(labels[valid].sum()) for _, valid in splitter.split(rows, labels)] print(type(splitter).__name__, counts) assert sum(counts) == 4KFold [0, 0, 0, 4]StratifiedKFold [1, 1, 1, 1]How it works:
KFold(4)takes rows 0–4, 5–9, 10–14 and 15–19 as validation folds. The 4 churners are rows 16–19, so they all land in the last fold. Three folds have no churner, and a model trained for that last fold never saw a churner at all.StratifiedKFold(4)distributes each class separately, so each fold gets 4 stayers and 1 churner.- Real files are often sorted (by date, by status). Shuffle and stratify for classification:
StratifiedKFold(n_splits=4, shuffle=True, random_state=42).
M37-W03 · Count the fits of a grid search
Section titled “M37-W03 · Count the fits of a grid search”Write the code: count the candidates of the grid below with ParameterGrid, and the number of fits that GridSearchCV(..., cv=5) makes, with and without the final refit.
candidates: 24CV fits: 120with refit: 121first candidate: {'criterion': 'gini', 'max_depth': 3, 'min_samples_leaf': 1}from sklearn.model_selection import ParameterGrid
grid = { "max_depth": [3, 5, 7, None], "min_samples_leaf": [1, 10, 50], "criterion": ["gini", "entropy"],}# TODO: count candidates, CV fits (5 folds) and the total with the refitHint 1
len(ParameterGrid(grid)) gives the number of combinations.
Hint 2
Each candidate is fitted once per fold. With refit=True (the default), the winner is fitted once more on all rows.
Solution
from sklearn.model_selection import ParameterGrid
grid = { "max_depth": [3, 5, 7, None], "min_samples_leaf": [1, 10, 50], "criterion": ["gini", "entropy"],}candidates = len(ParameterGrid(grid))cv_fits = candidates * 5print("candidates:", candidates)print("CV fits:", cv_fits)print("with refit:", cv_fits + 1)print("first candidate:", list(ParameterGrid(grid))[0])
assert candidates == 4 * 3 * 2assert cv_fits + 1 == 121candidates: 24CV fits: 120with refit: 121first candidate: {'criterion': 'gini', 'max_depth': 3, 'min_samples_leaf': 1}How it works:
ParameterGridexpands the dictionary into every combination: 4 × 3 × 2 = 24 candidates.- 5-fold CV fits each candidate 5 times: 120 fits. The refit of the winner on all rows makes 121.
- Adding one more hyperparameter with 5 values would multiply the cost by 5. This is why wide grids get expensive fast.
M37-W04 · Fix the bug: customers in two folds
Section titled “M37-W04 · Fix the bug: customers in two folds”Fix the bug: the code should build 3 folds of order lines in which no customer appears on both sides. It passes groups= to KFold, which ignores it (and warns). Fix the splitter and print, for each fold, the number of validation lines and the number of shared customers.
fold 0: 6952 lines, 0 shared customersfold 1: 6371 lines, 0 shared customersfold 2: 6905 lines, 0 shared customersfrom sklearn.model_selection import KFold
lines = pd.read_csv("data/sales.csv", usecols=["customer_id", "revenue"])groups = lines["customer_id"]splitter = KFold(n_splits=3, shuffle=True, random_state=42) # bugfor fold, (train_idx, valid_idx) in enumerate(splitter.split(lines, groups=groups)): shared = set(groups.iloc[train_idx]) & set(groups.iloc[valid_idx]) print(f"fold {fold}: {len(valid_idx)} lines, {len(shared)} shared customers")Hint 1
Which splitter keeps all rows of one group together?
Hint 2
GroupKFold(n_splits=3, shuffle=True, random_state=42) accepts the same split(X, y, groups) call.
Solution
from sklearn.model_selection import GroupKFold
lines = pd.read_csv("data/sales.csv", usecols=["customer_id", "revenue"])groups = lines["customer_id"]splitter = GroupKFold(n_splits=3, shuffle=True, random_state=42)for fold, (train_idx, valid_idx) in enumerate(splitter.split(lines, groups=groups)): shared = set(groups.iloc[train_idx]) & set(groups.iloc[valid_idx]) print(f"fold {fold}: {len(valid_idx)} lines, {len(shared)} shared customers") assert len(shared) == 0fold 0: 6952 lines, 0 shared customersfold 1: 6371 lines, 0 shared customersfold 2: 6905 lines, 0 shared customersHow it works:
KFoldsplits rows, not customers, so most customers end up on both sides. It ignoresgroupsand warnsThe groups parameter is ignored by KFold.GroupKFoldassigns whole customers to folds. The set intersection of the customer ids of both sides is empty in every fold.- The folds have different numbers of lines, because customers have different numbers of lines.
GroupKFoldbalances the line counts as well as it can.
M37-W05 · Predict the output: walk-forward indices
Section titled “M37-W05 · Predict the output: walk-forward indices”Predict the output: 10 days in date order go through TimeSeriesSplit(n_splits=3). Predict the training and validation day numbers of each split.
Acceptance criteria:
- Write the three lines of your prediction before you run the code.
- Run the code. Your prediction matches the Output in the solution.
- You can explain how the default validation size is computed.
from sklearn.model_selection import TimeSeriesSplit
days = np.arange(10).reshape(-1, 1)for train_idx, valid_idx in TimeSeriesSplit(n_splits=3).split(days): print("train", train_idx.tolist(), "validate", valid_idx.tolist())Hint 1
The default validation size is n_samples // (n_splits + 1).
Hint 2
The validation windows are the last n_splits × size rows. Each training set is everything before its window.
Solution
from sklearn.model_selection import TimeSeriesSplit
days = np.arange(10).reshape(-1, 1)for train_idx, valid_idx in TimeSeriesSplit(n_splits=3).split(days): print("train", train_idx.tolist(), "validate", valid_idx.tolist()) assert train_idx.max() < valid_idx.min()train [0, 1, 2, 3] validate [4, 5]train [0, 1, 2, 3, 4, 5] validate [6, 7]train [0, 1, 2, 3, 4, 5, 6, 7] validate [8, 9]How it works:
- The validation size is
10 // (3 + 1)= 2 days. - The three windows are the last 6 days: 4–5, 6–7 and 8–9.
- Each training set holds all days before its window, so it grows from 4 to 8 days. The assert checks that training always ends before validation starts.
M37-W06 · Sample a search space with SciPy
Section titled “M37-W06 · Sample a search space with SciPy”Write the code: draw 1,000 values of C from loguniform(1e-3, 1e2) and from uniform(1e-3, 1e2) (both with random_state=42). Print the share of draws below 0.1 for each. Then print the distinct values that randint(2, 6) produces in 1,000 draws.
loguniform: 42.1% of draws below 0.1uniform: 0.0% of draws below 0.1randint(2, 6) values: [2, 3, 4, 5]from scipy.stats import loguniform, randint, uniform
# TODO: 1,000 draws from each distribution with random_state=42# TODO: print the share of draws below 0.1# TODO: print the sorted distinct values of randint(2, 6)Hint 1
Every SciPy distribution has .rvs(size=1000, random_state=42).
Hint 2
(draws < 0.1).mean() is the share. np.unique(draws) gives the distinct values.
Solution
from scipy.stats import loguniform, randint, uniform
log_draws = loguniform(1e-3, 1e2).rvs(size=1000, random_state=42)lin_draws = uniform(1e-3, 1e2).rvs(size=1000, random_state=42)int_draws = randint(2, 6).rvs(size=1000, random_state=42)print(f"loguniform: {(log_draws < 0.1).mean():.1%} of draws below 0.1")print(f"uniform: {(lin_draws < 0.1).mean():.1%} of draws below 0.1")print("randint(2, 6) values:", np.unique(int_draws).tolist())
assert 0.35 < (log_draws < 0.1).mean() < 0.45assert np.unique(int_draws).tolist() == [2, 3, 4, 5]loguniform: 42.1% of draws below 0.1uniform: 0.0% of draws below 0.1randint(2, 6) values: [2, 3, 4, 5]How it works:
- The range 0.001 to 100 spans 5 orders of magnitude. Values below 0.1 cover 2 of them, so
loguniformputs about 40% of its draws there. uniform(loc, scale)coversloctoloc + scale. Values below 0.1 are only 0.1% of that width, souniformalmost never tries a smallC.randint(2, 6)excludes its upper bound, likerange.
M37-W07 · Compute balanced class weights by hand
Section titled “M37-W07 · Compute balanced class weights by hand”Write the code: compute the "balanced" class weights of the churn label y with the formula , and check them against compute_class_weight.
counts: [4037, 963]manual: [0.619, 2.596]sklearn: [0.619, 2.596]weighted totals: [2500.0, 2500.0]from sklearn.utils.class_weight import compute_class_weight
# TODO: count the rows per class# TODO: apply n / (k * n_c)# TODO: compare with compute_class_weight("balanced", classes=..., y=y)Hint 1
y.value_counts().sort_index() gives the counts for class 0 and class 1.
Hint 2
is len(y) and is 2.
Solution
from sklearn.utils.class_weight import compute_class_weight
counts = y.value_counts().sort_index()manual = len(y) / (len(counts) * counts)library = compute_class_weight("balanced", classes=np.array([0, 1]), y=y)print("counts:", counts.tolist())print("manual:", manual.round(3).tolist())print("sklearn:", library.round(3).tolist())print("weighted totals:", (counts * manual).round(1).tolist())
assert np.allclose(manual.to_numpy(), library)counts: [4037, 963]manual: [0.619, 2.596]sklearn: [0.619, 2.596]weighted totals: [2500.0, 2500.0]How it works:
- 4,037 stayers and 963 churners. The weights are 5,000 / (2 × 4,037) and 5,000 / (2 × 963).
- The weighted totals are equal (2,500 each): with these weights, both classes contribute the same to the loss.
class_weight="balanced"computes exactly these values from the training labels insidefit.
M37-W08 · Apply a custom threshold
Section titled “M37-W08 · Apply a custom threshold”Write the code: ten customers have the churn probabilities below. Turn them into predictions at the thresholds 0.5 and 0.3, and print the number of flagged customers and the recall at each threshold.
threshold 0.5: flagged 2, recall 0.50threshold 0.3: flagged 6, recall 1.00proba = np.array([0.05, 0.12, 0.33, 0.41, 0.48, 0.22, 0.67, 0.81, 0.36, 0.09])actual = np.array([0, 0, 1, 1, 0, 0, 1, 1, 0, 0])# TODO: for 0.5 and 0.3, predict 1 where proba >= threshold# TODO: print flagged count and recallHint 1
(proba >= 0.3).astype(int) gives the predictions.
Hint 2
Recall is the share of actual churners that you flagged: pred[actual == 1].mean().
Solution
from sklearn.metrics import recall_score
proba = np.array([0.05, 0.12, 0.33, 0.41, 0.48, 0.22, 0.67, 0.81, 0.36, 0.09])actual = np.array([0, 0, 1, 1, 0, 0, 1, 1, 0, 0])for threshold in [0.5, 0.3]: pred = (proba >= threshold).astype(int) recall = recall_score(actual, pred) print(f"threshold {threshold}: flagged {pred.sum()}, recall {recall:.2f}")
assert recall_score(actual, (proba >= 0.3).astype(int)) == 1.0threshold 0.5: flagged 2, recall 0.50threshold 0.3: flagged 6, recall 1.00How it works:
- At 0.5, only the two highest probabilities are flagged, so 2 of the 4 churners are caught.
- At 0.3, six customers are flagged, all 4 churners among them. Recall rises to 1.0 and precision falls to 4 / 6.
predictuses 0.5. Lowering the threshold trades precision for recall.
M37-W09 · Read cv_results_
Section titled “M37-W09 · Read cv_results_”Write the code: tune max_depth (2, 4, 6, 8) of a DecisionTreeClassifier(random_state=42) on the numeric columns of X_train with GridSearchCV (cv=cv3, scoring="roc_auc"). Print the three best rows of cv_results_ with the depth, the mean score, its standard deviation and the rank.
param_max_depth mean_test_score std_test_score rank_test_score 4 0.756 0.012 1 6 0.732 0.003 2 2 0.720 0.005 3from sklearn.model_selection import GridSearchCVfrom sklearn.tree import DecisionTreeClassifier
# TODO: fit the search on X_train[NUMERIC]# TODO: build a DataFrame from cv_results_ and print the top 3 rowsHint 1
Decision trees in scikit-learn 1.9 accept missing values, so total_charges needs no imputer here.
Hint 2
The columns are param_max_depth, mean_test_score, std_test_score and rank_test_score. Sort by the rank.
Solution
from sklearn.model_selection import GridSearchCVfrom sklearn.tree import DecisionTreeClassifier
search = GridSearchCV( DecisionTreeClassifier(random_state=42), {"max_depth": [2, 4, 6, 8]}, cv=cv3, scoring="roc_auc", n_jobs=1,).fit(X_train[NUMERIC], y_train)columns = ["param_max_depth", "mean_test_score", "std_test_score", "rank_test_score"]results = pd.DataFrame(search.cv_results_)[columns]print(results.sort_values("rank_test_score").head(3).to_string(index=False))
assert search.best_params_["max_depth"] == results.loc[ results["rank_test_score"] == 1, "param_max_depth"].iloc[0] param_max_depth mean_test_score std_test_score rank_test_score 4 0.756 0.012 1 6 0.732 0.003 2 2 0.720 0.005 3How it works:
cv_results_is a dictionary of arrays, one entry per candidate.pd.DataFrameturns it into a table.rank_test_scoreis 1 for the best mean score. Ties get the same rank.- Look at
std_test_scoretoo: if two candidates differ by less than one standard deviation, the data cannot really tell them apart, and the simpler one is a fine choice.
M37-C01 · Validation curve for k-nearest neighbors
Section titled “M37-C01 · Validation curve for k-nearest neighbors”Write the code and interpret: compute a validation curve for n_neighbors of a KNeighborsClassifier on the numeric churn features (impute, scale, then KNN). Use validation_curve with the values 1, 5, 15, 45 and 135, cv=cv3 and ROC-AUC. Print the mean training and validation scores and the best k. Which values underfit and which overfit?
k train valid 1 1.000 0.577 5 0.895 0.690 15 0.843 0.746 45 0.810 0.772135 0.797 0.784best k: 135from sklearn.model_selection import validation_curvefrom sklearn.neighbors import KNeighborsClassifier
knn = make_pipeline( SimpleImputer(strategy="median"), StandardScaler(), KNeighborsClassifier())ks = [1, 5, 15, 45, 135]# TODO: validation_curve(..., param_name="kneighborsclassifier__n_neighbors", ...)# TODO: print a table of k, train and valid means and the best kHint 1
validation_curve returns two arrays of shape (number of values, number of folds): training scores and validation scores.
Hint 2
Take .mean(axis=1) of each array and put them in a DataFrame with the k values.
Solution
from sklearn.model_selection import validation_curvefrom sklearn.neighbors import KNeighborsClassifier
knn = make_pipeline( SimpleImputer(strategy="median"), StandardScaler(), KNeighborsClassifier())ks = [1, 5, 15, 45, 135]train_scores, valid_scores = validation_curve( knn, X_train[NUMERIC], y_train, param_name="kneighborsclassifier__n_neighbors", param_range=ks, cv=cv3, scoring="roc_auc", n_jobs=1,)curve = pd.DataFrame( {"k": ks, "train": train_scores.mean(axis=1), "valid": valid_scores.mean(axis=1)})print(curve.round(3).to_string(index=False))print("best k:", curve.loc[curve["valid"].idxmax(), "k"])
assert curve.loc[0, "train"] == 1.0assert curve["valid"].idxmax() > 0 k train valid 1 1.000 0.577 5 0.895 0.690 15 0.843 0.746 45 0.810 0.772135 0.797 0.784best k: 135How it works:
- With
k=1, each training customer is its own nearest neighbor, so the training ROC-AUC is a perfect 1.0, while the validation score is the lowest: strong overfitting. - As
kgrows, the prediction averages more neighbors, the training score falls and the gap closes. The validation score is still rising atk=135, the largest value tried. A best value at the edge of the range means that the search should go further: exercise C09 does. - For KNN, a small
kis complex (high variance) and a largekis simple (high bias). The direction is the opposite ofmax_depth.
Alternative: ValidationCurveDisplay.from_estimator(...) with the same arguments draws the curve and keeps the same arrays in train_scores and test_scores.
M37-C02 · Will more data help?
Section titled “M37-C02 · Will more data help?”Interpret a result: compute learning curves (learning_curve, sizes 20%, 50% and 100% of each training fold, cv=cv3, ROC-AUC) for two models on the numeric churn features: an unpruned decision tree and a logistic regression (impute, scale, model). For each model, print the final gap and the gain of the validation score between the last two sizes, and a verdict: “more data helps” if the gap is above 0.1 and the gain is positive, “overfits: regularize first” if the gap is above 0.1 and the gain is not positive, otherwise “more data will not help much”.
tree sizes [500, 1250, 2500] valid [0.646, 0.635, 0.628] gap 0.372, last gain -0.007 -> overfits: regularize firstlogistic sizes [500, 1250, 2500] valid [0.775, 0.781, 0.785] gap 0.004, last gain +0.004 -> more data will not help muchfrom sklearn.model_selection import learning_curvefrom sklearn.tree import DecisionTreeClassifier
models = { "tree": DecisionTreeClassifier(random_state=42), "logistic": make_pipeline( SimpleImputer(strategy="median"), StandardScaler(), LogisticRegression() ),}# TODO: learning_curve for each model# TODO: print sizes, final gap, last gain and a verdictHint 1
learning_curve returns (train_sizes, train_scores, valid_scores). Pass train_sizes=[0.2, 0.5, 1.0].
Hint 2
The final gap is train_mean[-1] - valid_mean[-1]. The last gain is valid_mean[-1] - valid_mean[-2].
Solution
from sklearn.model_selection import learning_curvefrom sklearn.tree import DecisionTreeClassifier
models = { "tree": DecisionTreeClassifier(random_state=42), "logistic": make_pipeline( SimpleImputer(strategy="median"), StandardScaler(), LogisticRegression() ),}gaps = {}for name, model in models.items(): sizes, train_scores, valid_scores = learning_curve( model, X_train[NUMERIC], y_train, train_sizes=[0.2, 0.5, 1.0], cv=cv3, scoring="roc_auc", n_jobs=1, ) train_mean = train_scores.mean(axis=1) valid_mean = valid_scores.mean(axis=1) gap = train_mean[-1] - valid_mean[-1] gain = valid_mean[-1] - valid_mean[-2] if gap > 0.1: verdict = "more data helps" if gain > 0 else "overfits: regularize first" else: verdict = "more data will not help much" gaps[name] = gap print(f"{name:<8} sizes {sizes.tolist()} valid {valid_mean.round(3).tolist()}") print(f"{'':<8} gap {gap:.3f}, last gain {gain:+.3f} -> {verdict}")
assert gaps["tree"] > 0.3 > gaps["logistic"]tree sizes [500, 1250, 2500] valid [0.646, 0.635, 0.628] gap 0.372, last gain -0.007 -> overfits: regularize firstlogistic sizes [500, 1250, 2500] valid [0.775, 0.781, 0.785] gap 0.004, last gain +0.004 -> more data will not help muchHow it works:
- The tree keeps a training score of 1.0 and a validation score near 0.63. The gap is huge: high variance. Its validation score does not improve with more rows: the small drop (−0.007) is within the fold-to-fold noise. Limiting the depth helps much more than more data, and it costs nothing.
- The logistic regression has a tiny gap and a validation score that barely moves between 1,250 and 2,500 rows. Its curves have converged: high bias for this feature set. Better features (such as the text columns that this exercise leaves out) or a more flexible model are the next step.
- A verdict rule like this is a starting point. Always look at the curve itself before you buy more data.
M37-C03 · Measure bias and variance of k-nearest neighbors
Section titled “M37-C03 · Measure bias and variance of k-nearest neighbors”Write the code: simulate 100 training sets of 40 points on the grid np.linspace(0, 3, 40) with the target np.sin(2 * x) + 0.5 * x plus normal noise (standard deviation 0.3, rng = np.random.default_rng(42)). For KNeighborsRegressor with k = 1, 5, 15 and 35, compute bias² and variance on 100 evaluation points between 0 and 3. Print a table.
k bias^2 variance total 1 0.0016 0.0896 0.0912 5 0.0069 0.0178 0.024715 0.0875 0.0061 0.093635 0.2185 0.0025 0.2209from sklearn.neighbors import KNeighborsRegressor
rng = np.random.default_rng(42)x_train = np.linspace(0, 3, 40).reshape(-1, 1)x_eval = np.linspace(0, 3, 100).reshape(-1, 1)
def true_curve(x): return np.sin(2 * x) + 0.5 * x
# TODO: for each k, fit on 100 noisy draws and collect predictions at x_eval# TODO: bias^2 = mean((mean prediction - truth)^2), variance = mean(var of predictions)Hint 1
Stack the 100 prediction arrays with np.array(preds). It has shape (100, 100): one row per training set.
Hint 2
preds.mean(axis=0) is the average prediction at each point. preds.var(axis=0) is the variance at each point. Average both over the points.
Solution
from sklearn.neighbors import KNeighborsRegressor
rng = np.random.default_rng(42)x_train = np.linspace(0, 3, 40).reshape(-1, 1)x_eval = np.linspace(0, 3, 100).reshape(-1, 1)
def true_curve(x): return np.sin(2 * x) + 0.5 * x
truth = true_curve(x_eval.ravel())rows = []for k in [1, 5, 15, 35]: preds = [] for _ in range(100): y_draw = true_curve(x_train.ravel()) + rng.normal(0, 0.3, 40) model = KNeighborsRegressor(n_neighbors=k).fit(x_train, y_draw) preds.append(model.predict(x_eval)) preds = np.array(preds) rows.append( { "k": k, "bias^2": ((preds.mean(axis=0) - truth) ** 2).mean(), "variance": preds.var(axis=0).mean(), } )table = pd.DataFrame(rows)table["total"] = table["bias^2"] + table["variance"]print(table.to_string(index=False, float_format="{:.4f}".format))
assert table["variance"].is_monotonic_decreasingassert table["bias^2"].is_monotonic_increasing k bias^2 variance total 1 0.0016 0.0896 0.0912 5 0.0069 0.0178 0.024715 0.0875 0.0061 0.093635 0.2185 0.0025 0.2209How it works:
- With
k=1, the prediction copies the nearest noisy point. Its variance is close to the noise variance 0.09, and its bias is tiny. - With
k=35, each prediction averages most of the 40 points. The variance falls to almost nothing, but the average flattens the wave and the bias explodes. - The total (without the constant noise) is smallest at a medium
k. This is the same trade-off as the polynomial degree in the lesson, with the complexity knob reversed.
M37-C04 · Group leakage with a nearest-neighbor model
Section titled “M37-C04 · Group leakage with a nearest-neighbor model”Write the code: join the order lines of data/sales.csv with the customer table and predict churned per line with a 1-nearest-neighbor classifier (scaled age, tenure_months, monthly_charges and unit_price). Use the first 6,000 lines for speed. Compare the ROC-AUC of KFold(3, shuffle=True, random_state=42) with GroupKFold(3, shuffle=True, random_state=42) grouped by customer.
lines 6000, customers 1559KFold ROC-AUC 0.817GroupKFold ROC-AUC 0.526from sklearn.model_selection import GroupKFold, KFold, cross_val_scorefrom sklearn.neighbors import KNeighborsClassifier
sales = pd.read_csv("data/sales.csv", usecols=["customer_id", "unit_price"])lines = sales.head(6000).merge(customers, on="customer_id", how="left")features = ["age", "tenure_months", "monthly_charges", "unit_price"]# TODO: X_lines, y_lines, groups# TODO: score a scaled 1-NN with KFold and with GroupKFoldHint 1
make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=1)).
Hint 2
Pass groups=groups to cross_val_score only for the GroupKFold run.
Solution
from sklearn.model_selection import GroupKFold, KFold, cross_val_scorefrom sklearn.neighbors import KNeighborsClassifier
sales = pd.read_csv("data/sales.csv", usecols=["customer_id", "unit_price"])lines = sales.head(6000).merge(customers, on="customer_id", how="left")features = ["age", "tenure_months", "monthly_charges", "unit_price"]X_lines, y_lines, groups = lines[features], lines["churned"], lines["customer_id"]one_nn = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=1))naive = cross_val_score( one_nn, X_lines, y_lines, scoring="roc_auc", cv=KFold(n_splits=3, shuffle=True, random_state=42),)grouped = cross_val_score( one_nn, X_lines, y_lines, groups=groups, scoring="roc_auc", cv=GroupKFold(n_splits=3, shuffle=True, random_state=42),)print(f"lines {len(lines)}, customers {groups.nunique()}")print(f"KFold ROC-AUC {naive.mean():.3f}")print(f"GroupKFold ROC-AUC {grouped.mean():.3f}")
assert naive.mean() - grouped.mean() > 0.2lines 6000, customers 1559KFold ROC-AUC 0.817GroupKFold ROC-AUC 0.526How it works:
- A 1-nearest-neighbor model finds the closest training line. With
KFold, that line usually belongs to the same customer (same age, tenure and charges), so the model copies the customer’s own label. - With
GroupKFold, the nearest line always belongs to another customer, and the score shows what the model knows about churn in general: much less. - The more a model can memorize, the larger the gap. A 1-NN model or an unpruned tree is a good leakage detector.
M37-C05 · Walk-forward validation of daily units
Section titled “M37-C05 · Walk-forward validation of daily units”Write the code: aggregate data/sales.csv to daily units sold. Build lag_7, lag_14 and day_of_week, drop the rows with missing lags and evaluate on TimeSeriesSplit(n_splits=4, test_size=60). For each split, print the MAE of the seasonal-naive forecast (predict lag_7) and of a Ridge model on the three features.
split 0 (to 2024-07-04): naive 13.3, ridge 10.1split 1 (to 2024-09-02): naive 14.7, ridge 10.7split 2 (to 2024-11-01): naive 14.1, ridge 10.3split 3 (to 2024-12-31): naive 29.0, ridge 26.9mean MAE: naive 17.8, ridge 14.5from sklearn.linear_model import Ridgefrom sklearn.metrics import mean_absolute_errorfrom sklearn.model_selection import TimeSeriesSplit
sales = pd.read_csv("data/sales.csv", usecols=["order_date", "quantity"])daily = sales.groupby("order_date")["quantity"].sum().rename("units").reset_index()# TODO: lag_7, lag_14, day_of_week; dropna# TODO: loop over the splits; MAE of lag_7 and of RidgeHint 1
pd.to_datetime(daily["order_date"]).dt.day_of_week gives 0 for Monday. daily["units"].shift(7) is the value one week earlier.
Hint 2
Inside the loop, fit Ridge() on X.iloc[train_idx] and score on X.iloc[valid_idx]. The naive forecast is X.iloc[valid_idx]["lag_7"].
Solution
from sklearn.linear_model import Ridgefrom sklearn.metrics import mean_absolute_errorfrom sklearn.model_selection import TimeSeriesSplit
sales = pd.read_csv("data/sales.csv", usecols=["order_date", "quantity"])daily = sales.groupby("order_date")["quantity"].sum().rename("units").reset_index()daily = daily.assign( lag_7=daily["units"].shift(7), lag_14=daily["units"].shift(14), day_of_week=pd.to_datetime(daily["order_date"]).dt.day_of_week,).dropna()X_daily = daily[["lag_7", "lag_14", "day_of_week"]]y_daily = daily["units"]results = []for fold, (train_idx, valid_idx) in enumerate( TimeSeriesSplit(n_splits=4, test_size=60).split(X_daily)): y_valid = y_daily.iloc[valid_idx] naive_mae = mean_absolute_error(y_valid, X_daily.iloc[valid_idx]["lag_7"]) ridge = Ridge().fit(X_daily.iloc[train_idx], y_daily.iloc[train_idx]) ridge_mae = mean_absolute_error(y_valid, ridge.predict(X_daily.iloc[valid_idx])) results.append((naive_mae, ridge_mae)) end = daily["order_date"].iloc[valid_idx[-1]] print(f"split {fold} (to {end}): naive {naive_mae:.1f}, ridge {ridge_mae:.1f}")naive_mean, ridge_mean = np.mean(results, axis=0)print(f"mean MAE: naive {naive_mean:.1f}, ridge {ridge_mean:.1f}")
assert len(results) == 4split 0 (to 2024-07-04): naive 13.3, ridge 10.1split 1 (to 2024-09-02): naive 14.7, ridge 10.7split 2 (to 2024-11-01): naive 14.1, ridge 10.3split 3 (to 2024-12-31): naive 29.0, ridge 26.9mean MAE: naive 17.8, ridge 14.5How it works:
groupby("order_date")sums the units per day. The rows stay in date order, whichTimeSeriesSplitrequires.- Each split trains on all earlier days and validates on the next 60 days. The last split covers November and December 2024 with the promo peaks.
- Ridge combines two lags and learns that a weighted average is smoother than one noisy lag. For simplicity,
day_of_weekenters as one number from 0 to 6, so Ridge can only fit a straight-line weekday effect. One-hot encoding it (module 33) lets each weekday get its own level. Always report a naive baseline next to a model: a forecast that cannot beat “same day last week” is not worth deploying.
M37-C06 · Fix the bug: parameter names in a pipeline
Section titled “M37-C06 · Fix the bug: parameter names in a pipeline”Fix the bug: the search below raises ValueError: Invalid parameter 'C' for estimator Pipeline(...). Fix the parameter grid, then print the best C and its cross-validated ROC-AUC.
best: {'logisticregression__C': 10}CV ROC-AUC: 0.785C names: ['logisticregression__C']from sklearn.model_selection import GridSearchCV
pipe = make_pipeline( SimpleImputer(strategy="median"), StandardScaler(), LogisticRegression())search = GridSearchCV(pipe, {"C": [0.001, 0.01, 0.1, 1, 10]}, cv=cv3, scoring="roc_auc")search.fit(X_train[NUMERIC], y_train)Hint 1
A pipeline exposes the parameters of its steps as <step name>__<parameter>.
Hint 2
make_pipeline names the step logisticregression. Print pipe.get_params().keys() to see every valid name.
Solution
from sklearn.model_selection import GridSearchCV
pipe = make_pipeline( SimpleImputer(strategy="median"), StandardScaler(), LogisticRegression())param_grid = {"logisticregression__C": [0.001, 0.01, 0.1, 1, 10]}search = GridSearchCV(pipe, param_grid, cv=cv3, scoring="roc_auc", n_jobs=1)search.fit(X_train[NUMERIC], y_train)print("best:", search.best_params_)print(f"CV ROC-AUC: {search.best_score_:.3f}")print("C names:", [name for name in pipe.get_params() if name.endswith("__C")])
assert "logisticregression__C" in search.best_params_best: {'logisticregression__C': 10}CV ROC-AUC: 0.785C names: ['logisticregression__C']How it works:
- The pipeline itself has no parameter
C. Its steplogisticregressionhas one, so the full name islogisticregression__C. get_params()lists every settable name, including nested ones such assimpleimputer__strategy. Filtering it is the fastest way to find the right spelling.- With a
Pipeline([("model", LogisticRegression())]), the name would bemodel__C. Short step names make grids easier to read. - The best
Cis the largest value in the grid. In a real project, widen the grid (for example up to 1,000) before you trust it.
M37-C07 · Random search over C with a log-uniform distribution
Section titled “M37-C07 · Random search over C with a log-uniform distribution”Write the code: tune a logistic regression on all churn features (make_preprocess() then LogisticRegression(max_iter=1000)) with RandomizedSearchCV. Sample C from loguniform(1e-3, 1e2) and class_weight from [None, "balanced"], with n_iter=12, cv=cv3, scoring="average_precision" and random_state=42. Print the best parameters, the CV score and the test average precision.
best C: 0.9847best class_weight: NoneCV average precision: 0.546test average precision: 0.557from scipy.stats import loguniformfrom sklearn.metrics import average_precision_scorefrom sklearn.model_selection import RandomizedSearchCV
pipe = make_pipeline(make_preprocess(), LogisticRegression(max_iter=1000))# TODO: param_distributions with loguniform C and a class_weight list# TODO: fit, print the best parameters and scoresHint 1
The parameter names are logisticregression__C and logisticregression__class_weight.
Hint 2
Average precision needs probabilities: average_precision_score(y_test, search.predict_proba(X_test)[:, 1]).
Solution
from scipy.stats import loguniformfrom sklearn.metrics import average_precision_scorefrom sklearn.model_selection import RandomizedSearchCV
pipe = make_pipeline(make_preprocess(), LogisticRegression(max_iter=1000))param_dist = { "logisticregression__C": loguniform(1e-3, 1e2), "logisticregression__class_weight": [None, "balanced"],}search = RandomizedSearchCV( pipe, param_dist, n_iter=12, cv=cv3, scoring="average_precision", random_state=42, n_jobs=1,).fit(X_train, y_train)best_c = search.best_params_["logisticregression__C"]print(f"best C: {best_c:.4f}")print("best class_weight:", search.best_params_["logisticregression__class_weight"])print(f"CV average precision: {search.best_score_:.3f}")test_ap = average_precision_score(y_test, search.predict_proba(X_test)[:, 1])print(f"test average precision: {test_ap:.3f}")
assert 1e-3 <= best_c <= 1e2best C: 0.9847best class_weight: NoneCV average precision: 0.546test average precision: 0.557How it works:
loguniformspreads the 12 draws ofCover five orders of magnitude, so small and large values both get tried.- Average precision summarizes the precision–recall curve. It suits a rare positive class better than accuracy.
class_weightchanges the probabilities but hardly the ranking of customers, so ranking metrics such as average precision and ROC-AUC move little betweenNoneand"balanced". Either value can win by a small margin.
M37-C08 · Grid or random search on the same budget?
Section titled “M37-C08 · Grid or random search on the same budget?”Choose a method and justify it: tune a decision tree on the numeric churn features with 9 candidates each way. The grid tries max_depth in (3, 6, 9) and min_samples_leaf in (1, 30, 90). The random search draws max_depth from randint(2, 12) and min_samples_leaf from randint(1, 150) with n_iter=9. Print each best score and the number of distinct values each search tried per hyperparameter. Which search would you use for a model with five hyperparameters?
grid best 0.773 {'max_depth': 6, 'min_samples_leaf': 90} distinct depths 3, leaf sizes 3random best 0.783 {'max_depth': 9, 'min_samples_leaf': 131} distinct depths 6, leaf sizes 9from scipy.stats import randintfrom sklearn.model_selection import GridSearchCV, RandomizedSearchCVfrom sklearn.tree import DecisionTreeClassifier
tree = DecisionTreeClassifier(random_state=42)# TODO: run both searches with cv=cv3 and scoring="roc_auc"# TODO: count the distinct values in cv_results_["param_max_depth"], ...Hint 1
Both searches take the same cv, scoring and n_jobs. Give the random search random_state=42.
Hint 2
len(set(search.cv_results_["param_max_depth"])) counts the distinct depths tried.
Solution
from scipy.stats import randintfrom sklearn.model_selection import GridSearchCV, RandomizedSearchCVfrom sklearn.tree import DecisionTreeClassifier
tree = DecisionTreeClassifier(random_state=42)common = {"cv": cv3, "scoring": "roc_auc", "n_jobs": 1}grid = GridSearchCV( tree, {"max_depth": [3, 6, 9], "min_samples_leaf": [1, 30, 90]}, **common).fit(X_train[NUMERIC], y_train)rand = RandomizedSearchCV( tree, {"max_depth": randint(2, 12), "min_samples_leaf": randint(1, 150)}, n_iter=9, random_state=42, **common,).fit(X_train[NUMERIC], y_train)for name, search in [("grid", grid), ("random", rand)]: depths = len(set(search.cv_results_["param_max_depth"])) leaves = len(set(search.cv_results_["param_min_samples_leaf"])) print(f"{name:<6} best {search.best_score_:.3f} {search.best_params_}" f" distinct depths {depths}, leaf sizes {leaves}")
assert len(set(rand.cv_results_["param_min_samples_leaf"])) > 3grid best 0.773 {'max_depth': 6, 'min_samples_leaf': 90} distinct depths 3, leaf sizes 3random best 0.783 {'max_depth': 9, 'min_samples_leaf': 131} distinct depths 6, leaf sizes 9How it works:
- Both searches fit 9 candidates × 3 folds. The grid tries only 3 values of each knob. The random search tries up to 9 distinct values of each.
- The random search wins here because it tried leaf sizes above 90, outside the grid. The grid can only find what you put into it.
- For five hyperparameters, a grid with 3 values each needs 243 candidates. A random search keeps any budget you choose and still explores each knob widely. Choose random search (or Optuna), and use a grid only for one or two knobs or for a final fine-tuning around a known optimum.
M37-C09 · Tune k-nearest neighbors with Optuna
Section titled “M37-C09 · Tune k-nearest neighbors with Optuna”Write the code: tune a KNN classifier on the numeric churn features (impute, scale, KNN) with Optuna. Search n_neighbors from 1 to 150 on a log scale, weights in ["uniform", "distance"] and p in [1, 2] (Manhattan or Euclidean distance). Use TPESampler(seed=42), 15 trials, cv=cv3 and ROC-AUC. Print the best parameters and score.
best params: {'n_neighbors': 137, 'weights': 'uniform', 'p': 1}best CV ROC-AUC: 0.796trials run: 15import optunafrom sklearn.model_selection import cross_val_scorefrom sklearn.neighbors import KNeighborsClassifier
optuna.logging.set_verbosity(optuna.logging.WARNING)
def objective(trial): # TODO: suggest the three hyperparameters # TODO: build the pipeline and return the mean CV ROC-AUC ...
# TODO: create a study with TPESampler(seed=42) and run 15 trialsHint 1
trial.suggest_int("n_neighbors", 1, 150, log=True) and trial.suggest_categorical("p", [1, 2]).
Hint 2
Build a new pipeline inside the objective: make_pipeline(SimpleImputer(strategy="median"), StandardScaler(), KNeighborsClassifier(**params)).
Solution
import optunafrom sklearn.model_selection import cross_val_scorefrom sklearn.neighbors import KNeighborsClassifier
optuna.logging.set_verbosity(optuna.logging.WARNING)
def objective(trial): params = { "n_neighbors": trial.suggest_int("n_neighbors", 1, 150, log=True), "weights": trial.suggest_categorical("weights", ["uniform", "distance"]), "p": trial.suggest_categorical("p", [1, 2]), } model = make_pipeline( SimpleImputer(strategy="median"), StandardScaler(), KNeighborsClassifier(**params), ) scores = cross_val_score( model, X_train[NUMERIC], y_train, cv=cv3, scoring="roc_auc" ) return scores.mean()
study = optuna.create_study( direction="maximize", sampler=optuna.samplers.TPESampler(seed=42))study.optimize(objective, n_trials=15)print("best params:", study.best_params)print(f"best CV ROC-AUC: {study.best_value:.3f}")print("trials run:", len(study.trials))
assert study.best_params["n_neighbors"] > 10best params: {'n_neighbors': 137, 'weights': 'uniform', 'p': 1}best CV ROC-AUC: 0.796trials run: 15How it works:
log=Truegives smallkvalues as many trials as large ones, which matters because the effect ofkis roughly logarithmic.- The parameter names inside the trial (
"n_neighbors") are free labels. The objective maps them to the estimator’s arguments. - The best trials use a large
k, consistent with the validation curve of exercise C01.
M37-C10 · Find the most profitable threshold
Section titled “M37-C10 · Find the most profitable threshold”Write the code: get out-of-fold churn probabilities on the training set with cross_val_predict (make_preprocess() + logistic regression, cv=cv3). A retention call costs 40 and saves a churner worth 200, so profit = 160 × TP − 40 × FP. Try the thresholds 0.05, 0.10, …, 0.90 and print the best threshold with its profit, and the profit at 0.5.
best threshold 0.2: profit 53360threshold 0.5: profit 29480from sklearn.model_selection import cross_val_predict
model = make_pipeline(make_preprocess(), LogisticRegression(max_iter=1000))# TODO: out-of-fold probabilities with method="predict_proba"# TODO: profit for each threshold in np.arange(0.05, 0.95, 0.05)Hint 1
cross_val_predict(model, X_train, y_train, cv=cv3, method="predict_proba")[:, 1].
Hint 2
For one threshold: pred = proba >= t, tp = (pred & (y_train == 1)).sum(), fp = (pred & (y_train == 0)).sum().
Solution
from sklearn.model_selection import cross_val_predict
model = make_pipeline(make_preprocess(), LogisticRegression(max_iter=1000))proba = cross_val_predict(model, X_train, y_train, cv=cv3, method="predict_proba")[:, 1]actual = y_train.to_numpy() == 1
def profit(threshold): pred = proba >= threshold tp = (pred & actual).sum() fp = (pred & ~actual).sum() return 160 * tp - 40 * fp
thresholds = np.round(np.arange(0.05, 0.95, 0.05), 2)profits = pd.Series([profit(t) for t in thresholds], index=thresholds)print(f"best threshold {profits.idxmax()}: profit {profits.max()}")print(f"threshold 0.5: profit {profits.loc[0.5]}")
assert 0.1 <= profits.idxmax() <= 0.3best threshold 0.2: profit 53360threshold 0.5: profit 29480How it works:
cross_val_predictreturns, for every training row, the probability from the model that did not train on that row. These out-of-fold probabilities behave like predictions on new data.- The profit curve peaks near the break-even probability 40 / 200 = 0.2, far below the default 0.5.
- Choosing the threshold on out-of-fold predictions keeps the test set clean for the final check.
Alternative: TunedThresholdClassifierCV(model, scoring=make_scorer(...), cv=cv3) runs the same search, then refits the model on all rows and applies the threshold in predict.
M37-C11 · Fix a threshold inside a pipeline
Section titled “M37-C11 · Fix a threshold inside a pipeline”Write the code: wrap the churn logistic regression in FixedThresholdClassifier with a threshold of 0.3. Fit both the plain and the wrapped model on the training set, and print precision, recall and the share of flagged customers on the test set.
threshold 0.5: precision 0.664, recall 0.303, flagged 8.8%threshold 0.3: precision 0.460, recall 0.598, flagged 25.0%from sklearn.metrics import precision_score, recall_scorefrom sklearn.model_selection import FixedThresholdClassifier
base = make_pipeline(make_preprocess(), LogisticRegression(max_iter=1000))# TODO: wrapped = FixedThresholdClassifier(...)# TODO: fit both and print the test metricsHint 1
FixedThresholdClassifier(base, threshold=0.3) fits a clone of base when you call fit.
Hint 2
The flagged share is pred.mean().
Solution
from sklearn.metrics import precision_score, recall_scorefrom sklearn.model_selection import FixedThresholdClassifier
base = make_pipeline(make_preprocess(), LogisticRegression(max_iter=1000))wrapped = FixedThresholdClassifier(base, threshold=0.3)recalls = {}for name, model in [("threshold 0.5", base), ("threshold 0.3", wrapped)]: pred = model.fit(X_train, y_train).predict(X_test) recalls[name] = recall_score(y_test, pred) print(f"{name}: precision {precision_score(y_test, pred):.3f}," f" recall {recalls[name]:.3f}, flagged {pred.mean():.1%}")
assert recalls["threshold 0.3"] > recalls["threshold 0.5"]threshold 0.5: precision 0.664, recall 0.303, flagged 8.8%threshold 0.3: precision 0.460, recall 0.598, flagged 25.0%How it works:
FixedThresholdClassifierchanges onlypredict.predict_probareturns the same probabilities as the base model.- Lowering the threshold to 0.3 flags more customers: recall goes up, precision goes down.
- The wrapper is an estimator, so you can save it with joblib and serve it. The threshold travels with the model instead of living in a separate script.
M37-C12 · Fix the bug: oversampling before cross-validation
Section titled “M37-C12 · Fix the bug: oversampling before cross-validation”Fix the bug: the code below reports a cross-validated recall far above what the model achieves on new customers. Move the oversampling into an imbalanced-learn pipeline, and print the leaky recall, the fixed recall and the test recall.
leaky CV recall 0.845safe CV recall 0.453test recall 0.494from imblearn.over_sampling import RandomOverSamplerfrom sklearn.model_selection import cross_val_scorefrom sklearn.tree import DecisionTreeClassifier
X_num = SimpleImputer(strategy="median").fit_transform(X_train[NUMERIC])X_res, y_res = RandomOverSampler(random_state=42).fit_resample(X_num, y_train)tree = DecisionTreeClassifier(min_samples_leaf=5, random_state=42)leaky = cross_val_score(tree, X_res, y_res, cv=cv3, scoring="recall") # bugprint(f"leaky CV recall {leaky.mean():.3f}")Hint 1
RandomOverSampler copies churner rows. A copy and its original can land in different folds.
Hint 2
from imblearn.pipeline import make_pipeline as make_imb_pipeline, then make_imb_pipeline(SimpleImputer(...), RandomOverSampler(...), tree) on the raw X_train[NUMERIC].
Solution
from imblearn.over_sampling import RandomOverSamplerfrom imblearn.pipeline import make_pipeline as make_imb_pipelinefrom sklearn.metrics import recall_scorefrom sklearn.model_selection import cross_val_scorefrom sklearn.tree import DecisionTreeClassifier
X_num = SimpleImputer(strategy="median").fit_transform(X_train[NUMERIC])X_res, y_res = RandomOverSampler(random_state=42).fit_resample(X_num, y_train)tree = DecisionTreeClassifier(min_samples_leaf=5, random_state=42)leaky = cross_val_score(tree, X_res, y_res, cv=cv3, scoring="recall")
safe_model = make_imb_pipeline( SimpleImputer(strategy="median"), RandomOverSampler(random_state=42), tree)safe = cross_val_score(safe_model, X_train[NUMERIC], y_train, cv=cv3, scoring="recall")test_recall = recall_score( y_test, safe_model.fit(X_train[NUMERIC], y_train).predict(X_test[NUMERIC]))print(f"leaky CV recall {leaky.mean():.3f}")print(f"safe CV recall {safe.mean():.3f}")print(f"test recall {test_recall:.3f}")
assert leaky.mean() - safe.mean() > 0.2assert abs(safe.mean() - test_recall) < 0.1leaky CV recall 0.845safe CV recall 0.453test recall 0.494How it works:
- In the leaky version, each churner appears about four times after oversampling. The validation fold contains exact copies of training rows, and a tree with small leaves recognizes them.
- The imbalanced-learn pipeline calls
fit_resampleon the training folds only. Validation folds keep their original rows and their real class balance. - The safe CV recall and the test recall agree. That agreement is the sign of an honest evaluation.
M37-C13 · Refactor a manual tuning loop into GridSearchCV
Section titled “M37-C13 · Refactor a manual tuning loop into GridSearchCV”Refactor: the procedural code below tunes n_neighbors of a KNN regressor for house prices with one train/validation split. Replace it with a GridSearchCV over the same values with KFold(5, shuffle=True, random_state=42) and scoring="neg_root_mean_squared_error". The target is np.log(price). Print the best k and the CV RMSE on the log scale.
best k: 20CV RMSE (log price): 0.1968RMSE by k: [0.2126, 0.201, 0.1976, 0.1968, 0.2021]from sklearn.metrics import root_mean_squared_errorfrom sklearn.neighbors import KNeighborsRegressor
houses = pd.read_csv("data/houses.csv")cols = ["sqft", "bedrooms", "bathrooms", "year_built", "condition", "distance_to_center_km", "school_rating"]X_h = houses[cols]y_h = np.log(houses["price"])X_a, X_b, y_a, y_b = train_test_split(X_h, y_h, test_size=0.25, random_state=42)best_k, best_rmse = None, float("inf")for k in [3, 5, 10, 20, 40]: imputer = SimpleImputer(strategy="median").fit(X_a) scaler = StandardScaler().fit(imputer.transform(X_a)) model = KNeighborsRegressor(n_neighbors=k) model.fit(scaler.transform(imputer.transform(X_a)), y_a) pred = model.predict(scaler.transform(imputer.transform(X_b))) rmse = root_mean_squared_error(y_b, pred) if rmse < best_rmse: best_k, best_rmse = k, rmseprint(best_k, round(best_rmse, 4))Hint 1
Put the imputer, the scaler and the model into one make_pipeline. The search refits all three steps on each training fold.
Hint 2
The score is negated: the RMSE is -search.best_score_.
Solution
from sklearn.model_selection import GridSearchCV, KFoldfrom sklearn.neighbors import KNeighborsRegressor
houses = pd.read_csv("data/houses.csv")cols = ["sqft", "bedrooms", "bathrooms", "year_built", "condition", "distance_to_center_km", "school_rating"]X_h = houses[cols]y_h = np.log(houses["price"])knn = make_pipeline( SimpleImputer(strategy="median"), StandardScaler(), KNeighborsRegressor())search = GridSearchCV( knn, {"kneighborsregressor__n_neighbors": [3, 5, 10, 20, 40]}, cv=KFold(n_splits=5, shuffle=True, random_state=42), scoring="neg_root_mean_squared_error", n_jobs=1,).fit(X_h, y_h)print("best k:", search.best_params_["kneighborsregressor__n_neighbors"])print(f"CV RMSE (log price): {-search.best_score_:.4f}")rmse_by_k = -search.cv_results_["mean_test_score"]print("RMSE by k:", rmse_by_k.round(4).tolist())
assert -search.best_score_ == rmse_by_k.min()best k: 20CV RMSE (log price): 0.1968RMSE by k: [0.2126, 0.201, 0.1976, 0.1968, 0.2021]How it works:
- The pipeline replaces three manual
fit/transformcalls and guarantees that the imputer and scaler learn from training folds only. - Five folds average out the luck of one split, so the choice of
kis more stable. - Scikit-learn maximizes scores, so the RMSE comes negated. An RMSE of about 0.20 on log price means typical errors of roughly 20%.
Alternative: cross_val_score in a loop over k also works, but you would rebuild the bookkeeping that GridSearchCV already does (best_params_, cv_results_, the refit).
M37-C14 · Interpret nested cross-validation results
Section titled “M37-C14 · Interpret nested cross-validation results”Interpret a result: on the breast cancer dataset (load_breast_cancer), tune an SVM (StandardScaler + SVC) over C in (0.1, 1, 10) and gamma in (0.001, 0.01, 0.1) with an inner StratifiedKFold(3), and evaluate the search with an outer StratifiedKFold(5) (both shuffled, random_state=42). Print best_score_ of the search fitted on all rows, the nested mean ± standard deviation and the optimism. Then answer: which number would you report, and why?
best_score_ (non-nested): 0.9789nested accuracy: 0.9754 +/- 0.0151optimism: +0.0035from sklearn.datasets import load_breast_cancerfrom sklearn.model_selection import GridSearchCV, cross_val_scorefrom sklearn.svm import SVC
X_bc, y_bc = load_breast_cancer(return_X_y=True)# TODO: inner and outer splitters, the search, its best_score_ and nested scoresHint 1
search = GridSearchCV(make_pipeline(StandardScaler(), SVC()), grid, cv=inner). Fit it once for best_score_, and pass it unfitted to cross_val_score(search, X_bc, y_bc, cv=outer).
Hint 2
The optimism is best_score_ - nested.mean().
Solution
from sklearn.datasets import load_breast_cancerfrom sklearn.model_selection import GridSearchCV, cross_val_scorefrom sklearn.svm import SVC
X_bc, y_bc = load_breast_cancer(return_X_y=True)inner = StratifiedKFold(n_splits=3, shuffle=True, random_state=42)outer = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)grid = {"svc__C": [0.1, 1, 10], "svc__gamma": [0.001, 0.01, 0.1]}search = GridSearchCV( make_pipeline(StandardScaler(), SVC()), grid, cv=inner, n_jobs=1)best_score = search.fit(X_bc, y_bc).best_score_nested = cross_val_score(search, X_bc, y_bc, cv=outer)print(f"best_score_ (non-nested): {best_score:.4f}")print(f"nested accuracy: {nested.mean():.4f} +/- {nested.std():.4f}")print(f"optimism: {best_score - nested.mean():+.4f}")
assert nested.mean() > 0.95best_score_ (non-nested): 0.9789nested accuracy: 0.9754 +/- 0.0151optimism: +0.0035How it works:
best_score_is the best of 9 candidates scored on the same folds that chose it. The nested estimate scores each tuned model on an outer fold that its search never saw.- Here the optimism is small compared with the spread of the outer scores: with only 9 candidates, the selection bias is modest. The difference is within the noise.
- Report the nested estimate with its spread (about 97–98% ± 1–2 points). It answers the question “how accurate will this tuning procedure be on new patients?”.
best_score_answers a different question: “which candidate looked best on these folds?”.
Challenge
Section titled “Challenge”M37-X01 · Compare two model families with nested cross-validation
Section titled “M37-X01 · Compare two model families with nested cross-validation”Choose a method and justify it: the retention team must choose between a tuned logistic regression and a tuned decision tree for churn. On X_train, run nested CV for both: the logistic regression (make_preprocess() + LogisticRegression(max_iter=1000)) with C in (0.01, 0.1, 1, 10), and the tree (make_preprocess() + DecisionTreeClassifier(random_state=42)) with max_depth in (4, 6, 8) and min_samples_leaf in (25, 50, 100). Inner cv3, outer StratifiedKFold(5, shuffle=True, random_state=42), ROC-AUC. Print each nested mean ± std, pick the winner, refit its search on X_train and print its test ROC-AUC.
logistic nested ROC-AUC 0.812 +/- 0.012tree nested ROC-AUC 0.809 +/- 0.012winner: logistic with {'model__C': 10}test ROC-AUC: 0.813from sklearn.metrics import roc_auc_scorefrom sklearn.model_selection import GridSearchCV, cross_val_scorefrom sklearn.pipeline import Pipelinefrom sklearn.tree import DecisionTreeClassifier
outer = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)searches = { # TODO: "logistic": GridSearchCV(...), "tree": GridSearchCV(...)}# TODO: nested scores for each, the winner and its test ROC-AUCHint 1
Use Pipeline([("prep", make_preprocess()), ("model", ...)]) for both, so the grids read model__C, model__max_depth and so on.
Hint 2
cross_val_score(search, X_train, y_train, cv=outer, scoring="roc_auc") runs the whole inner search 5 times.
Hint 3
The winner is max(nested, key=lambda name: nested[name].mean()). Then searches[winner].fit(X_train, y_train).
Solution
from sklearn.metrics import roc_auc_scorefrom sklearn.model_selection import GridSearchCV, cross_val_scorefrom sklearn.pipeline import Pipelinefrom sklearn.tree import DecisionTreeClassifier
outer = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)searches = { "logistic": GridSearchCV( Pipeline([("prep", make_preprocess()), ("model", LogisticRegression(max_iter=1000))]), {"model__C": [0.01, 0.1, 1, 10]}, cv=cv3, scoring="roc_auc", n_jobs=1, ), "tree": GridSearchCV( Pipeline([("prep", make_preprocess()), ("model", DecisionTreeClassifier(random_state=42))]), {"model__max_depth": [4, 6, 8], "model__min_samples_leaf": [25, 50, 100]}, cv=cv3, scoring="roc_auc", n_jobs=1, ),}nested = {}for name, search in searches.items(): nested[name] = cross_val_score( search, X_train, y_train, cv=outer, scoring="roc_auc" ) print(f"{name:<8} nested ROC-AUC {nested[name].mean():.3f}" f" +/- {nested[name].std():.3f}")winner = max(nested, key=lambda name: nested[name].mean())final = searches[winner].fit(X_train, y_train)test_auc = roc_auc_score(y_test, final.predict_proba(X_test)[:, 1])print(f"winner: {winner} with {final.best_params_}")print(f"test ROC-AUC: {test_auc:.3f}")
assert winner == "logistic"logistic nested ROC-AUC 0.812 +/- 0.012tree nested ROC-AUC 0.809 +/- 0.012winner: logistic with {'model__C': 10}test ROC-AUC: 0.813How it works:
- Each family gets its own search, and each search is evaluated as a whole by the outer loop. Both families are tuned with the same care, so the comparison is fair.
- Comparing the two
best_score_values instead would favor the family with more candidates, because more candidates mean more selection bias. - The two families are tied within the noise: 0.003 apart, with an outer spread of 0.012. When scores tie, choose the simpler model. The logistic regression wins the tie-break and also gives coefficients that the team can read. The test score confirms the nested estimate.
M37-X02 · Tune a traffic forecaster and test it against a baseline
Section titled “M37-X02 · Tune a traffic forecaster and test it against a baseline”Write the code: on data/web_traffic.csv, interpolate visits and build lag_1, lag_7, day_of_week and marketing_spend as features. Keep the last 90 days as the test period. Tune a RandomForestRegressor(n_estimators=50, random_state=42, n_jobs=1) with GridSearchCV over min_samples_leaf (1, 5, 20) and max_features (0.5, 1.0), using TimeSeriesSplit(n_splits=4, test_size=90) and MAE. Print the best parameters and CV MAE, then the test MAE of the tuned forest and of the naive forecast lag_7.
best: {'max_features': 1.0, 'min_samples_leaf': 5} CV MAE 372test period 2024-10-03 to 2024-12-31test MAE: forest 725, naive lag_7 451from sklearn.ensemble import RandomForestRegressorfrom sklearn.metrics import mean_absolute_errorfrom sklearn.model_selection import GridSearchCV, TimeSeriesSplit
traffic = pd.read_csv("data/web_traffic.csv", parse_dates=["date"])traffic["visits"] = traffic["visits"].interpolate()# TODO: lag features, dropna, split off the last 90 days (no shuffling)# TODO: GridSearchCV with TimeSeriesSplit; test MAE vs the lag_7 baselineHint 1
X_past, X_future = X.iloc[:-90], X.iloc[-90:] keeps the time order. Never use train_test_split with shuffling here.
Hint 2
Pass cv=TimeSeriesSplit(n_splits=4, test_size=90) and scoring="neg_mean_absolute_error" to GridSearchCV.
Solution
from sklearn.ensemble import RandomForestRegressorfrom sklearn.metrics import mean_absolute_errorfrom sklearn.model_selection import GridSearchCV, TimeSeriesSplit
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()features = ["lag_1", "lag_7", "day_of_week", "marketing_spend"]X_past, X_future = traffic[features].iloc[:-90], traffic[features].iloc[-90:]y_past, y_future = traffic["visits"].iloc[:-90], traffic["visits"].iloc[-90:]search = GridSearchCV( RandomForestRegressor(n_estimators=50, random_state=42, n_jobs=1), {"min_samples_leaf": [1, 5, 20], "max_features": [0.5, 1.0]}, cv=TimeSeriesSplit(n_splits=4, test_size=90), scoring="neg_mean_absolute_error", n_jobs=1,).fit(X_past, y_past)forest_mae = mean_absolute_error(y_future, search.predict(X_future))naive_mae = mean_absolute_error(y_future, X_future["lag_7"])print("best:", search.best_params_, f"CV MAE {-search.best_score_:.0f}")test_dates = traffic["date"].iloc[-90:]print(f"test period {test_dates.iloc[0].date()} to {test_dates.iloc[-1].date()}")print(f"test MAE: forest {forest_mae:.0f}, naive lag_7 {naive_mae:.0f}")
assert forest_mae > naive_maebest: {'max_features': 1.0, 'min_samples_leaf': 5} CV MAE 372test period 2024-10-03 to 2024-12-31test MAE: forest 725, naive lag_7 451How it works:
- The last 90 days are the test period, cut by position, not at random. The search only ever sees the earlier days.
TimeSeriesSplitinsideGridSearchCVmakes every candidate face the same walk-forward folds, so the tuning rewards settings that forecast the future, not settings that interpolate.- The tuned forest loses to the naive forecast on the test quarter, and its test MAE is about twice its CV MAE. The last quarter of 2024 has record traffic. A random forest cannot predict values above the range of its training targets, so it underestimates every peak day. The naive forecast copies last week and follows the growth.
- Tuning cannot fix a model that cannot extrapolate. Always compare with a naive baseline on the final period. Next steps are a target that removes the trend (for example the ratio
visits / lag_7) or a model with a trend term; module 40 covers both.
M37-X03 · An imbalanced pipeline from sampler to threshold
Section titled “M37-X03 · An imbalanced pipeline from sampler to threshold”Write the code: build an imbalanced-learn pipeline make_preprocess() → RandomUnderSampler(random_state=42) → LogisticRegression(max_iter=1000). Tune sampling_strategy (0.33, 0.5, 1.0) and C (0.1, 1, 10) with GridSearchCV (cv=cv3, scoring="average_precision"). Then wrap the best pipeline in TunedThresholdClassifierCV with the campaign profit (160 per caught churner, −40 per wasted call) and cv=cv3. Print the best parameters, the tuned threshold, and the test precision, recall and profit.
best: {'logisticregression__C': 0.1, 'randomundersampler__sampling_strategy': 0.33}CV average precision 0.546tuned threshold 0.319test precision 0.427, recall 0.685, profit 17560from imblearn.pipeline import make_pipeline as make_imb_pipelinefrom imblearn.under_sampling import RandomUnderSamplerfrom sklearn.metrics import confusion_matrix, make_scorer, precision_score, recall_scorefrom sklearn.model_selection import GridSearchCV, TunedThresholdClassifierCV
def campaign_profit(y_true, y_pred): tn, fp, fn, tp = confusion_matrix(y_true, y_pred, labels=[0, 1]).ravel() return 160 * tp - 40 * fp
# TODO: the imbalanced pipeline and its grid search# TODO: TunedThresholdClassifierCV around search.best_estimator_# TODO: print parameters, threshold and test metricsHint 1
sampling_strategy=0.5 means “after undersampling, churners are half as many as stayers”. The step name is randomundersampler.
Hint 2
TunedThresholdClassifierCV(search.best_estimator_, scoring=make_scorer(campaign_profit), cv=cv3), then .fit(X_train, y_train).
Solution
from imblearn.pipeline import make_pipeline as make_imb_pipelinefrom imblearn.under_sampling import RandomUnderSamplerfrom sklearn.metrics import confusion_matrix, make_scorer, precision_score, recall_scorefrom sklearn.model_selection import GridSearchCV, TunedThresholdClassifierCV
def campaign_profit(y_true, y_pred): tn, fp, fn, tp = confusion_matrix(y_true, y_pred, labels=[0, 1]).ravel() return 160 * tp - 40 * fp
pipe = make_imb_pipeline( make_preprocess(), RandomUnderSampler(random_state=42), LogisticRegression(max_iter=1000),)grid = { "randomundersampler__sampling_strategy": [0.33, 0.5, 1.0], "logisticregression__C": [0.1, 1, 10],}search = GridSearchCV(pipe, grid, cv=cv3, scoring="average_precision", n_jobs=1)search.fit(X_train, y_train)tuned = TunedThresholdClassifierCV( search.best_estimator_, scoring=make_scorer(campaign_profit), cv=cv3, random_state=42,).fit(X_train, y_train)pred = tuned.predict(X_test)print("best:", search.best_params_)print(f"CV average precision {search.best_score_:.3f}")print(f"tuned threshold {tuned.best_threshold_:.3f}")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)}")
assert campaign_profit(y_test, pred) > 0best: {'logisticregression__C': 0.1, 'randomundersampler__sampling_strategy': 0.33}CV average precision 0.546tuned threshold 0.319test precision 0.427, recall 0.685, profit 17560How it works:
- The undersampler runs inside each training fold of the grid search and again inside each fold of the threshold tuning. Validation rows are never resampled.
- Average precision ranks customers, and undersampling hardly changes the ranking, so the sampling strategies score close to each other.
- Undersampling shifts the probabilities upward. The tuned threshold therefore sits above the break-even 0.2 of a calibrated model. Tuning the threshold on the final pipeline corrects for the shift automatically, which is why you tune it last.
M37-X04 · Group-aware tuning picks different hyperparameters
Section titled “M37-X04 · Group-aware tuning picks different hyperparameters”Interpret a result: on the order lines joined with the customer table (features age, tenure_months, monthly_charges, support_tickets, logins_last_30d, unit_price, quantity, discount; label churned), tune min_samples_leaf (1, 5, 25, 100, 400) of a DecisionTreeClassifier(random_state=42) twice: once with KFold(3, shuffle=True, random_state=42) and once with GroupKFold(3, shuffle=True, random_state=42) by customer. Print each search’s choice and best score. Then score both chosen trees with the group splitter. Which choice is right for new customers?
KFold search picks {'min_samples_leaf': 5}, says 0.962, group score 0.591GroupKFold search picks {'min_samples_leaf': 100}, says 0.711, group score 0.711from sklearn.model_selection import GridSearchCV, GroupKFold, KFold, cross_val_scorefrom sklearn.tree import DecisionTreeClassifier
sales = pd.read_csv("data/sales.csv", usecols=["customer_id", "unit_price", "quantity", "discount"])lines = sales.merge(customers, on="customer_id", how="left")# TODO: features, label and groups# TODO: two GridSearchCV runs; pass groups= to fit for the group search# TODO: re-score both chosen trees with GroupKFoldHint 1
GridSearchCV(...).fit(X_lines, y_lines, groups=groups) forwards the groups to the splitter.
Hint 2
search.best_estimator_ is a fitted tree. Pass a clone of it, or simply the estimator (cross-validation clones it), to cross_val_score with the group splitter.
Solution
from sklearn.model_selection import GridSearchCV, GroupKFold, KFold, cross_val_scorefrom sklearn.tree import DecisionTreeClassifier
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, y_lines, groups = lines[features], lines["churned"], lines["customer_id"]kfold = KFold(n_splits=3, shuffle=True, random_state=42)group_kfold = GroupKFold(n_splits=3, shuffle=True, random_state=42)grid = {"min_samples_leaf": [1, 5, 25, 100, 400]}tree = DecisionTreeClassifier(random_state=42)naive = GridSearchCV(tree, grid, cv=kfold, scoring="roc_auc", n_jobs=1)naive.fit(X_lines, y_lines)honest = GridSearchCV(tree, grid, cv=group_kfold, scoring="roc_auc", n_jobs=1)honest.fit(X_lines, y_lines, groups=groups)for name, search in [("KFold search", naive), ("GroupKFold search", honest)]: rescored = cross_val_score( search.best_estimator_, X_lines, y_lines, groups=groups, cv=group_kfold, scoring="roc_auc", ).mean() print(f"{name:<18} picks {search.best_params_}, says {search.best_score_:.3f}," f" group score {rescored:.3f}")
assert naive.best_params_["min_samples_leaf"] < honest.best_params_["min_samples_leaf"]KFold search picks {'min_samples_leaf': 5}, says 0.962, group score 0.591GroupKFold search picks {'min_samples_leaf': 100}, says 0.711, group score 0.711How it works:
- The naive search rewards memorization: small leaves let the tree recognize each customer’s exact profile, which pays off when the same customers sit in the validation fold. It picks leaves of 5 rows and reports a score of 0.96.
- The group search sees only new customers in validation, so memorization does not pay. It picks large leaves that capture general patterns.
- Re-scored honestly, the naive choice is clearly worse. Leakage does not only inflate a score; it also steers the tuning to the wrong hyperparameters. The group choice is right for new customers.
M37-X05 · Successive halving or random search?
Section titled “M37-X05 · Successive halving or random search?”Choose a method and justify it: on make_classification(n_samples=6000, n_features=20, n_informative=6, random_state=42) (split 75/25, stratified, random_state=42), compare RandomizedSearchCV(n_iter=27) with HalvingRandomSearchCV(n_candidates=27, factor=3, min_resources=500) for a DecisionTreeClassifier(random_state=42). Sample max_depth from randint(2, 20), min_samples_leaf from randint(1, 100) and max_features from [0.3, 0.6, 1.0]. Use StratifiedKFold(3, shuffle=True, random_state=42) and accuracy. Print, for each, the training rows used in total (rows per fit × fits), the best CV score and the test accuracy.
random rows used 243,000 CV 0.884 test 0.885halving rows used 81,000 CV 0.882 test 0.884halving rounds: [27, 9, 3] [500, 1500, 4500]from scipy.stats import randintfrom sklearn.datasets import make_classificationfrom sklearn.experimental import enable_halving_search_cv # noqa: F401from sklearn.model_selection import HalvingRandomSearchCV, RandomizedSearchCVfrom sklearn.tree import DecisionTreeClassifier
X_syn, y_syn = make_classification( n_samples=6000, n_features=20, n_informative=6, random_state=42)# TODO: split, define the distributions, run both searches# TODO: rows used: random = n_iter * 3 folds * (2/3 of the training rows)# TODO: halving = sum over rounds of candidates * 3 * rows per round (2/3 used for fit)Hint 1
halving.n_candidates_ and halving.n_resources_ are lists with one entry per round.
Hint 2
In each round, each candidate is fitted on 2/3 of the resource (3-fold CV). Multiply candidates × 3 folds × resource × 2/3 and sum the rounds.
Solution
from scipy.stats import randintfrom sklearn.datasets import make_classificationfrom sklearn.experimental import enable_halving_search_cv # noqa: F401from sklearn.model_selection import HalvingRandomSearchCV, RandomizedSearchCVfrom sklearn.tree import DecisionTreeClassifier
X_syn, y_syn = make_classification( n_samples=6000, n_features=20, n_informative=6, random_state=42)Xs_train, Xs_test, ys_train, ys_test = train_test_split( X_syn, y_syn, test_size=0.25, stratify=y_syn, random_state=42)dist = { "max_depth": randint(2, 20), "min_samples_leaf": randint(1, 100), "max_features": [0.3, 0.6, 1.0],}tree = DecisionTreeClassifier(random_state=42)common = {"cv": cv3, "random_state": 42, "n_jobs": 1}rand = RandomizedSearchCV(tree, dist, n_iter=27, **common).fit(Xs_train, ys_train)halving = HalvingRandomSearchCV( tree, dist, n_candidates=27, factor=3, min_resources=500, **common).fit(Xs_train, ys_train)rows_random = 27 * 3 * len(Xs_train) * 2 // 3rows_halving = sum( c * 3 * r * 2 // 3 for c, r in zip(halving.n_candidates_, halving.n_resources_))for name, search, rows in [("random", rand, rows_random), ("halving", halving, rows_halving)]: print(f"{name:<8} rows used {rows:>7,} CV {search.best_score_:.3f}" f" test {search.score(Xs_test, ys_test):.3f}")print("halving rounds:", halving.n_candidates_, halving.n_resources_)
assert rows_halving < rows_randomrandom rows used 243,000 CV 0.884 test 0.885halving rows used 81,000 CV 0.882 test 0.884halving rounds: [27, 9, 3] [500, 1500, 4500]How it works:
- Random search fits all 27 candidates on 3,000 rows each (2/3 of 4,500), 81 times.
- Halving fits 27 candidates on 333 rows each, then 9 on 1,000, then 3 on 3,000. It uses a third of the training rows of the random search.
- The test accuracies are close. Choose successive halving when fits are slow and you have many candidates: a weak candidate is usually weak on small data too. Choose plain random search when the ranking of candidates changes with the data size (for example, deep trees that only shine on many rows), because halving can drop them in the first round.