Sub topic 13
Planning the compute budget
This chapter assumes you can run GridSearchCV and RandomizedSearchCV in scikit-learn, you know what k-fold cross-validation does, and you have read the earlier chapters on search spaces and the grid and random search methods. Here you will learn to estimate what a tuning run will cost before you start it. You will also learn how to split a fixed budget across the choices you control, and how to decide when to stop.
Why plan the budget
Tuning is the most expensive step in many projects. A search that "just runs overnight" can fail at hour eight, and then you have learned nothing. A budget turns tuning into an engineering decision: you decide how much time, money, or hardware to spend, and then choose the search method that gets the most from it.
The budget also affects the quality of your result. Spending it badly, for example on a fine grid over one hyperparameter while ignoring another, gives worse models than a cheaper search that is well planned.
Count the fits
Every tuning run is a number of model fits. Cross-validated search multiplies three factors:
total fits = configurations × folds + refits- Configurations are the grid size, or
n_iterfor random search, or the number of trials in Optuna. - Folds are the
cvvalue. Nested cross-validation multiplies by outer folds as well. - Refits are one extra fit on the whole training set when
refit=True, which is the default.
Grid size grows multiplicatively. Three hyperparameters with 4, 5, and 3 values give 60 configurations. Adding a fourth with 5 values gives 300. This is why grids become impractical beyond three or four dimensions, and why random search lets you fix the number of configurations independently of the dimensions.
Measure the cost of one fit
Do not guess the time per fit. Measure it on your data with a representative configuration. Pay attention to the expensive end of your search space, because large n_estimators, deep trees, and small regularization values usually train slowest.
import time
from math import prod
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
X, y = load_breast_cancer(return_X_y=True)
pipe = make_pipeline(StandardScaler(), SVC(C=10, gamma=0.1))
n_folds = 5
start = time.perf_counter()
cross_val_score(pipe, X, y, cv=n_folds)
seconds_per_fit = (time.perf_counter() - start) / n_folds
param_grid = {
"svc__C": [0.1, 1, 10, 100],
"svc__gamma": [0.0001, 0.001, 0.01, 0.1, 1],
}
n_configs = prod(len(values) for values in param_grid.values())
total_fits = n_configs * n_folds + 1 # +1 for the final refit
workers = 4
estimate = total_fits * seconds_per_fit / workers
print(f"{n_configs} configs, {total_fits} fits")
print(f"about {seconds_per_fit:.3f} s per fit")
print(f"estimated wall-clock time: {estimate:.1f} s on {workers} workers")The estimate is rough. Timing includes scoring, and parallel runs rarely scale perfectly, so treat the result as a lower bound and add a margin of 20 to 50 percent.
Parallelism and its limits
Both GridSearchCV and RandomizedSearchCV accept n_jobs. Setting n_jobs=-1 uses every core, which is usually right for single-threaded models such as SVC or logistic regression with lbfgs.
Be careful when the model is already multithreaded. A random forest with n_jobs=-1 inside a search with n_jobs=-1 can start far more threads than you have cores. This is called oversubscription, and it makes the run slower, not faster. Put the parallelism at one level only: usually the search level, because it has less coordination overhead.
Memory is the other limit. Each worker holds its own copy of the training data and a model, so a large dataset multiplied by many workers can exhaust RAM. If the run slows down or the machine starts swapping, reduce n_jobs.
Where to spend a fixed budget
Total cost is configurations × folds × data size × model cost. You can reduce any one of them. Each choice trades something away.
| Lever | Cheaper option | What you lose |
|---|---|---|
| Configurations | Random search with fewer trials | Coverage of the search space |
| Folds | 3-fold instead of 5- or 10-fold | Lower-quality score estimates, so ranking is noisier |
| Data size | Tune on a subsample | Best settings can shift with more data |
| Model cost | Fewer trees, fewer epochs while searching | Rankings may change at full size |
| Wasted trials | Pruning or successive halving | Risk of discarding slow starters |
A practical rule is to spend on configurations first. In a space where only a few hyperparameters matter, random search tests many distinct values of each important one, while a grid repeats the same few values. Sixty random trials give about a 95 percent chance that at least one lands in the best 5 percent of the space, because 1 − 0.95^60 ≈ 0.95. This holds no matter how many dimensions there are. Treat it as a planning heuristic: it assumes the good region really makes up 5 percent of the space.
Coarse-to-fine search
A common way to stretch a budget is to search in two stages. The first stage uses wide ranges, a cheap evaluation, and few trials, to find where good values live. The second stage narrows the ranges around the best region and spends more per trial, for example with more folds.
Keep the stages honest. Both stages use only training data, with the test set untouched. If the best values sit on the edge of your first range, extend the range instead of narrowing it. A best value at the boundary means the optimum may lie outside.
Spending less per trial with successive halving
Successive halving starts many candidates on a small resource, such as a few samples, then keeps the best fraction and gives it more. Scikit-learn offers HalvingRandomSearchCV, which is still marked experimental and must be enabled by an import.
from scipy.stats import loguniform
from sklearn.datasets import load_breast_cancer
from sklearn.experimental import enable_halving_search_cv # noqa: F401
from sklearn.model_selection import HalvingRandomSearchCV, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=0, stratify=y
)
pipe = make_pipeline(StandardScaler(), SVC())
param_distributions = {
"svc__C": loguniform(1e-2, 1e2),
"svc__gamma": loguniform(1e-4, 1e0),
}
search = HalvingRandomSearchCV(
pipe,
param_distributions,
n_candidates=60,
factor=3,
resource="n_samples",
min_resources=50,
cv=5,
random_state=0,
n_jobs=-1,
)
search.fit(X_train, y_train)
print(search.best_params_)
print("Rounds:", search.n_iterations_)With 60 candidates, factor=3, and a start of 50 samples, about 60 candidates see 50 samples, about 20 see 150, and about 7 see the full training set. That is roughly 9,000 sample-fits, against about 27,000 for scoring all 60 on the full data. The saving is about two thirds. The risk is that a configuration that looks weak on 50 samples might have won on all of them. Large, flexible models and tiny first rounds make this more likely.
Setting a time limit and a stopping rule
Sequential tools let you cap the run by time instead of by count. In Optuna you can pass timeout in seconds, n_trials, or both. The run stops at whichever limit comes first.
import optuna
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
X, y = load_breast_cancer(return_X_y=True)
def objective(trial):
model = RandomForestClassifier(
n_estimators=trial.suggest_int("n_estimators", 50, 300),
max_depth=trial.suggest_int("max_depth", 2, 16),
random_state=0,
)
return cross_val_score(model, X, y, cv=3).mean()
optuna.logging.set_verbosity(optuna.logging.WARNING)
study = optuna.create_study(
direction="maximize", sampler=optuna.samplers.TPESampler(seed=0)
)
study.optimize(objective, n_trials=100, timeout=60)
print(len(study.trials), "trials finished")
print(study.best_params, study.best_value)To decide whether to stop early, look at the best score so far against the trial number. When that curve has been flat for a large share of the trials, more of the same search is unlikely to help. A better use of the remaining budget may be a different model family, better features, or more data. Also compare the improvement to the noise: if the cross-validation standard deviation is 0.01, a gain of 0.001 is not a real gain.
Common budgeting errors
- Skipping the single-fit measurement. Estimates from memory are often wrong by an order of magnitude.
- Forgetting nested cross-validation. An inner search with 100 fits inside 5 outer folds costs about 500 fits, plus refits.
- Oversubscribing threads. Parallel search around a parallel model slows everything down.
- Tuning rarely used settings first. Start with the hyperparameters that usually matter most, such as regularization strength, learning rate, or tree depth.
- Not recording the budget. Note the number of trials, folds, timeout, and hardware. The reporting chapter explains why this matters for reproducibility.
Exercise
A grid has 4 values for C, 5 for gamma, and 3 for class_weight settings. You use 5-fold cross-validation with refit enabled. One fit takes 2 seconds, and you have 4 workers that scale perfectly. How many fits will run, and about how long will the search take?
Show answer
There are 4 × 5 × 3 = 60 configurations. With 5 folds that is 300 fits, plus 1 refit, so 301 fits. At 2 seconds each that is 602 CPU seconds, and across 4 workers about 150 seconds, or 2.5 minutes. Real runs are usually somewhat slower, so plan for a margin.
Exercise
You want a 95 percent chance that random search samples at least one configuration from the best 5 percent of the space. About how many trials do you need, and what assumption does this make?
Show answer
You need n such that 1 − 0.95^n ≥ 0.95. Since 0.95^59 ≈ 0.049, n = 59 trials is enough, so about 60. It assumes the best 5 percent of configurations occupy 5 percent of the sampled space and that trials are independent. If the good region is much smaller, or your ranges are poorly chosen, you need more trials.