MLDay 27 of 50Trees and Ensembles
Tune Within a Budget
Your boosted model has four knobs worth tuning.
Your boosted model has four knobs worth tuning. Five values for each makes 625 settings, and with 3-fold cross-validation that's 1,875 fits. You need a good setting without paying for every one.
The idea
A hyperparameter is a setting you choose before training, such as the learning rate. One full choice of them is a candidate. Tuning tests candidates by cross-validation (D10) and keeps the best.
Grid search, as in D11, tries every combination of a few values per knob. It has two problems. Its cost multiplies with each knob you add. And usually only one or two knobs matter, so most of its tries repeat the same few values of them.
Two methods spend a fixed budget (the compute you allow, decided up front) better:
- Random search draws each candidate at random from ranges you give. Every try tests a fresh value of every knob, so the knobs that matter get many values.
- Successive halving trains many candidates on a small slice of the rows. It keeps the best third, gives them three times the rows, and repeats. Weak candidates drop out cheaply.
Both pick by cross-validation on the training rows only. The test set stays out until the very end, scored once.
A tiny example
You have 9 tries for two knobs: the learning rate, which matters, and a second knob, which barely does.
- A 3 × 3 grid tests only 3 learning rates, each three times.
- 9 random tries test 9 different learning rates.
Now halving with 9 candidates, a factor of 3, and 9,000 rows:
| Round | Candidates | Rows each | Rows used |
|---|---|---|---|
| 1 | 9 | 1,000 | 9,000 |
| 2 | 3 | 3,000 | 9,000 |
| 3 | 1 | 9,000 | 9,000 |
That's 27,000 rows in total. Training all 9 on the full 9,000 rows would use 81,000, three times as much.
The formula
How many random tries do you need? Each one lands in the best fraction of the space with chance . So the chance that at least one of tries does is:
| Symbol | Meaning |
|---|---|
| the chance that at least one try lands in the best fraction | |
| that fraction of the search space, e.g. 0.05 for the top 5% | |
| the number of random tries |
Worked: for the top 5% with , . With it's . The count doesn't depend on how many knobs there are.
Try it
Spend the same budget two ways
Darker means a higher score. The good region is a narrow band in A; B hardly changes the score. Grow the budget and compare how many different values of A each strategy tries.
grid trials (their A values ticked along the bottom) · random trials (ticked along the top) · + the true best · green ring: each strategy's best
grid 3 × 3 = 9 trials, 3 values of A, best 0.551random 9 trials, 9 values of A, best 0.9true maximum 0.94
At 9 trials, the 3 × 3 grid tests 3 values of A (the knob that matters) and its best score is 0.551. Random search tests 9 values and reaches 0.900. Raise budget (trials) to 36: the 6 × 6 grid scores only 0.717, worse than its 0.877 at 16, because its values of A step over the narrow good band.
In code
This tunes the boosting model from D25 on the Phase 3 split. The budget is counted in rows: candidates times the rows each one trains on (both searches then run 3 folds). Rows, not seconds, because a row count is the same on every laptop and time isn't. Random search gets 20 candidates on all 24,000 training rows.
# script_id: day_027_tuning_within_a_budget/tune
import os
from pathlib import Path
import pandas as pd
from scipy.stats import loguniform, randint
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.model_selection import RandomizedSearchCV, cross_val_score, train_test_split
DATA_DIR = Path(os.environ.get("ML_DATA", "datasets"))
df = pd.read_csv(DATA_DIR / "credit_default" / "default_of_credit_card_clients.csv")
df = df.drop(columns="ID").rename(columns={"default payment next month": "default"})
X, y = df.drop(columns="default"), df["default"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, stratify=y, random_state=42)
model = HistGradientBoostingClassifier(random_state=42) # the D25 model
space = {"learning_rate": loguniform(0.01, 0.3), "max_leaf_nodes": randint(4, 64),
"min_samples_leaf": randint(20, 500), "l2_regularization": loguniform(0.01, 100)}
default_cv = cross_val_score(model, X_train, y_train, cv=3, scoring="roc_auc").mean()
print(f"default settings: CV AUC {default_cv:.3f}")
rand = RandomizedSearchCV(model, space, n_iter=20, cv=3, scoring="roc_auc", n_jobs=-1, random_state=42)
rand.fit(X_train, y_train)
scores = rand.cv_results_["mean_test_score"]
print(f"random: 20 candidates x {len(X_train):,} rows = {20 * len(X_train):,} rows")
print(f" CV AUC from {scores.min():.3f} to {scores.max():.3f}")
print(" best:", ", ".join(f"{k}={v:.3g}" for k, v in rand.best_params_.items()))
default settings: CV AUC 0.779
random: 20 candidates x 24,000 rows = 480,000 rows
CV AUC from 0.769 to 0.784
best: l2_regularization=0.0921, learning_rate=0.102, max_leaf_nodes=47, min_samples_leaf=283
loguniform(0.01, 0.3) draws as many values between 0.01 and 0.03 as between 0.1 and 0.3, which suits
knobs whose effect grows by ratios. randint(4, 64) draws whole numbers from 4 to 63.
Halving gets 60 candidates. Starting at 2,666 rows, a ninth of the data, makes its three rounds add up to about the same budget.
# script_id: day_027_tuning_within_a_budget/tune
from sklearn.experimental import enable_halving_search_cv # noqa: F401
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import HalvingRandomSearchCV
halv = HalvingRandomSearchCV(model, space, n_candidates=60, factor=3, min_resources=2_666, cv=3,
scoring="roc_auc", n_jobs=-1, random_state=42)
halv.fit(X_train, y_train)
for k, r in zip(halv.n_candidates_, halv.n_resources_):
print(f"halving round: {k:2d} candidates x {r:6,} rows = {k * r:,} rows")
print(f" total {sum(k * r for k, r in zip(halv.n_candidates_, halv.n_resources_)):,} rows")
print(" best:", ", ".join(f"{k}={v:.3g}" for k, v in halv.best_params_.items()))
print(f"best CV AUC: random {rand.best_score_:.3f}, halving {halv.best_score_:.3f}")
winner = max([rand, halv], key=lambda s: s.best_score_)
print(f"winner's test ROC AUC (scored once): {roc_auc_score(y_test, winner.predict_proba(X_test)[:, 1]):.3f}")
halving round: 60 candidates x 2,666 rows = 159,960 rows
halving round: 20 candidates x 7,998 rows = 159,960 rows
halving round: 7 candidates x 23,994 rows = 167,958 rows
total 487,878 rows
best: l2_regularization=0.63, learning_rate=0.0383, max_leaf_nodes=39, min_samples_leaf=289
best CV AUC: random 0.784, halving 0.783
winner's test ROC AUC (scored once): 0.772
For the same rows, halving screened three times as many candidates and finished level with random search. Both landed at the top: random search's 20 candidates ranged from 0.769 to 0.784.
The test score is the honest part. The untuned model scored 0.781 on this test set in D25, so the 0.005 gain in CV didn't survive. A search's best CV score is the highest of many noisy scores, so it runs high. Here the defaults were already near the top; tuning mainly guards against bad settings.
Quick check
Quick check
1. You have 16 tries and only the learning rate matters. How many learning rates do a 4 × 4 grid and 16 random tries test?
2. Halving with a factor of 3 starts 27 candidates on 1,000 rows each. What does round 2 look like?
3. Why score the test set only once, after the search?
Next
D28 brings Phase 3 together: a baseline, a forest and tuned boosting, compared under one protocol on the credit-default data.
Data: Default of Credit Card Clients (UCI Machine Learning Repository, dataset 350), CC BY 4.0; cite Yeh, I.-C. and Lien, C.-H. (2009), "The comparisons of data mining techniques for the predictive accuracy of probability of default of credit card clients", Expert Systems with Applications 36(2).