38. Ensembles — Exercises
These exercises practice every idea of the Ensembles lesson. They use data/houses.csv (house prices, scored with RMSE), data/customers.csv (churn, scored with ROC-AUC) and one dataset bundled with scikit-learn. The data dictionary describes the course files.
How to work:
- Read the task and the expected output.
- Copy the setup block and the starter code into a script, for example
exercise.py. Replace each to-do comment with your code. - Run the script with
python exercise.pyfrom your project folder (the one that holdsdata/). 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. Scores are printed with 3 or 4 decimals; your numbers match exactly when you use the same seeds, splits and settings.
Every exercise starts with these lines. The verifier runs them before each exercise. They prepare the house split (X_train, X_test, y_train, y_test) and the churn split (Xc_train, Xc_test, yc_train, yc_test) exactly as in the lesson.
import lightgbm as lgbimport numpy as npimport pandas as pdfrom sklearn.compose import ColumnTransformerfrom sklearn.ensemble import ( AdaBoostClassifier, BaggingRegressor, GradientBoostingRegressor, HistGradientBoostingClassifier, RandomForestClassifier, RandomForestRegressor, StackingClassifier, VotingClassifier,)from sklearn.impute import SimpleImputerfrom sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import accuracy_score, roc_auc_score, root_mean_squared_errorfrom sklearn.model_selection import ( KFold, StratifiedKFold, cross_val_predict, cross_val_score, cross_validate, train_test_split,)from sklearn.pipeline import make_pipelinefrom sklearn.preprocessing import OneHotEncoder, StandardScalerfrom sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressorfrom threadpoolctl import threadpool_limitsfrom xgboost import XGBClassifier
threadpool_limits(limits=1) # whole script: 1 thread for OpenMP and BLASpd.set_option("display.width", 100)pd.set_option("display.max_columns", 12)pd.set_option("display.precision", 3)
houses = pd.read_csv("data/houses.csv")X = pd.get_dummies( houses.drop(columns=["house_id", "sold_date", "price"]), columns=["neighborhood"], dtype=int,)y = houses["price"]X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.25, random_state=42)medians = X_train.median()X_train, X_test = X_train.fillna(medians), X_test.fillna(medians)
customers = pd.read_csv("data/customers.csv")CAT = ["region", "plan", "contract", "payment_method"]NUM = [ "age", "has_autopay", "tenure_months", "monthly_charges", "total_charges", "support_tickets", "logins_last_30d", "avg_session_minutes",]X_c = customers[CAT + NUM].astype({c: "category" for c in CAT})y_c = customers["churned"]Xc_train, Xc_test, yc_train, yc_test = train_test_split( X_c, y_c, test_size=0.25, stratify=y_c, random_state=42)one_hot = ColumnTransformer([ ("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), CAT), ("num", SimpleImputer(strategy="median"), NUM),])scaled = ColumnTransformer([ ("cat", OneHotEncoder(handle_unknown="ignore"), CAT), ("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), NUM),])Warm-up
Section titled “Warm-up”M38-W01 · Draw a bootstrap sample
Section titled “M38-W01 · Draw a bootstrap sample”A bootstrap sample of 1,000 rows draws 1,000 row positions with replacement. Draw one with np.random.default_rng(42). Print the number and share of distinct rows, the number of out-of-bag rows and the theoretical in-bag share .
distinct rows: 637 (63.7%)out-of-bag rows: 363theory: 63.2% in the bagrng = np.random.default_rng(42)n = 1000# TODO: draw n positions from 0..n-1 with replacement# TODO: count the distinct positions and the rows never drawn# TODO: print them and the theoretical in-bag shareHint 1
rng.integers(0, n, size=n) draws n positions with replacement. np.unique keeps each position once.
Hint 2
The out-of-bag rows are the rows never drawn: n - len(np.unique(rows)).
Solution
rng = np.random.default_rng(42)n = 1000rows = rng.integers(0, n, size=n)distinct = len(np.unique(rows))theory = 1 - (1 - 1 / n) ** nprint(f"distinct rows: {distinct} ({distinct / n:.1%})")print(f"out-of-bag rows: {n - distinct}")print(f"theory: {theory:.1%} in the bag")assert 0.6 < distinct / n < 0.67assert round(theory, 3) == 0.632distinct rows: 637 (63.7%)out-of-bag rows: 363theory: 63.2% in the bagHow it works:
rng.integers(0, n, size=n)draws 1,000 positions. Some come up more than once.np.uniqueremoves the repeats. About 63% of the rows remain; the rest are out of bag.- The formula gives the long-run share. One sample differs from it by chance.
Alternative: np.bincount(rows, minlength=n) counts how often each row was drawn. (counts == 0).sum() is the out-of-bag count.
M38-W02 · Predict the output: three forecasters
Section titled “M38-W02 · Predict the output: three forecasters”Predict the output: three analysts forecast next month’s units for four stores. Write down what each line prints, then run the code. The numbers are small on purpose.
actual = np.array([100, 200, 300, 400])forecasts = np.array([ [110, 190, 330, 380], # analyst A [ 90, 220, 280, 410], # analyst B [100, 200, 300, 450], # analyst C])errors = forecasts - actualprint(np.abs(errors).mean(axis=1))average = forecasts.mean(axis=0)print(average.round(1))print(round(np.abs(average - actual).mean(), 2))Acceptance criteria:
- Write your three predicted lines before you run the code.
- Your prediction matches the Output in the solution, and you can say why the average beats analyst A and B but not analyst C on store 1.
Hint 1
axis=1 averages along each row (one analyst). axis=0 averages down each column (one store).
Hint 2
On store 1 the errors are +10, −10 and 0. On store 4 they are −20, +10 and +50.
Solution
actual = np.array([100, 200, 300, 400])forecasts = np.array([ [110, 190, 330, 380], # analyst A [90, 220, 280, 410], # analyst B [100, 200, 300, 450], # analyst C])errors = forecasts - actualprint(np.abs(errors).mean(axis=1))average = forecasts.mean(axis=0)print(average.round(1))print(round(np.abs(average - actual).mean(), 2))assert np.abs(average - actual).mean() < np.abs(errors).mean(axis=1).min()[17.5 15. 12.5][100. 203.3 303.3 413.3]5.0How it works:
- The mean absolute errors of the analysts are 17.5, 15 and 12.5.
- The average forecast per store is the column mean. On store 1, the +10 and −10 cancel exactly.
- The average errs by 0, 3.3, 3.3 and 13.3: a mean of 5, better than every analyst. On store 1, analyst C is exactly right, so no average can beat C there. Averaging wins overall because the errors point in different directions.
M38-W03 · Hard and soft votes by hand
Section titled “M38-W03 · Hard and soft votes by hand”Three churn models give these probabilities for five customers (one row per model). With a 0.5 threshold, compute the hard vote (majority of labels) and the soft vote (mean probability) for each customer. Print the labels of each model, both votes and the mean probabilities.
[[1 0 0 1 1] [0 0 0 1 0] [0 1 0 1 0]]hard: [0 0 0 1 0]soft: [1 1 0 1 0] [0.533 0.543 0.2 0.527 0.483]probs = np.array([ [0.90, 0.45, 0.20, 0.55, 0.60], # model 1 [0.30, 0.48, 0.10, 0.52, 0.40], # model 2 [0.40, 0.70, 0.30, 0.51, 0.45], # model 3])# TODO: labels per model (threshold 0.5)# TODO: hard vote = majority of the labels; soft vote = mean probability >= 0.5Hint 1
(probs >= 0.5).astype(int) gives the labels. A majority of 3 means at least 2 votes: labels.sum(axis=0) >= 2.
Hint 2
The soft vote uses probs.mean(axis=0) and the same threshold.
Solution
probs = np.array([ [0.90, 0.45, 0.20, 0.55, 0.60], # model 1 [0.30, 0.48, 0.10, 0.52, 0.40], # model 2 [0.40, 0.70, 0.30, 0.51, 0.45], # model 3])labels = (probs >= 0.5).astype(int)hard = (labels.sum(axis=0) >= 2).astype(int)mean_prob = probs.mean(axis=0)soft = (mean_prob >= 0.5).astype(int)print(labels)print("hard:", hard)print("soft:", soft, mean_prob.round(3))assert hard.tolist() == [0, 0, 0, 1, 0]assert soft.tolist() == [1, 1, 0, 1, 0][[1 0 0 1 1] [0 0 0 1 0] [0 1 0 1 0]]hard: [0 0 0 1 0]soft: [1 1 0 1 0] [0.533 0.543 0.2 0.527 0.483]How it works:
- Customer 1: only model 1 says churn, so the hard vote is 0. But model 1 is very sure (0.90), and the mean is 0.533, so the soft vote is 1.
- Customer 2: two models say 0.45 and 0.48, just below the line, and one says 0.70. The mean is 0.543, so the soft vote is 1 again.
- Customer 5: one 0.60 against 0.40 and 0.45 gives a mean below 0.5. Both votes agree on 0.
Soft voting uses how sure each model is; hard voting throws that away.
M38-W04 · Majority of independent voters
Section titled “M38-W04 · Majority of independent voters”Seven independent classifiers are each right 70% of the time. Compute the probability that the majority (4 or more) is right, first with scipy.stats.binom, then by simulating 100,000 cases with np.random.default_rng(42).
exact 0.8740 | simulated 0.8750from scipy.stats import binom
n, p = 7, 0.7# TODO: exact probability that more than 3 of 7 are right# TODO: simulate 100,000 cases of 7 voters and count the majoritiesHint 1
binom.sf(3, 7, 0.7) is the probability of more than 3 successes.
Hint 2
rng.random((100_000, 7)) < 0.7 gives a True for each correct voter. Sum each row and compare with 4.
Solution
from scipy.stats import binom
n, p = 7, 0.7exact = binom.sf(n // 2, n, p)rng = np.random.default_rng(42)correct = rng.random((100_000, n)) < psimulated = (correct.sum(axis=1) > n // 2).mean()print(f"exact {exact:.4f} | simulated {simulated:.4f}")assert abs(exact - simulated) < 0.005assert exact > pexact 0.8740 | simulated 0.8750How it works:
binom.sf(3, 7, 0.7)adds the probabilities of 4, 5, 6 and 7 correct voters.- The simulation draws 100,000 rows of 7 independent voters and counts the rows with a majority right. It agrees with the formula to about two decimals.
- The majority is right 87% of the time, much more than one voter’s 70%. Real models are not independent, so the real gain is smaller.
M38-W05 · Fix the bug: no out-of-bag rows
Section titled “M38-W05 · Fix the bug: no out-of-bag rows”Fix the bug: a colleague wants the out-of-bag R² of bagged trees on the house prices, but the code raises ValueError: Out of bag estimation only available if bootstrap=True. Fix it with 40 trees and print the OOB R² and the test R².
OOB R² 0.861 | test R² 0.890bag = BaggingRegressor( DecisionTreeRegressor(), n_estimators=40, bootstrap=False, # "use all the rows, more data is better" oob_score=True, random_state=42,)bag.fit(X_train, y_train)print(f"OOB R² {bag.oob_score_:.3f}")Hint 1
Which rows are “out of bag” when every tree trains on every row?
Hint 2
Remove bootstrap=False. The default, bootstrap=True, draws a bootstrap sample for each tree.
Solution
bag = BaggingRegressor( DecisionTreeRegressor(), n_estimators=40, oob_score=True, # bootstrap=True is the default random_state=42,)bag.fit(X_train, y_train)print(f"OOB R² {bag.oob_score_:.3f} | test R² {bag.score(X_test, y_test):.3f}")assert bag.bootstrapassert 0.8 < bag.oob_score_ < 0.95OOB R² 0.861 | test R² 0.890How it works:
- With
bootstrap=False, every tree trains on all rows. No row is out of bag, so there is nothing to score. - Worse, deep trees on the same rows are almost identical, so averaging them gains nothing. The bootstrap is what makes the trees differ.
- With the default
bootstrap=True, each tree leaves out about 37% of the rows, and the OOB score uses them.
M38-W06 · Out-of-bag score of a forest
Section titled “M38-W06 · Out-of-bag score of a forest”Fit a RandomForestRegressor with 100 trees, max_features=0.33, oob_score=True and random_state=42 on the house prices. Print the OOB R², the test R² and the OOB RMSE (from oob_prediction_).
OOB R² 0.874 | test R² 0.910OOB RMSE 112,414# TODO: fit the forest with oob_score=True# TODO: print oob_score_, the test R² and the RMSE of oob_prediction_Hint 1
forest.score(X_test, y_test) is the test R² of a regressor.
Hint 2
forest.oob_prediction_ has one prediction per training row. Compare it with y_train.
Solution
forest = RandomForestRegressor( n_estimators=100, max_features=0.33, oob_score=True, random_state=42).fit(X_train, y_train)oob_rmse = root_mean_squared_error(y_train, forest.oob_prediction_)print(f"OOB R² {forest.oob_score_:.3f} | test R² {forest.score(X_test, y_test):.3f}")print(f"OOB RMSE {oob_rmse:,.0f}")assert forest.oob_prediction_.shape == y_train.shapeassert abs(forest.oob_score_ - forest.score(X_test, y_test)) < 0.05OOB R² 0.874 | test R² 0.910OOB RMSE 112,414How it works:
oob_score=Truemakes the forest predict each training row with the trees that did not see it, about 37 of the 100.oob_score_is the R² of those predictions;oob_prediction_holds them.- The OOB R² is below the test R². Fewer trees per OOB prediction (about 37 of 100) add only a little pessimism. The main reason is the split: the 8 known price outliers listed in the data dictionary all fell into the training rows, so this test set is easier. The OOB score is a fair estimate for the training rows, and it cost no extra data and no extra fits.
M38-W07 · One boosting round on five houses
Section titled “M38-W07 · One boosting round on five houses”Five houses have these sizes and prices (in thousand USD). Run one gradient boosting round by hand: start from the mean, compute the residuals, fit a stump (DecisionTreeRegressor(max_depth=1)) to the residuals and add it with a learning rate of 0.5. Print a table and the RMSE before and after.
sqft price residual_0 stump F1 residual_10 800 200 -134.0 -84.0 292.0 -92.01 1000 240 -94.0 -84.0 292.0 -52.02 1400 310 -24.0 -84.0 292.0 18.03 1900 400 66.0 126.0 397.0 3.04 2600 520 186.0 126.0 397.0 123.0F0 = 334 | RMSE before 115.2, after 73.0toy = pd.DataFrame({"sqft": [800, 1000, 1400, 1900, 2600], "price": [200, 240, 310, 400, 520]})# TODO: F0 = mean price; residuals = price - F0# TODO: fit a stump on sqft -> residuals; F1 = F0 + 0.5 * stump predictionHint 1
Fit the stump on toy[["sqft"]] (a DataFrame, two brackets) with the residuals as the target.
Hint 2
F1 = f0 + 0.5 * stump.predict(toy[["sqft"]]). Then residual_1 = price - F1.
Solution
toy = pd.DataFrame({"sqft": [800, 1000, 1400, 1900, 2600], "price": [200, 240, 310, 400, 520]})f0 = toy["price"].mean()toy["residual_0"] = toy["price"] - f0stump = DecisionTreeRegressor(max_depth=1, random_state=42)stump.fit(toy[["sqft"]], toy["residual_0"])toy["stump"] = stump.predict(toy[["sqft"]])toy["F1"] = f0 + 0.5 * toy["stump"]toy["residual_1"] = toy["price"] - toy["F1"]print(toy)rmse_0 = np.sqrt((toy["residual_0"] ** 2).mean())rmse_1 = np.sqrt((toy["residual_1"] ** 2).mean())print(f"F0 = {f0:.0f} | RMSE before {rmse_0:.1f}, after {rmse_1:.1f}")assert rmse_1 < rmse_0assert np.isclose(toy["residual_0"].sum(), 0) sqft price residual_0 stump F1 residual_10 800 200 -134.0 -84.0 292.0 -92.01 1000 240 -94.0 -84.0 292.0 -52.02 1400 310 -24.0 -84.0 292.0 18.03 1900 400 66.0 126.0 397.0 3.04 2600 520 186.0 126.0 397.0 123.0F0 = 334 | RMSE before 115.2, after 73.0How it works:
- The mean price, 334, is the first model. The residuals sum to zero.
- The stump splits the houses into small and large and predicts the mean residual of each group.
- Adding half of the stump’s correction moves every prediction halfway toward its group mean. The RMSE drops, and the next round would fit the new residuals.
M38-W08 · Predict the output: how fast the residual shrinks
Section titled “M38-W08 · Predict the output: how fast the residual shrinks”Predict the output: imagine a perfect tree that always predicts the current residual exactly. Each round adds nu times that residual. Starting from a residual of 100, write down the residual after rounds 1, 2, 3 and 10 for nu = 1.0, 0.5 and 0.1. Then run the code.
for nu in [1.0, 0.5, 0.1]: residual = 100.0 history = [] for _ in range(10): # 10 rounds residual = residual - nu * residual # the tree predicts it exactly history.append(residual) print(nu, [round(history[i], 1) for i in [0, 1, 2, 9]])Acceptance criteria:
- Write your three predicted lines before you run the code.
- Your prediction matches the Output in the solution, and you can explain why boosting with
nu = 1.0would overfit real data.
Hint 1
Each round keeps a share 1 - nu of the residual.
Hint 2
After m rounds the residual is 100 * (1 - nu) ** m.
Solution
for nu in [1.0, 0.5, 0.1]: residual = 100.0 history = [] for _ in range(10): # 10 rounds residual = residual - nu * residual # the tree predicts it exactly history.append(residual) print(nu, [round(history[i], 1) for i in [0, 1, 2, 9]]) assert np.isclose(residual, 100 * (1 - nu) ** 10)1.0 [0.0, 0.0, 0.0, 0.0]0.5 [50.0, 25.0, 12.5, 0.1]0.1 [90.0, 81.0, 72.9, 34.9]How it works:
- With
nu = 1.0, the first tree removes the whole residual. On real data, the residual contains noise, so the tree would learn the noise in one step: overfitting. - With
nu = 0.5, each round halves the residual: 50, 25, 12.5, and about 0.1 after 10 rounds. - With
nu = 0.1, each round keeps 90%. After 10 rounds, 35% is left. A small learning rate needs many more rounds, which is the trade-off of Example 4 in the lesson.
M38-W09 · Fix the bug: probabilities from a voting ensemble
Section titled “M38-W09 · Fix the bug: probabilities from a voting ensemble”Fix the bug: this code should print the test ROC-AUC of a voting ensemble of a logistic regression and a depth-4 tree, but predict_proba raises AttributeError: This 'VotingClassifier' has no attribute 'predict_proba'. Fix it and print the ROC-AUC.
ROC-AUC 0.824vote = VotingClassifier([ ("logreg", make_pipeline(scaled, LogisticRegression(max_iter=1000))), ("tree", make_pipeline( one_hot, DecisionTreeClassifier(max_depth=4, random_state=42) )),])vote.fit(Xc_train, yc_train)auc = roc_auc_score(yc_test, vote.predict_proba(Xc_test)[:, 1])print(f"ROC-AUC {auc:.3f}")Hint 1
What is the default value of voting? What does that rule combine?
Hint 2
Hard voting combines labels, so it has no probabilities. Pass voting="soft".
Solution
vote = VotingClassifier( [ ("logreg", make_pipeline(scaled, LogisticRegression(max_iter=1000))), ("tree", make_pipeline( one_hot, DecisionTreeClassifier(max_depth=4, random_state=42) )), ], voting="soft",)vote.fit(Xc_train, yc_train)auc = roc_auc_score(yc_test, vote.predict_proba(Xc_test)[:, 1])print(f"ROC-AUC {auc:.3f}")assert hasattr(vote, "predict_proba")assert auc > 0.8ROC-AUC 0.824How it works:
- The default is
voting="hard": a majority vote of the predicted labels. Labels carry no probability, so scikit-learn hidespredict_proba. voting="soft"averages the probabilities of the two pipelines. The ensemble then haspredict_proba, and ROC-AUC works.- With only two members, a hard vote would also have to break every 1-to-1 tie; soft voting has no ties in practice.
M38-C01 · Bag trees by hand and compare with BaggingRegressor
Section titled “M38-C01 · Bag trees by hand and compare with BaggingRegressor”Bag 30 deep trees by hand on the house prices: draw a bootstrap sample with np.random.default_rng(42) for each tree (random_state=b for tree b), predict the test set and average. Print the test RMSE of the first tree, of the hand-made bag, and of BaggingRegressor(DecisionTreeRegressor(), n_estimators=30, random_state=42).
one tree 170,802by hand 107,610library 107,121rng = np.random.default_rng(42)n = len(X_train)preds = []for b in range(30): # TODO: draw a bootstrap sample of row positions # TODO: fit DecisionTreeRegressor(random_state=b) on it and predict X_test ...# TODO: RMSE of preds[0], of the mean of preds, and of BaggingRegressorHint 1
rows = rng.integers(0, n, size=n), then X_train.iloc[rows] and y_train.iloc[rows].
Hint 2
Stack the predictions with np.array(preds) (shape 30 × 750) and average with .mean(axis=0).
Solution
rng = np.random.default_rng(42)n = len(X_train)preds = []for b in range(30): rows = rng.integers(0, n, size=n) tree = DecisionTreeRegressor(random_state=b) tree.fit(X_train.iloc[rows], y_train.iloc[rows]) preds.append(tree.predict(X_test))preds = np.array(preds)one_tree = root_mean_squared_error(y_test, preds[0])by_hand = root_mean_squared_error(y_test, preds.mean(axis=0))bag = BaggingRegressor(DecisionTreeRegressor(), n_estimators=30, random_state=42)library = root_mean_squared_error(y_test, bag.fit(X_train, y_train).predict(X_test))print(f"one tree {one_tree:,.0f}")print(f"by hand {by_hand:,.0f}")print(f"library {library:,.0f}")assert by_hand < 0.8 * one_treeassert abs(by_hand - library) / library < 0.05one tree 170,802by hand 107,610library 107,121How it works:
- Each tree trains on its own bootstrap sample, so the trees differ.
- Averaging the 30 predictions removes much of their variance, so the error drops by about a third.
BaggingRegressorruns the same loop with its own random draws. The two bags differ by a few percent, which is the randomness of the samples.
M38-C02 · Choose max_features with the OOB score
Section titled “M38-C02 · Choose max_features with the OOB score”Fit a RandomForestRegressor with 60 trees, oob_score=True and random_state=42 for each max_features in [1.0, 0.5, 0.33, "sqrt"]. Choose the setting with the highest OOB R², and only then print its test RMSE.
max_features=1.0 OOB R² 0.8671max_features=0.5 OOB R² 0.8726max_features=0.33 OOB R² 0.8727max_features=sqrt OOB R² 0.8656chosen: 0.33 | test RMSE 98,096scores = {}for setting in [1.0, 0.5, 0.33, "sqrt"]: # TODO: fit the forest and store its OOB R² ...# TODO: choose the best setting, refit (or keep) it and print its test RMSEHint 1
Keep the fitted forests in a dict as well, so you do not refit the winner.
Hint 2
best = max(scores, key=scores.get) returns the key with the highest value.
Solution
scores, forests = {}, {}for setting in [1.0, 0.5, 0.33, "sqrt"]: forest = RandomForestRegressor( n_estimators=60, max_features=setting, oob_score=True, random_state=42 ).fit(X_train, y_train) scores[setting], forests[setting] = forest.oob_score_, forest print(f"max_features={setting!s:<5} OOB R² {forest.oob_score_:.4f}")best = max(scores, key=scores.get)rmse = root_mean_squared_error(y_test, forests[best].predict(X_test))print(f"chosen: {best} | test RMSE {rmse:,.0f}")assert best != 1.0assert scores[best] == max(scores.values())max_features=1.0 OOB R² 0.8671max_features=0.5 OOB R² 0.8726max_features=0.33 OOB R² 0.8727max_features=sqrt OOB R² 0.8656chosen: 0.33 | test RMSE 98,096How it works:
- The loop scores each setting with the OOB R², which uses only training rows.
max(scores, key=scores.get)picks the setting with the highest OOB R². With 18 features,"sqrt"means 4 features per split.- The test set is used once, for the chosen model only, so its score stays honest.
0.5and0.33both beat plain bagging (1.0) and are practically tied."sqrt"(4 features) goes too far: each tree gets too weak.
Alternative: use cross_val_score with 5 folds for each setting. It costs 5 fits per setting, while the OOB score comes free with one fit.
M38-C03 · Refactor: one splitter for every model
Section titled “M38-C03 · Refactor: one splitter for every model”Refactor: the code below compares three churn models, but each model gets its own splitter with a different seed, and the loop collects scores by hand. Rewrite it with one StratifiedKFold(5, shuffle=True, random_state=42) and cross_validate, and print a table with the mean and standard deviation of ROC-AUC per model.
auc_mean auc_stdmodelforest 0.833 0.010logreg 0.814 0.018tree 0.804 0.005models = { "logreg": make_pipeline(scaled, LogisticRegression(max_iter=1000)), "tree": make_pipeline( one_hot, DecisionTreeClassifier(max_depth=5, random_state=42) ), "forest": make_pipeline(one_hot, RandomForestClassifier( n_estimators=50, min_samples_leaf=3, random_state=42)),}for seed, (name, model) in enumerate(models.items()): scores = [] for train_idx, val_idx in KFold(5, shuffle=True, random_state=seed).split(X_c): model.fit(X_c.iloc[train_idx], y_c.iloc[train_idx]) p = model.predict_proba(X_c.iloc[val_idx])[:, 1] scores.append(roc_auc_score(y_c.iloc[val_idx], p)) print(name, np.mean(scores))Hint 1
Create the splitter once, before the loop: cv = StratifiedKFold(5, shuffle=True, random_state=42).
Hint 2
cross_validate(model, X_c, y_c, cv=cv, scoring="roc_auc")["test_score"] returns the 5 fold scores. Collect one dict per model and build a DataFrame.
Solution
models = { "logreg": make_pipeline(scaled, LogisticRegression(max_iter=1000)), "tree": make_pipeline( one_hot, DecisionTreeClassifier(max_depth=5, random_state=42) ), "forest": make_pipeline(one_hot, RandomForestClassifier( n_estimators=50, min_samples_leaf=3, random_state=42)),}cv = StratifiedKFold(5, shuffle=True, random_state=42) # one splitter for allrows = []for name, model in models.items(): auc = cross_validate(model, X_c, y_c, cv=cv, scoring="roc_auc")["test_score"] rows.append({"model": name, "auc_mean": auc.mean(), "auc_std": auc.std()})table = pd.DataFrame(rows).set_index("model").sort_values("auc_mean", ascending=False)print(table.round(3))assert table.index[0] == "forest"assert (table["auc_std"] < 0.03).all() auc_mean auc_stdmodelforest 0.833 0.010logreg 0.814 0.018tree 0.804 0.005How it works:
- One splitter object gives every model the same 5 folds, so the comparison is paired and fair.
StratifiedKFoldalso keeps the churn rate equal in each fold. cross_validateclones the model for each fold, so no fitted state leaks from one fold to the next. The manual loop refitted the same object, which works but is easy to get wrong.- The table shows the spread next to the mean, so you can see whether a gap is larger than the noise.
M38-C04 · Gradient boosting by hand: 5 rounds
Section titled “M38-C04 · Gradient boosting by hand: 5 rounds”Build gradient boosting by hand on the house prices: 5 rounds, trees of depth 2 (random_state=42), learning rate 0.2, starting from the training mean. Print the training RMSE after each round, then check that GradientBoostingRegressor(n_estimators=5, learning_rate=0.2, max_depth=2, random_state=42) gives the same test predictions.
round 1: train RMSE 283,143round 2: train RMSE 256,297round 3: train RMSE 236,305round 4: train RMSE 218,921round 5: train RMSE 202,322matches GradientBoostingRegressor: Truelr = 0.2pred_train = np.full(len(y_train), y_train.mean())pred_test = np.full(len(y_test), y_train.mean())for round_no in range(1, 6): # TODO: residuals, fit a depth-2 tree on them, update both predictions ...# TODO: fit GradientBoostingRegressor and compare with np.allcloseHint 1
The residuals are y_train - pred_train, recomputed at the start of each round.
Hint 2
Update with pred_train += lr * tree.predict(X_train) and the same for pred_test.
Solution
lr = 0.2pred_train = np.full(len(y_train), y_train.mean())pred_test = np.full(len(y_test), y_train.mean())for round_no in range(1, 6): residuals = y_train - pred_train tree = DecisionTreeRegressor(max_depth=2, random_state=42).fit(X_train, residuals) pred_train += lr * tree.predict(X_train) pred_test += lr * tree.predict(X_test) rmse = root_mean_squared_error(y_train, pred_train) print(f"round {round_no}: train RMSE {rmse:,.0f}")gbr = GradientBoostingRegressor( n_estimators=5, learning_rate=0.2, max_depth=2, random_state=42).fit(X_train, y_train)same = np.allclose(gbr.predict(X_test), pred_test)print("matches GradientBoostingRegressor:", same)assert sameround 1: train RMSE 283,143round 2: train RMSE 256,297round 3: train RMSE 236,305round 4: train RMSE 218,921round 5: train RMSE 202,322matches GradientBoostingRegressor: TrueHow it works:
- Each round fits a tree to what the current model still gets wrong, then adds 20% of the tree’s prediction.
- The training RMSE falls each round, by less and less.
- For squared error,
GradientBoostingRegressorruns exactly this loop: itsinit_is the mean, each tree fits the residuals, and the update uses the learning rate.
M38-C05 · Pick the number of trees on a validation split
Section titled “M38-C05 · Pick the number of trees on a validation split”Split the house training set again (20% validation, random_state=42). Fit GradientBoostingRegressor(n_estimators=400, learning_rate=0.1, max_depth=3, random_state=42) on the rest. Use staged_predict to find the number of trees with the lowest validation RMSE. Refit with that number on the full training set and print the test RMSE.
best on validation: 272 trees, RMSE 90,781test RMSE 97,958X_fit, X_val, y_fit, y_val = train_test_split( X_train, y_train, test_size=0.2, random_state=42)# TODO: fit 400 trees on X_fit; staged validation RMSE; best number of trees# TODO: refit on X_train with that number; print the test RMSEHint 1
[root_mean_squared_error(y_val, p) for p in model.staged_predict(X_val)] gives 400 RMSEs.
Hint 2
np.argmin(curve) + 1 is the best number of trees (the list starts at 1 tree).
Solution
X_fit, X_val, y_fit, y_val = train_test_split( X_train, y_train, test_size=0.2, random_state=42)model = GradientBoostingRegressor( n_estimators=400, learning_rate=0.1, max_depth=3, random_state=42).fit(X_fit, y_fit)curve = [root_mean_squared_error(y_val, p) for p in model.staged_predict(X_val)]best_n = int(np.argmin(curve)) + 1print(f"best on validation: {best_n} trees, RMSE {min(curve):,.0f}")final = GradientBoostingRegressor( n_estimators=best_n, learning_rate=0.1, max_depth=3, random_state=42).fit(X_train, y_train)print(f"test RMSE {root_mean_squared_error(y_test, final.predict(X_test)):,.0f}")assert 50 < best_n < 400best on validation: 272 trees, RMSE 90,781test RMSE 97,958How it works:
- One fit of 400 trees gives the whole validation curve through
staged_predict. - The minimum of the curve is the number of trees to keep. The test set played no part in the choice.
- The final model refits on all training rows. With 25% more data, the best number of trees could be slightly higher, but the choice is close enough.
Alternative: GradientBoostingRegressor(n_estimators=1000, validation_fraction=0.2, n_iter_no_change=20) stops early by itself. Its n_estimators_ attribute holds the number of trees it kept.
M38-C06 · Early stopping with HistGradientBoosting
Section titled “M38-C06 · Early stopping with HistGradientBoosting”Fit HistGradientBoostingClassifier on the churn training set with max_iter=1000, max_leaf_nodes=15, early_stopping=True, n_iter_no_change=30, categorical_features="from_dtype" and random_state=42, for learning rates 0.2 and 0.05. Print the number of trees kept (n_iter_) and the test ROC-AUC for each.
learning_rate 0.2: 53 trees, test ROC-AUC 0.830learning_rate 0.05: 103 trees, test ROC-AUC 0.837for lr in [0.2, 0.05]: # TODO: fit with early stopping; print n_iter_ and the test ROC-AUC ...Hint 1
early_stopping=True holds out 10% of the training rows by default (validation_fraction=0.1).
Hint 2
model.n_iter_ is the number of boosting rounds that were kept.
Solution
kept = {}for lr in [0.2, 0.05]: model = HistGradientBoostingClassifier( learning_rate=lr, max_iter=1000, max_leaf_nodes=15, early_stopping=True, n_iter_no_change=30, categorical_features="from_dtype", random_state=42, ).fit(Xc_train, yc_train) auc = roc_auc_score(yc_test, model.predict_proba(Xc_test)[:, 1]) kept[lr] = model.n_iter_ print(f"learning_rate {lr}: {model.n_iter_} trees, test ROC-AUC {auc:.3f}")assert kept[0.05] > kept[0.2]assert max(kept.values()) < 1000learning_rate 0.2: 53 trees, test ROC-AUC 0.830learning_rate 0.05: 103 trees, test ROC-AUC 0.837How it works:
- Early stopping scores the held-out 10% after each tree and stops when 30 trees in a row bring no gain in the validation loss.
n_iter_counts all fitted trees, including those last 30: scikit-learn does not roll back to the best one. - The smaller learning rate keeps about twice as many trees: each tree corrects less.
- The smaller learning rate also scores a little higher on the test set, the usual result: small steps find a slightly better optimum. These two test scores only illustrate the effect; choose the learning rate with cross-validation or a validation split, not with the test set.
M38-C07 · Bagging or boosting for a weak tree?
Section titled “M38-C07 · Bagging or boosting for a weak tree?”Choose a method and justify it: a depth-2 tree underfits the house prices (high bias). Which ensemble fixes it? Compare on the test set: one depth-2 tree, BaggingRegressor of 50 depth-2 trees (random_state=42) and GradientBoostingRegressor(n_estimators=50, max_depth=2, learning_rate=0.1, random_state=42). Print the three RMSEs.
one depth-2 tree test RMSE 226,151bagging, 50 trees test RMSE 203,280boosting, 50 trees test RMSE 119,620models = { "one depth-2 tree": DecisionTreeRegressor(max_depth=2, random_state=42), # TODO: bagging of 50 depth-2 trees # TODO: gradient boosting with 50 depth-2 trees}# TODO: fit each model and print its test RMSEHint 1
Pass the base tree as the first argument: BaggingRegressor(DecisionTreeRegressor(max_depth=2), n_estimators=50, random_state=42).
Hint 2
Ask which error each method attacks: variance (bagging) or bias (boosting). A depth-2 tree has little variance to remove.
Solution
models = { "one depth-2 tree": DecisionTreeRegressor(max_depth=2, random_state=42), "bagging, 50 trees": BaggingRegressor( DecisionTreeRegressor(max_depth=2), n_estimators=50, random_state=42 ), "boosting, 50 trees": GradientBoostingRegressor( n_estimators=50, max_depth=2, learning_rate=0.1, random_state=42 ),}rmse = {}for name, model in models.items(): model.fit(X_train, y_train) rmse[name] = root_mean_squared_error(y_test, model.predict(X_test)) print(f"{name:<18} test RMSE {rmse[name]:,.0f}")assert rmse["boosting, 50 trees"] < 0.75 * rmse["bagging, 50 trees"]one depth-2 tree test RMSE 226,151bagging, 50 trees test RMSE 203,280boosting, 50 trees test RMSE 119,620How it works:
- A depth-2 tree has only 4 leaves, so it predicts 4 prices. Its error is mostly bias.
- Bagging averages 50 such trees. They are all similar, simple step functions, so the average is still simple. The error barely moves.
- Boosting adds trees that each fit the remaining residuals. Together they build a much richer function, and the error falls sharply. Choose boosting for weak, high-bias learners and bagging for strong, high-variance ones. These test scores only illustrate that rule; on a real project, make the choice with cross-validation on the training rows.
M38-C08 · XGBoost with early stopping
Section titled “M38-C08 · XGBoost with early stopping”Split the churn training set again (20% validation, stratified, random_state=42). Fit XGBClassifier with n_estimators=1000, learning_rate=0.1, max_depth=3, enable_categorical=True, early_stopping_rounds=30, eval_metric="auc", random_state=42 and n_jobs=1, stopping on the validation part. Print the best iteration, the validation AUC and the test ROC-AUC.
best iteration 49 | validation AUC 0.8639test ROC-AUC 0.841Xc_fit, Xc_val, yc_fit, yc_val = train_test_split( Xc_train, yc_train, test_size=0.2, stratify=yc_train, random_state=42)# TODO: create the XGBClassifier with early stopping# TODO: fit with eval_set=[(Xc_val, yc_val)] and verbose=False# TODO: print best_iteration, best_score and the test ROC-AUCHint 1
In XGBoost 3, early_stopping_rounds and eval_metric go in the constructor, not in fit.
Hint 2
model.best_iteration and model.best_score exist after an early-stopped fit.
Solution
Xc_fit, Xc_val, yc_fit, yc_val = train_test_split( Xc_train, yc_train, test_size=0.2, stratify=yc_train, random_state=42)model = XGBClassifier( n_estimators=1000, learning_rate=0.1, max_depth=3, enable_categorical=True, early_stopping_rounds=30, eval_metric="auc", random_state=42, n_jobs=1,)model.fit(Xc_fit, yc_fit, eval_set=[(Xc_val, yc_val)], verbose=False)test_auc = roc_auc_score(yc_test, model.predict_proba(Xc_test)[:, 1])print(f"best iteration {model.best_iteration} | validation AUC {model.best_score:.4f}")print(f"test ROC-AUC {test_auc:.3f}")assert model.best_iteration < 1000 - 30assert test_auc > 0.83best iteration 49 | validation AUC 0.8639test ROC-AUC 0.841How it works:
eval_setis scored after each tree witheval_metric="auc".- Training stops 30 rounds after the best validation AUC.
best_iterationcounts from 0, so the model keepsbest_iteration + 1trees, andpredict_probauses only those. - The test AUC is the honest number. The validation AUC chose the stopping point, so it is slightly optimistic.
M38-C09 · Fix the bug: noisy LightGBM that ignores subsample
Section titled “M38-C09 · Fix the bug: noisy LightGBM that ignores subsample”Fix the bug: this LightGBM model has two problems. Every fit prints [LightGBM] [Info] ... lines, and subsample=0.8 has no effect (the predictions equal those of subsample=1.0). Fix both, keep the seed and one thread, and print whether the subsampled model now differs from the full-data model, plus both test ROC-AUCs.
subsample changes the model: TrueROC-AUC subsample 0.8: 0.838ROC-AUC subsample 1.0: 0.834def make_model(subsample): return lgb.LGBMClassifier(n_estimators=100, learning_rate=0.05, num_leaves=15, subsample=subsample)
sub = make_model(0.8).fit(Xc_train, yc_train)full = make_model(1.0).fit(Xc_train, yc_train)print(np.allclose(sub.predict_proba(Xc_test), full.predict_proba(Xc_test)))Hint 1
One parameter silences LightGBM. Which value of verbose does the lesson use?
Hint 2
LightGBM subsamples rows only every subsample_freq iterations, and the default is 0 (never). Set subsample_freq=1.
Solution
def make_model(subsample: float) -> lgb.LGBMClassifier: return lgb.LGBMClassifier( n_estimators=100, learning_rate=0.05, num_leaves=15, subsample=subsample, subsample_freq=1, # resample rows every round random_state=42, n_jobs=1, verbose=-1, # reproducible and quiet )
sub = make_model(0.8).fit(Xc_train, yc_train)full = make_model(1.0).fit(Xc_train, yc_train)p_sub = sub.predict_proba(Xc_test)[:, 1]p_full = full.predict_proba(Xc_test)[:, 1]print("subsample changes the model:", not np.allclose(p_sub, p_full))print(f"ROC-AUC subsample 0.8: {roc_auc_score(yc_test, p_sub):.3f}")print(f"ROC-AUC subsample 1.0: {roc_auc_score(yc_test, p_full):.3f}")again = make_model(0.8).fit(Xc_train, yc_train).predict_proba(Xc_test)[:, 1]assert np.allclose(p_sub, again) # same seed, same modelassert not np.allclose(p_sub, p_full)subsample changes the model: TrueROC-AUC subsample 0.8: 0.838ROC-AUC subsample 1.0: 0.834How it works:
verbose=-1turns off LightGBM’s info lines and warnings. They go straight to the terminal, so Python’swarningsfilters cannot catch them.subsample_freq=1makes LightGBM draw a new 80% sample of rows for every tree. Without it,subsampleis silently ignored.random_state=42andn_jobs=1make the fit repeatable: the last assert refits and gets the same probabilities.
M38-C10 · Weighted soft voting
Section titled “M38-C10 · Weighted soft voting”Build a soft-voting ensemble of a logistic regression, a random forest (100 trees, min_samples_leaf=3) and LightGBM (100 trees, learning rate 0.05, 15 leaves, quiet, one thread, seed 42). Print the test ROC-AUC of each member, of equal-weight soft voting and of soft voting with weights=[1, 1, 2].
logreg 0.8131forest 0.8281lgbm 0.8338soft equal 0.8371soft 1-1-2 0.8371members = [ ("logreg", make_pipeline(scaled, LogisticRegression(max_iter=1000))), # TODO: the forest pipeline and the LightGBM model]# TODO: ROC-AUC of each member, then of two VotingClassifier(voting="soft") modelsHint 1
The forest needs one_hot in front of it; LightGBM takes the category columns directly.
Hint 2
VotingClassifier(members, voting="soft", weights=[1, 1, 2]) gives LightGBM twice the say of each other member.
Solution
members = [ ("logreg", make_pipeline(scaled, LogisticRegression(max_iter=1000))), ("forest", make_pipeline(one_hot, RandomForestClassifier( n_estimators=100, min_samples_leaf=3, random_state=42))), ("lgbm", lgb.LGBMClassifier( n_estimators=100, learning_rate=0.05, num_leaves=15, random_state=42, n_jobs=1, verbose=-1)),]aucs = {}for name, model in members: model.fit(Xc_train, yc_train) aucs[name] = roc_auc_score(yc_test, model.predict_proba(Xc_test)[:, 1])for label, weights in [("equal", None), ("1-1-2", [1, 1, 2])]: vote = VotingClassifier(members, voting="soft", weights=weights) vote.fit(Xc_train, yc_train) aucs[f"soft {label}"] = roc_auc_score(yc_test, vote.predict_proba(Xc_test)[:, 1])for name, auc in aucs.items(): print(f"{name:<11} {auc:.4f}")assert aucs["soft equal"] > max(aucs["logreg"], aucs["forest"], aucs["lgbm"])logreg 0.8131forest 0.8281lgbm 0.8338soft equal 0.8371soft 1-1-2 0.8371How it works:
- Each member is fitted and scored alone first, so you know what the ensemble must beat.
- Equal-weight soft voting beats every member here. This LightGBM has no row or column subsampling, so it is a little weaker than in the lesson, and the three members err differently enough for the average to gain.
- Weights
[1, 1, 2]give LightGBM half of the vote. The score does not change even in the fourth decimal: the weights matter less than the choice of members. Choosing weights by the test score is tuning on the test set; in a real project, choose them with cross-validation.
M38-C11 · Stacking with and without passthrough
Section titled “M38-C11 · Stacking with and without passthrough”Stack a logistic regression and LightGBM (100 trees, learning rate 0.05, 15 leaves, quiet, one thread, seed 42) with a LogisticRegression meta-learner and cv=StratifiedKFold(5, shuffle=True, random_state=42). Fit it with passthrough=False and with passthrough=True. Print the number of input features of the meta-learner and the test ROC-AUC for both.
passthrough=False meta-learner inputs 2 | test ROC-AUC 0.836passthrough=True meta-learner inputs 24 | test ROC-AUC 0.835base = [ ("logreg", make_pipeline(scaled, LogisticRegression(max_iter=1000))), # TODO: LightGBM]cv = StratifiedKFold(5, shuffle=True, random_state=42)for passthrough in [False, True]: # TODO: build and fit StackingClassifier; print final_estimator_.n_features_in_ ...Hint 1
With passthrough=True, the meta-learner also gets the original features. They must be numeric for a LogisticRegression.
Hint 2
The churn features contain category columns and blanks. Pass scaled as a preprocessing step in front of the stack: make_pipeline(scaled, StackingClassifier(...)). LightGBM then sees the encoded features too.
Solution
base = [ ("logreg", LogisticRegression(max_iter=1000)), ("lgbm", lgb.LGBMClassifier( n_estimators=100, learning_rate=0.05, num_leaves=15, random_state=42, n_jobs=1, verbose=-1)),]cv = StratifiedKFold(5, shuffle=True, random_state=42)aucs = {}for passthrough in [False, True]: stack = make_pipeline(scaled, StackingClassifier( base, final_estimator=LogisticRegression(max_iter=1000), cv=cv, passthrough=passthrough, )).fit(Xc_train, yc_train) meta_inputs = stack[-1].final_estimator_.n_features_in_ aucs[passthrough] = roc_auc_score(yc_test, stack.predict_proba(Xc_test)[:, 1]) print(f"passthrough={passthrough!s:<5} meta-learner inputs {meta_inputs:>2}" f" | test ROC-AUC {aucs[passthrough]:.3f}")assert abs(aucs[True] - aucs[False]) < 0.01passthrough=False meta-learner inputs 2 | test ROC-AUC 0.836passthrough=True meta-learner inputs 24 | test ROC-AUC 0.835How it works:
- The
scaledtransformer one-hot encodes the categories, imputes and scales once, in front of the stack. Both base models and the meta-learner then get numeric inputs. - Without passthrough, the meta-learner sees 2 columns: the out-of-fold churn probability of each base model. With passthrough, it also sees the 22 encoded features (14 one-hot columns and 8 numeric ones), 24 in total.
- The two scores are almost equal. Passthrough rarely helps on small data: the base models already used those features, and the meta-learner gets more weights to fit. Both numbers are test scores, so they only report; decide on
passthroughwith cross-validation on the training rows.
M38-C12 · Interpret a paired comparison
Section titled “M38-C12 · Interpret a paired comparison”Interpret a result: cross-validate a random forest (100 trees, min_samples_leaf=3) and HistGradientBoostingClassifier (learning rate 0.05, max_iter=300, 15 leaves, early stopping, native categories, seed 42) on all churn customers with the same StratifiedKFold(5, shuffle=True, random_state=42). Print both means ± standard deviations, the per-fold differences and the number of folds that boosting wins. Is the gain real?
forest 0.836 ± 0.010boosting 0.847 ± 0.007boosting minus forest per fold: [0.009 0.018 0.003 0.019 0.006]boosting wins 5 of 5 folds, mean gain 0.011cv = StratifiedKFold(5, shuffle=True, random_state=42)forest = make_pipeline(one_hot, RandomForestClassifier( n_estimators=100, min_samples_leaf=3, random_state=42))boost = HistGradientBoostingClassifier( learning_rate=0.05, max_iter=300, max_leaf_nodes=15, early_stopping=True, categorical_features="from_dtype", random_state=42)# TODO: cross_val_score for both with the same cv and scoring="roc_auc"# TODO: print mean ± std, the fold differences and the winsHint 1
cross_val_score(model, X_c, y_c, cv=cv, scoring="roc_auc") returns the 5 fold scores as an array.
Hint 2
With the same folds, diff = boost_scores - forest_scores compares the models on the same customers.
Solution
cv = StratifiedKFold(5, shuffle=True, random_state=42)forest = make_pipeline(one_hot, RandomForestClassifier( n_estimators=100, min_samples_leaf=3, random_state=42))boost = HistGradientBoostingClassifier( learning_rate=0.05, max_iter=300, max_leaf_nodes=15, early_stopping=True, categorical_features="from_dtype", random_state=42)f = cross_val_score(forest, X_c, y_c, cv=cv, scoring="roc_auc")b = cross_val_score(boost, X_c, y_c, cv=cv, scoring="roc_auc")diff = b - fprint(f"forest {f.mean():.3f} ± {f.std():.3f}")print(f"boosting {b.mean():.3f} ± {b.std():.3f}")print("boosting minus forest per fold:", diff.round(3))print(f"boosting wins {(diff > 0).sum()} of 5 folds, mean gain {diff.mean():.3f}")assert (diff > 0).sum() == 5forest 0.836 ± 0.010boosting 0.847 ± 0.007boosting minus forest per fold: [0.009 0.018 0.003 0.019 0.006]boosting wins 5 of 5 folds, mean gain 0.011How it works:
- The two means differ by about one standard deviation, which alone does not look convincing.
- The fold scores move together: a hard fold is hard for both models. The paired differences remove that shared part.
- Boosting wins on every fold. Five wins out of five would happen by chance only about 3% of the time () if the models were equal. The gain is small but real.
M38-C13 · Choose the AdaBoost base tree on a validation split
Section titled “M38-C13 · Choose the AdaBoost base tree on a validation split”Choose a method and justify it: should AdaBoost on churn boost stumps (depth 1) or depth-2 trees? Split the churn training set again (20% validation, stratified, random_state=42). For each depth, fit AdaBoostClassifier with 300 trees, learning_rate=0.5 and random_state=42 after one_hot on the fit part. Use staged_predict_proba to find the number of trees with the best validation ROC-AUC. Print, per depth, the best number of trees, its validation AUC and the validation AUC after 300 trees. Refit the winner with its best number of trees on the full training set and read the test ROC-AUC once.
depth 1: best 300 trees, validation AUC 0.8703 | after 300: 0.8703depth 2: best 233 trees, validation AUC 0.8662 | after 300: 0.8644chosen: depth 1, 300 trees | test ROC-AUC 0.840X_fit, X_val, y_fit, y_val = train_test_split( Xc_train, yc_train, test_size=0.2, stratify=yc_train, random_state=42)best = {}for depth in [1, 2]: # TODO: fit the pipeline on X_fit; staged validation ROC-AUCs # TODO: best number of trees and its AUC; store them in best[depth] ...# TODO: choose the depth, refit on Xc_train with that number of trees, test onceHint 1
ada[-1].staged_predict_proba(ada[0].transform(X_val)) yields the validation probabilities after 1, 2, …, 300 trees. The first step of the pipeline encodes the validation rows.
Hint 2
k = int(np.argmax(staged)) + 1 is the best number of trees. Choose the depth with the highest best AUC: max(best, key=lambda d: best[d][1]) if you store (k, auc).
Solution
X_fit, X_val, y_fit, y_val = train_test_split( Xc_train, yc_train, test_size=0.2, stratify=yc_train, random_state=42)
def adaboost(depth: int, n_trees: int): return make_pipeline(one_hot, AdaBoostClassifier( DecisionTreeClassifier(max_depth=depth), n_estimators=n_trees, learning_rate=0.5, random_state=42, ))
best = {}for depth in [1, 2]: ada = adaboost(depth, 300).fit(X_fit, y_fit) staged = [roc_auc_score(y_val, p[:, 1]) for p in ada[-1].staged_predict_proba(ada[0].transform(X_val))] k = int(np.argmax(staged)) + 1 best[depth] = (k, staged[k - 1]) print(f"depth {depth}: best {k} trees, validation AUC {staged[k - 1]:.4f}" f" | after 300: {staged[-1]:.4f}")depth = max(best, key=lambda d: best[d][1])n_trees = best[depth][0]final = adaboost(depth, n_trees).fit(Xc_train, yc_train)test_auc = roc_auc_score(yc_test, final.predict_proba(Xc_test)[:, 1])print(f"chosen: depth {depth}, {n_trees} trees | test ROC-AUC {test_auc:.3f}")assert depth == 1assert best[2][0] < 300depth 1: best 300 trees, validation AUC 0.8703 | after 300: 0.8703depth 2: best 233 trees, validation AUC 0.8662 | after 300: 0.8644chosen: depth 1, 300 trees | test ROC-AUC 0.840How it works:
- The test set stays out of the choice. The validation split, cut from the training rows, chooses both the depth and the number of trees.
- Stumps improve until the last of the 300 trees. Their best is at the limit, so more trees could still help a little.
- Depth-2 trees peak earlier and then decline. Each tree fits more of the weighted errors, including noise, so the ensemble overfits sooner and ends lower. Weak learners are the better choice for AdaBoost here.
- The winner is refitted on all training rows with its best number of trees, and the test ROC-AUC is read once.
Alternative: cross_val_score with StratifiedKFold for a few (depth, n_estimators) pairs gives a less noisy choice than one validation split, at 5 times the cost.
Challenge
Section titled “Challenge”M38-X01 · Catch the leak in a hand-made stack
Section titled “M38-X01 · Catch the leak in a hand-made stack”Build a stack of a logistic regression and an unpruned random forest (100 trees, default min_samples_leaf=1, seed 42) twice. Leaky version: fit both base models on the training set, predict the same training set, and fit a LogisticRegression meta-learner on those predictions. Honest version: build the meta-features with cross_val_predict and StratifiedKFold(5, shuffle=True, random_state=42). Print the meta-learner weights and the test ROC-AUC of both, plus the forest alone.
leaky weights [[-0.11 12.78]] | test ROC-AUC 0.819honest weights [[2.88 4.01]] | test ROC-AUC 0.830forest alone: test ROC-AUC 0.820base = { "logreg": make_pipeline(scaled, LogisticRegression(max_iter=1000)), "forest": make_pipeline(one_hot, RandomForestClassifier( n_estimators=100, random_state=42)),}cv = StratifiedKFold(5, shuffle=True, random_state=42)# TODO: fit each base model on the training set; test meta-features# TODO: leaky meta-features: in-sample predict_proba on Xc_train# TODO: honest meta-features: cross_val_predict(..., method="predict_proba")# TODO: fit a LogisticRegression on each and compareHint 1
All meta-feature matrices have one column per base model: np.column_stack([...]) of the churn probabilities [:, 1].
Hint 2
The test meta-features are the same for both stacks: predictions of the base models fitted on the full training set.
Hint 3
Print meta.coef_.round(2). A huge weight on one model is the sign of the leak.
Solution
base = { "logreg": make_pipeline(scaled, LogisticRegression(max_iter=1000)), "forest": make_pipeline(one_hot, RandomForestClassifier( n_estimators=100, random_state=42)),}cv = StratifiedKFold(5, shuffle=True, random_state=42)for model in base.values(): model.fit(Xc_train, yc_train)test_meta = np.column_stack([m.predict_proba(Xc_test)[:, 1] for m in base.values()])leaky_meta = np.column_stack([m.predict_proba(Xc_train)[:, 1] for m in base.values()])honest_meta = np.column_stack([ cross_val_predict(m, Xc_train, yc_train, cv=cv, method="predict_proba")[:, 1] for m in base.values()])results = {}for name, meta_x in [("leaky", leaky_meta), ("honest", honest_meta)]: meta = LogisticRegression().fit(meta_x, yc_train) results[name] = roc_auc_score(yc_test, meta.predict_proba(test_meta)[:, 1]) print(f"{name:<6} weights {meta.coef_.round(2)} | test ROC-AUC {results[name]:.3f}")forest_auc = roc_auc_score(yc_test, test_meta[:, 1])print(f"forest alone: test ROC-AUC {forest_auc:.3f}")assert results["honest"] > results["leaky"]leaky weights [[-0.11 12.78]] | test ROC-AUC 0.819honest weights [[2.88 4.01]] | test ROC-AUC 0.830forest alone: test ROC-AUC 0.820How it works:
- An unpruned forest predicts its own training rows almost perfectly. The leaky meta-learner sees a near-perfect feature and puts a very large weight on it.
- On the test set, the forest’s probabilities are much less reliable than the meta-learner believes, and the stack is ranked worse than the honest stack.
- The out-of-fold predictions come from models that never saw each row. They behave like test predictions, so the meta-learner gives sensible weights. This is exactly what
StackingClassifier(cv=...)automates.
Alternative: StackingClassifier(list(base.items()), final_estimator=LogisticRegression(), cv=cv) builds the honest stack in one line and gives the same weights.
M38-X02 · Write a bagging regressor class
Section titled “M38-X02 · Write a bagging regressor class”Refactor procedural bagging into a class. Write SimpleBaggingRegressor(BaseEstimator, RegressorMixin) with n_estimators, max_depth and random_state parameters. fit draws a bootstrap sample per tree with np.random.default_rng(random_state), fits a DecisionTreeRegressor, remembers the out-of-bag rows and computes oob_prediction_ (the mean prediction of the trees that did not see each row). predict averages all trees. Test it with 40 trees on the houses: print the test RMSE, the OOB RMSE and the test R² from the inherited score.
test RMSE 107,013 | OOB RMSE 116,402test R² 0.890SimpleBaggingRegressor(n_estimators=40, random_state=42)from sklearn.base import BaseEstimator, RegressorMixin
class SimpleBaggingRegressor(BaseEstimator, RegressorMixin): def __init__(self, n_estimators=10, max_depth=None, random_state=None): self.n_estimators = n_estimators self.max_depth = max_depth self.random_state = random_state
def fit(self, X, y): # TODO: bootstrap, fit trees, collect OOB sums and counts return self
def predict(self, X): # TODO: mean prediction of all trees ...Hint 1
Convert X and y to NumPy arrays first (np.asarray). Keep two arrays of length n: the sum of OOB predictions and the number of OOB trees per row.
Hint 2
The OOB rows of one tree are np.setdiff1d(np.arange(n), rows). Add the tree’s predictions for them to the sums and 1 to their counts.
Hint 3
A row that is in every bootstrap sample has no OOB prediction. With 40 trees that is very unlikely, but divide with np.divide(..., where=counts > 0) or assert that all counts are positive.
Solution
from sklearn.base import BaseEstimator, RegressorMixin
class SimpleBaggingRegressor(BaseEstimator, RegressorMixin): """Bagged decision trees with an out-of-bag prediction."""
def __init__(self, n_estimators=10, max_depth=None, random_state=None): self.n_estimators = n_estimators self.max_depth = max_depth self.random_state = random_state
def fit(self, X, y): X, y = np.asarray(X), np.asarray(y, dtype=float) n = len(y) rng = np.random.default_rng(self.random_state) oob_sum, oob_count = np.zeros(n), np.zeros(n) self.estimators_ = [] for b in range(self.n_estimators): rows = rng.integers(0, n, size=n) tree = DecisionTreeRegressor(max_depth=self.max_depth, random_state=b) tree.fit(X[rows], y[rows]) out = np.setdiff1d(np.arange(n), rows) # rows this tree never saw oob_sum[out] += tree.predict(X[out]) oob_count[out] += 1 self.estimators_.append(tree) if (oob_count == 0).any(): raise ValueError("some rows were never out of bag; add trees") self.oob_prediction_ = oob_sum / oob_count return self
def predict(self, X): X = np.asarray(X) return np.mean([tree.predict(X) for tree in self.estimators_], axis=0)
bag = SimpleBaggingRegressor(n_estimators=40, random_state=42).fit(X_train, y_train)test_rmse = root_mean_squared_error(y_test, bag.predict(X_test))oob_rmse = root_mean_squared_error(y_train, bag.oob_prediction_)print(f"test RMSE {test_rmse:,.0f} | OOB RMSE {oob_rmse:,.0f}")print(f"test R² {bag.score(X_test, y_test):.3f}")print(bag)assert bag.get_params()["n_estimators"] == 40assert test_rmse < 115_000test RMSE 107,013 | OOB RMSE 116,402test R² 0.890SimpleBaggingRegressor(n_estimators=40, random_state=42)How it works:
BaseEstimatorgives the classget_params,set_paramsand a readablerepr, as long as__init__only stores its arguments.RegressorMixinaddsscore(R²).fitloops over the trees. For each one, it draws a bootstrap sample, fits a tree and adds the tree’s predictions for the rows it never saw tooob_sum.oob_prediction_divides the sums by the counts: each training row is predicted only by the trees that did not see it, about 15 of the 40.- The results are close to
BaggingRegressorin the lesson. Because the class follows the estimator rules, it also works incross_val_scoreand in aPipeline.
M38-X03 · Early stopping by hand
Section titled “M38-X03 · Early stopping by hand”Write a gradient boosting loop for the house prices with depth-3 trees (random_state=42) and learning rate 0.1 that stops early. Split the training set into 80% fit and 20% validation (random_state=42). After each round, compute the validation RMSE. Stop when 15 rounds in a row bring no new best, or after 500 rounds. Keep only the trees up to the best round. Print the stopping round, the best round with its validation RMSE, and the test RMSE of the kept trees.
stopped at round 288best round 273: validation RMSE 90,297test RMSE with 273 trees: 96,998X_fit, X_val, y_fit, y_val = train_test_split( X_train, y_train, test_size=0.2, random_state=42)lr, patience = 0.1, 15f0 = y_fit.mean()pred_fit = np.full(len(y_fit), f0)pred_val = np.full(len(y_val), f0)trees, best_rmse, best_round = [], np.inf, 0for round_no in range(1, 501): # TODO: fit a tree on the residuals, update both predictions # TODO: track the best validation RMSE; stop after `patience` rounds without a gain ...# TODO: predict the test set with f0 and the first best_round treesHint 1
Append each tree to trees. When the validation RMSE is a new best, store it and the round number.
Hint 2
Stop with if round_no - best_round >= patience: break.
Hint 3
The test prediction is f0 + lr * sum(tree.predict(X_test) for tree in trees[:best_round]).
Solution
X_fit, X_val, y_fit, y_val = train_test_split( X_train, y_train, test_size=0.2, random_state=42)lr, patience = 0.1, 15f0 = y_fit.mean()pred_fit = np.full(len(y_fit), f0)pred_val = np.full(len(y_val), f0)trees, best_rmse, best_round = [], np.inf, 0for round_no in range(1, 501): tree = DecisionTreeRegressor(max_depth=3, random_state=42) tree.fit(X_fit, y_fit - pred_fit) trees.append(tree) pred_fit += lr * tree.predict(X_fit) pred_val += lr * tree.predict(X_val) val_rmse = root_mean_squared_error(y_val, pred_val) if val_rmse < best_rmse: best_rmse, best_round = val_rmse, round_no if round_no - best_round >= patience: breakkept = trees[:best_round]pred_test = f0 + lr * np.sum([t.predict(X_test) for t in kept], axis=0)print(f"stopped at round {round_no}")print(f"best round {best_round}: validation RMSE {best_rmse:,.0f}")test_rmse = root_mean_squared_error(y_test, pred_test)print(f"test RMSE with {len(kept)} trees: {test_rmse:,.0f}")assert round_no == best_round + patienceassert len(kept) == best_roundstopped at round 288best round 273: validation RMSE 90,297test RMSE with 273 trees: 96,998How it works:
- Each round fits a tree to the residuals of the fit rows and updates the predictions of the fit and validation rows.
- The validation RMSE is tracked. When it has not improved for 15 rounds, the loop stops.
- Only the trees up to the best round are kept, so the extra 15 rounds do not count. XGBoost and LightGBM predict with the trees up to the best iteration in the same way. scikit-learn’s
HistGradientBoostingdoes not roll back: it keeps alln_iter_trees, including the lastn_iter_no_changethat did not improve. - A patience of 15 can stop at a local plateau. A longer patience, or a smaller learning rate, makes the stop more robust.
M38-X04 · Average LightGBM over seeds
Section titled “M38-X04 · Average LightGBM over seeds”Averaging, the idea behind bagging, works for any randomized model. Fit 5 LightGBM churn models (150 trees, learning rate 0.05, 15 leaves, subsample=0.7 with subsample_freq=1, colsample_bytree=0.7, quiet, one thread) with seeds 0 to 4. Print the test ROC-AUC of each, their mean and range, and the ROC-AUC of the averaged probabilities. Does seed averaging help?
single models: [0.8392 0.8391 0.8358 0.8347 0.8356]mean 0.8369, range 0.0045seed average: 0.8387probs, aucs = [], []for seed in range(5): # TODO: fit LightGBM with random_state=seed; store probabilities and AUC ...# TODO: print the single AUCs, their mean and range, and the AUC of the mean probabilityHint 1
Only random_state changes between the 5 models. Row and column subsampling make the seeds matter.
Hint 2
np.mean(probs, axis=0) averages the 5 probability vectors. Score it like any other prediction.
Solution
probs, aucs = [], []for seed in range(5): model = lgb.LGBMClassifier( n_estimators=150, learning_rate=0.05, num_leaves=15, subsample=0.7, subsample_freq=1, colsample_bytree=0.7, random_state=seed, n_jobs=1, verbose=-1, ).fit(Xc_train, yc_train) p = model.predict_proba(Xc_test)[:, 1] probs.append(p) aucs.append(roc_auc_score(yc_test, p))avg_auc = roc_auc_score(yc_test, np.mean(probs, axis=0))print("single models:", np.round(aucs, 4))print(f"mean {np.mean(aucs):.4f}, range {max(aucs) - min(aucs):.4f}")print(f"seed average: {avg_auc:.4f}")assert avg_auc > np.mean(aucs)single models: [0.8392 0.8391 0.8358 0.8347 0.8356]mean 0.8369, range 0.0045seed average: 0.8387How it works:
- The five models differ only in the random rows and columns they sample. Their AUCs spread over a small range: that spread is the variance that the seed adds.
- Averaging the probabilities removes part of that variance. The seed average scores above the mean single model.
- The gain is small, because the five models are highly correlated (same data, same settings). Seed averaging is cheap insurance that is common in competitions; in production, weigh it against 5 times the prediction cost.
M38-X05 · When an ensemble is not worth it
Section titled “M38-X05 · When an ensemble is not worth it”Choose a method and justify it: on the bundled breast cancer dataset (569 tumors, 30 features, load_breast_cancer), compare a scaled logistic regression, a random forest (200 trees), HistGradientBoostingClassifier (seed 42) and a soft-voting ensemble of the three, with RepeatedStratifiedKFold(n_splits=5, n_repeats=2, random_state=42) and ROC-AUC. Print mean ± standard deviation. Check, without printing the times (they change between runs), whether the voting ensemble takes more than 10 times longer to fit than the logistic regression. Then apply the rule “choose the simplest model whose mean is within one standard deviation of the best mean” and print the choice. The model order from simplest to most complex is the order of the list.
mean stdmodellogistic regression 0.9948 0.0050random forest 0.9896 0.0086gradient boosting 0.9921 0.0052soft voting 0.9949 0.0045best mean: soft voting; within one std: logistic regressionvoting fits more than 10 times slower: Truefrom sklearn.datasets import load_breast_cancerfrom sklearn.model_selection import RepeatedStratifiedKFold
X_b, y_b = load_breast_cancer(return_X_y=True)cv = RepeatedStratifiedKFold(n_splits=5, n_repeats=2, random_state=42)candidates = { "logistic regression": make_pipeline( StandardScaler(), LogisticRegression(max_iter=1000) ), # TODO: random forest, HistGradientBoosting, soft voting of the three}# TODO: cross_validate each; table of mean, std and fit time; apply the ruleHint 1
cross_validate(...)["fit_time"] holds the fit time per fold, in seconds. Compare the means with a ratio.
Hint 2
Find the best mean and its standard deviation. Then walk the candidates in order and take the first whose mean is at least best_mean - best_std.
Solution
from sklearn.datasets import load_breast_cancerfrom sklearn.model_selection import RepeatedStratifiedKFold
X_b, y_b = load_breast_cancer(return_X_y=True)cv = RepeatedStratifiedKFold(n_splits=5, n_repeats=2, random_state=42)logreg = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))forest = RandomForestClassifier(n_estimators=200, random_state=42)boost = HistGradientBoostingClassifier(random_state=42)candidates = { "logistic regression": logreg, "random forest": forest, "gradient boosting": boost, "soft voting": VotingClassifier( [("lr", logreg), ("rf", forest), ("gb", boost)], voting="soft" ),}rows = []for name, model in candidates.items(): res = cross_validate(model, X_b, y_b, cv=cv, scoring="roc_auc") rows.append({"model": name, "mean": res["test_score"].mean(), "std": res["test_score"].std(), "fit_s": res["fit_time"].mean()})table = pd.DataFrame(rows).set_index("model")print(table[["mean", "std"]].to_string(float_format="{:.4f}".format))best = table["mean"].idxmax()bar = table.loc[best, "mean"] - table.loc[best, "std"]choice = next(name for name in table.index if table.loc[name, "mean"] >= bar)print(f"best mean: {best}; within one std: {choice}")ratio = table.loc["soft voting", "fit_s"] / table.loc["logistic regression", "fit_s"]print("voting fits more than 10 times slower:", ratio > 10)assert choice == "logistic regression" mean stdmodellogistic regression 0.9948 0.0050random forest 0.9896 0.0086gradient boosting 0.9921 0.0052soft voting 0.9949 0.0045best mean: soft voting; within one std: logistic regressionvoting fits more than 10 times slower: TrueHow it works:
RepeatedStratifiedKFoldruns 5-fold CV twice with different shuffles: 10 scores per model, all on the same splits for every model.- All four models score above 0.98 ROC-AUC. The differences are a fraction of the fold spread.
- The one-standard-deviation rule picks the logistic regression: its mean is within the noise of the best. It also fits many times faster than the voting ensemble, and its 30 coefficients can be read.
- On a small, almost linearly separable dataset, an ensemble buys complexity, not accuracy.