Skip to content

Tuning without fooling yourself

Choose what to search, how far, and how you'll know when to stop. Compare grid, random and Bayesian search, read the trials, and report what you tried.

Applied ~12 min9 steps

What runs in CodeSplash

You will be able to

  • Separate parameters from hyperparameters and say which to tune
  • Choose a search method and a budget
  • Read a tuning run's trials and judge what the search bought

Read first

01

Which settings?

Read

Training learns parameters, like weights and splits. You pick hyperparametersHyperparameterA setting chosen before training (depth, learning rate, penalty) rather than learned from the data.: the settings that fix how it learns.

A few matter a lot. For boosting: rounds and rate, tree size, rows per leaf. Many don't matter much on a given dataset.

So don't search them all. Start with the defaults the app marks: the tune dialog ticks those for you under Hyperparameters to search.

02

Grid or random?

Predict

Predict first

Two hyperparameters, and only one of them really matters. You can afford 9 trials. Grid search gives 3 values each. Random search draws 9 pairs. Which explores the important one better?

Grid: it's more thoroughRandom: it tries more values of the one that mattersThey tie
Reveal

Random. The grid tries only 3 distinct values of the one that matters, while random tries 9. With more settings the gap widens, which is why random search beats grids in high dimensions, as Bergstra and Bengio showed in 2012.

03

Tune by hand first

Explore

Two settings that interact: Learning rate (boosting) and Trees so far. Find three different pairs that all get within 10% of the lowest New-data MSE. Then try a higher Tree depth.

DExplorable · Bagging and boosting

How do many weak trees combine into a strong model?

With up to 200 trees available, at how many trees will error on new data be lowest?

101
How sure?

Method

25
0.20
2
0.35
80
Simulating…

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

You've found a ridge, not a peak. Good settings often lie along a line, and that's why one fixed value and an early stop can replace a big search.

04

Search methods

Read

The app proposes every candidate itself, so a tuning run in Python and the same run in R see the same candidates.

SearchWhat it does
Bayesian (TPE)Learns from earlier trials where good settings are; usually the most efficient
Random searchIndependent draws: a strong, simple baseline
Quasi-random (Sobol)Covers the space more evenly than random
GridA few values per setting, every combination

Weak trials stop after the first folds, using a median rule, so the budget goes further. The presets give Quick, Standard and Thorough.

05

Reading the result

Read

The Tuning tab shows Best settings, Which hyperparameters mattered and every trial.

Tuning historyIs the hyperparameter search still improving, and which trials were pruned?
View data
trialROC AUCstatus
10.8416complete
20.7488complete
30.8209complete
40.8574complete
50.7799complete
60.8580complete
70.8472complete
80.7604complete
90.7422complete
100.8088complete
110.8602complete
120.8702complete
130.8166pruned
140.8471complete
150.8407complete
160.8531complete
170.8381complete
180.8755complete
190.8387complete
200.8472complete
210.8902complete
220.8606complete
230.8275failed
240.8522complete
250.8472complete
260.8377pruned
270.8512complete
280.8413pruned
290.8441pruned
300.8721complete
310.8457pruned
320.8498pruned
330.8576complete
340.8575complete
350.8799complete
360.8251pruned
370.8195pruned
380.8358pruned
390.8675complete
400.8666complete
410.8509pruned
420.8983complete
430.8760complete
440.8549pruned
450.8975complete
460.8746complete
470.8207pruned
480.8513pruned
490.8608complete
500.8708complete
510.9000complete
520.8818complete
530.8875complete
540.8625complete
550.8608complete
560.8899complete
570.8511pruned
580.9000complete
590.8462pruned
600.8412pruned

Dots are trials, and the step line is the best so far. A long flat stretch means more trials will mostly add selection bias. Check whether the best values sit at the edge of a range: that's a sign to widen it.

Then look at the gain. If tuning moved the score by less than the fold-to-fold spread, the default was fine.

06

Your budget

Reflect

Your next model has 2,000 rows and takes a minute to fit on five folds. You have an hour. Which learner would you tune, which three settings, with which preset? How will you report how many trials you ran, so a reader can judge the winner's score?

07

Check your understanding

Checkpoint

Check yourself

Which is a hyperparameter of a random forest?

Show the answer

Answer: b

Thresholds are learned from the data. You set Minimum rows per leaf before training.

Check yourself

The best Learning rate is at the very bottom of the search range. What should you do?

Show the answer

Answer: a

The real optimum may lie outside. Widen the range, but count the extra trials as more selection.

Check yourself

A tuned model's cross-validated AUC is 0.84, and its test AUC is 0.81. The default model's cross-validated AUC is 0.83. What's the fair summary?

Show the answer

Answer: b

The best inner score includes a selection effect, and the one honest look is the test set. Retuning to the test score would spend it.

Check yourself

A grid has 3 values for each of 3 hyperparameters. How many trials is that?

Show the answer

Answer: 27

33=273^3 = 27. Each added setting multiplies the count, and that's why grids don't scale.

08

Run a study

In the app

Select a learner in the Learners step, as the walkthrough does for {{target}}, and press Tune…. Choose Search, a preset, and the hyperparameters. The result joins the leaderboard: open it to read the Tuning tab. Robustness can also show Hyperparameter sensitivity from the trials.

Python
import pandas as pd
from scipy.stats import loguniform, randint
from sklearn.model_selection import RandomizedSearchCV, StratifiedKFold
from xgboost import XGBClassifier

df = pd.read_csv("pima.csv")
X, y = df.drop(columns="diabetic"), df["diabetic"]
space = {"learning_rate": loguniform(0.01, 0.3), "max_depth": randint(2, 7),
         "n_estimators": randint(50, 400), "min_child_weight": loguniform(1, 20)}
search = RandomizedSearchCV(XGBClassifier(), space, n_iter=15, scoring="roc_auc", random_state=1,
                            cv=StratifiedKFold(5, shuffle=True, random_state=1)).fit(X, y)
print(round(search.best_score_, 3), search.best_params_)
R
library(xgboost)
df <- rbind(MASS::Pima.tr, MASS::Pima.te)
X <- as.matrix(df[, setdiff(names(df), "type")])
y <- as.numeric(df$type == "Yes")
set.seed(1)
fold <- sample(rep(1:5, length.out = nrow(X)))
trial <- function() {
  p <- list(learning_rate = exp(runif(1, log(0.01), log(0.3))), max_depth = sample(2:6, 1),
            min_child_weight = exp(runif(1, 0, log(20))), objective = "binary:logistic")
  rounds <- sample(50:400, 1)
  auc <- sapply(1:5, function(k) {
    fit <- xgb.train(p, xgb.DMatrix(X[fold != k, ], label = y[fold != k]), nrounds = rounds, verbose = 0)
    as.numeric(pROC::auc(y[fold == k], predict(fit, X[fold == k, ]), quiet = TRUE))
  })
  c(auc = mean(auc), rate = p$learning_rate, depth = p$max_depth, rounds = rounds)
}
res <- t(replicate(15, trial()))
round(res[which.max(res[, "auc"]), ], 3)
09

Recap

Recap
  • Tune the few settings that matter, starting from good defaults.
  • Random or Bayesian search beats a grid once there are many settings.
  • Read the trials, watch for edges and flat stretches, and report how many you ran.

Concepts in this lesson