AI
Hyperparameter Tuning: Methods That Actually Work
Hyperparameter tuning explained: grid vs random search, Bayesian optimization, Hyperband, Optuna and scikit-learn code, what to tune first and mistakes.
Hyperparameter tuning is the process of finding the settings that control how a machine learning model learns, such as learning rate, tree depth, regularisation strength or batch size, so the model performs as well as possible on data it hasn't seen. Unlike model weights, hyperparameters aren't learned during training; you choose them, train, measure on a validation set, and repeat. The methods that work best in practice are random search for a quick baseline, Bayesian optimization or Hyperband-style early stopping when each training run is expensive, and always a held-out test set that tuning never touches.
This guide explains what hyperparameters are, the main hyperparameter optimization methods (grid search vs random search, Bayesian optimization, successive halving and Hyperband, population-based training), a hyperparameter tuning example in scikit-learn and Optuna, which hyperparameters to tune first for common models, how to avoid overfitting the validation set, and the mistakes that waste compute.
What Are Hyperparameters?
A model has two kinds of numbers:
- Parameters are learned from data during training: the weights of a neural network, the split thresholds in a decision tree, the coefficients of a regression.
- Hyperparameters are set before training and control how learning happens: how fast weights change (learning rate), how complex the model can get (tree depth, number of layers), how strongly it's penalised for complexity (regularisation), and how training proceeds (batch size, number of epochs).
Hyperparameters matter because the same algorithm can go from useless to excellent depending on them. A learning rate ten times too high can make a neural network diverge; a tree that's too deep memorises noise. Our guide to regularization in machine learning explains how several of these settings control overfitting.
| Model | Key hyperparameters |
|---|---|
| Linear and logistic regression | Regularisation strength (C or alpha), penalty type (L1, L2, elastic net) |
| Decision tree | Max depth, minimum samples per leaf, minimum samples to split |
| Random forest | Number of trees, max depth, max features per split, minimum samples per leaf |
| Gradient boosting (XGBoost, LightGBM) | Learning rate, number of trees, max depth or leaves, subsample, column sample, regularisation |
| Support vector machine | C, kernel, gamma |
| k-nearest neighbours | Number of neighbours, distance metric, weighting |
| Neural networks | Learning rate, batch size, optimiser and its settings, number and width of layers, dropout, weight decay, epochs, learning rate schedule |
Hyperparameter Optimization Methods
There are five main hyperparameter optimization methods, from simplest to most sophisticated.
1. Manual tuning
Change one setting, retrain, compare. It's how most people start, and with experience it can be efficient, but it's hard to reproduce, biased by intuition and slow to cover many settings.
2. Grid search
Define a list of values for each hyperparameter and train on every combination. Grid search is exhaustive, simple and easy to parallelise. Its problem is the combinatorial explosion: four hyperparameters with five values each is 5⁴ = 625 combinations, and with 5-fold cross-validation that's 3,125 training runs. Add one more hyperparameter and it multiplies again.
3. Random search
Sample each hyperparameter from a range or distribution and train a fixed number of random combinations. James Bergstra and Yoshua Bengio's 2012 paper "Random Search for Hyper-Parameter Optimization" showed that random search usually finds as good or better settings than grid search with far fewer trials, because typically only a few hyperparameters really matter, and random sampling tries many more distinct values of each one.
4. Bayesian optimization
Build a model of how hyperparameters affect validation score, using the results so far, and use it to pick the most promising next setting. That makes Bayesian hyperparameter optimization sample-efficient: it spends trials near good regions while still exploring. Common surrogate models include Gaussian processes (popularised for machine learning by Snoek, Larochelle and Adams in 2012) and tree-structured Parzen estimators (TPE), the default in the Optuna library. The trade-off is that it's partly sequential, since each choice depends on earlier results, so it parallelises less naturally than random search.
5. Early-stopping methods: successive halving, Hyperband and PBT
Instead of training every configuration fully, start many configurations on a small budget (a few epochs or a subset of data), keep the best fraction, give them more budget, and repeat. Successive halving does this in rounds; Hyperband (Li and colleagues, JMLR 2018) runs successive halving with several trade-offs between number of configurations and budget per configuration. Population-based training (DeepMind, 2017) trains a population of models in parallel, periodically copying the weights of strong performers into weak ones and perturbing their hyperparameters, so schedules evolve during training.
Grid Search vs Random Search
Grid search vs random search is the most common comparison, and the evidence favours random search for most problems.
| Grid search | Random search | |
|---|---|---|
| How it samples | Every combination of listed values | Random combinations from ranges or distributions |
| Cost | Grows exponentially with the number of hyperparameters | Fixed: you choose the number of trials |
| Coverage of important hyperparameters | Only the few values you listed | Many distinct values of each |
| Finds the best region | If it lies on the grid | With high probability given enough trials |
| Parallel | Fully | Fully |
| Best for | One or two hyperparameters with few, discrete values | Three or more hyperparameters, continuous ranges |
| scikit-learn class | GridSearchCV | RandomizedSearchCV |
Worked example: how many random trials do you need?
Suppose the best 5% of the search space gives results you'd be happy with. Each random trial has a 5% chance of landing there, so the chance that at least one of n trials does is 1 − 0.95ⁿ:
| Random trials | Chance at least one lands in the top 5% |
|---|---|
| 20 | about 64% |
| 60 | about 95% |
| 100 | about 99.4% |
So about 60 random trials give a 95% chance of finding a top-5% configuration, regardless of how many hyperparameters you're tuning, while a grid over four hyperparameters with five values each would need 625 trials and might still miss the best region between grid points. This simple argument is why random search is the recommended default over grid search.
Hyperparameter Tuning Example in scikit-learn
Here's a hyperparameter tuning example with scikit-learn's RandomizedSearchCV, tuning a gradient boosting classifier with 5-fold cross-validation:
from scipy.stats import loguniform, randint
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.model_selection import RandomizedSearchCV, train_test_split
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)
param_distributions = {
"learning_rate": loguniform(1e-3, 3e-1), # sample on a log scale
"max_depth": randint(2, 10),
"max_leaf_nodes": randint(8, 64),
"l2_regularization": loguniform(1e-6, 1.0),
}
search = RandomizedSearchCV(
HistGradientBoostingClassifier(random_state=0),
param_distributions,
n_iter=60, # 60 random configurations
cv=5,
scoring="roc_auc",
n_jobs=-1,
random_state=0,
)
search.fit(X_train, y_train)
print(search.best_params_, search.best_score_)
print("held-out test score:", search.score(X_test, y_test)) # evaluate once, at the endTwo details matter: continuous hyperparameters like learning rate and regularisation are sampled on a log scale, because the difference between 0.001 and 0.01 matters as much as between 0.1 and 1; and the test set is used exactly once, after tuning.
scikit-learn also offers HalvingGridSearchCV and HalvingRandomSearchCV, which implement successive halving; they're still marked experimental and need from sklearn.experimental import enable_halving_search_cv before importing them.
Bayesian Hyperparameter Optimization With Optuna
Optuna is a popular open-source framework for Bayesian hyperparameter optimization. You write an objective function that trains a model with suggested hyperparameters and returns a score:
import optuna
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.model_selection import cross_val_score
def objective(trial):
params = {
"learning_rate": trial.suggest_float("learning_rate", 1e-3, 3e-1, log=True),
"max_depth": trial.suggest_int("max_depth", 2, 10),
"l2_regularization": trial.suggest_float("l2_regularization", 1e-6, 1.0, log=True),
}
model = HistGradientBoostingClassifier(random_state=0, **params)
return cross_val_score(model, X_train, y_train, cv=5, scoring="roc_auc").mean()
study = optuna.create_study(direction="maximize") # TPE sampler by default
study.optimize(objective, n_trials=60)
print(study.best_params, study.best_value)For neural networks, Optuna's pruners can stop unpromising trials early: report the validation score after each epoch with trial.report() and check trial.should_prune(), which brings Hyperband-style savings to Bayesian search. Ray Tune offers similar capabilities with distributed execution across many machines.
Hyperparameter Tuning: What to Tune First
Tuning everything at once wastes compute. Start with the settings that matter most:
| Model type | Tune first | Then | Usually leave at defaults at first |
|---|---|---|---|
| Neural networks | Learning rate (and its schedule) | Batch size, weight decay, dropout, model width and depth | Optimiser momentum terms, epsilon |
| Gradient boosting (XGBoost, LightGBM) | Learning rate with number of trees (use early stopping), max depth or number of leaves | Subsample, column sample, min child weight, L1 and L2 regularisation | Rarely changed niche settings |
| Random forest | Max features per split, min samples per leaf | Number of trees (more is usually better, up to cost), max depth | Split criterion |
| SVM | C and gamma, together, on log scales | Kernel | — |
| Regularised linear models | Regularisation strength | Penalty mix (L1 ratio) | Solver |
For gradient boosting in particular, a robust recipe is: fix a moderately small learning rate, use early stopping on a validation set to choose the number of trees automatically, then tune tree size and sampling parameters, and finally lower the learning rate and increase trees for a last gain. For neural networks, the learning rate is almost always the single most important hyperparameter, and it interacts with batch size; our epoch vs batch size guide explains that link.
Hyperparameter Tuning for XGBoost
Gradient-boosted trees are where many people first tune seriously, and "best hyperparameter tuning method for XGBoost" is a frequent question. A practical approach that works for XGBoost and LightGBM alike:
- Fix a learning rate around 0.05 to 0.1 and set a large maximum number of trees.
- Use early stopping on a validation set (for example, stop when the validation metric hasn't improved for 50 rounds) so the number of trees is chosen automatically.
- Random or Bayesian search over tree shape and sampling, with ranges such as max depth 3 to 10 (or number of leaves for LightGBM), minimum child weight 1 to 10, row subsample 0.5 to 1.0 and column sample 0.5 to 1.0.
- Add regularisation (L1 and L2 penalties, sampled on log scales) if the model still overfits.
- Finish by lowering the learning rate (for example halving it) and letting early stopping pick more trees, which usually gives a small final gain.
Fifty to a hundred trials of step 3 with early stopping is often enough. The data matters more than squeezing the last decimal from hyperparameters: check for leakage and good features before spending more compute.
Hyperparameter Tuning vs Cross Validation vs Feature Engineering
These terms come up together but do different jobs:
- Cross-validation is a way to measure performance more reliably by training and validating on several splits of the data. Tuning uses it to score each candidate configuration.
- Hyperparameter tuning is the search over settings, using cross-validation (or a validation set) as its scoring method.
- Feature engineering changes the inputs: creating, transforming or selecting features. It often improves results more than tuning, and should come first.
- Training fits the model's parameters for one fixed set of hyperparameters; tuning repeats training many times.
How to Read Tuning Results
Don't just copy the best configuration. Look at the whole search:
- Check the edges. If the best value of a hyperparameter sits at the edge of your range, widen the range and search again.
- Look at importance. Optuna's visualisation module (for example
plot_param_importances) and similar tools show which hyperparameters drove the score; fix unimportant ones and focus future searches. - Look at stability. If the top ten configurations are spread across very different settings with similar scores, the model isn't sensitive to them, and a simpler, cheaper configuration may be just as good.
- Re-run the winner with different seeds to confirm the gain isn't noise.
Avoiding Overfitting the Validation Set
Tuning is itself a form of learning: try enough configurations and you'll find one that looks great on your validation data by luck. Protect against that:
- Split three ways: training data to fit, validation data (or cross-validation) to choose hyperparameters, and a test set used once at the end.
- Use cross-validation for small datasets, so the score doesn't depend on one lucky split.
- Use nested cross-validation when you need an unbiased estimate of the whole tuning procedure's performance, for example in research or model comparisons.
- Respect time and groups: for time series, validate on later periods than you train on; for grouped data (several rows per customer), keep each group in one split.
- Be suspicious of tiny gains: a 0.2% improvement after 500 trials may be noise.
Hyperparameter Tuning for Large Models
Full hyperparameter searches become impractical for very large neural networks, where one training run can cost thousands of GPU hours. Practitioners instead:
- Tune on smaller models or shorter runs and transfer the best settings, adjusting for scale.
- Reuse published recipes: large language model papers report the learning rates, schedules and batch sizes that worked, which are better starting points than any search.
- Search only the few settings that matter, usually learning rate and its warmup and decay, with a handful of runs.
- Use early stopping and pruning so poor runs end quickly.
Our how to train an AI model guide covers where tuning fits in the full training workflow.
Hyperparameter Optimization Tools
| Tool | Methods | Good for |
|---|---|---|
| scikit-learn | Grid, random, successive halving (experimental) | Classic machine learning models, quick experiments |
| Optuna | TPE (Bayesian), CMA-ES, random, grid, pruning | General-purpose tuning in Python, including deep learning |
| Ray Tune | Random, Bayesian, Hyperband, ASHA, population-based training | Distributed tuning across many machines |
| KerasTuner | Random, Bayesian, Hyperband | Keras and TensorFlow models |
| Cloud services | Managed Bayesian search on cloud training jobs | Teams already training on a cloud ML platform |
Common Mistakes
- Tuning on the test set, which makes reported results optimistic and unreliable.
- Using a grid for many continuous hyperparameters, wasting most trials on unimportant dimensions.
- Linear ranges for scale-like settings such as learning rate and regularisation; use log scales.
- Tuning before fixing the data pipeline, when leakage or bad features matter far more than hyperparameters.
- Ignoring variance: comparing single runs with different random seeds as if differences were real.
- Searching ranges that are too narrow, so the best value sits at the edge; widen the range and search again.
- Spending days on tuning when a better model choice or more data would help more.
FAQ
What is hyperparameter tuning in machine learning?
It's choosing the settings that control how a model learns, such as learning rate, depth or regularisation, by training with different values and comparing performance on validation data.
Is random search better than grid search?
Usually, for more than two hyperparameters. Random search tries more distinct values of each important hyperparameter for the same budget, so it tends to find good settings with fewer trials.
What is Bayesian hyperparameter optimization?
A method that models how hyperparameters relate to performance using the trials so far, then picks the most promising next configuration. It's more sample-efficient than random search when each training run is expensive.
How many trials do I need?
There's no fixed number, but 50 to 100 random or Bayesian trials is a common starting budget for classic models. For expensive neural networks, use early stopping methods and fewer, well-chosen trials.
What's the difference between hyperparameter tuning and fine-tuning?
Hyperparameter tuning chooses training settings. Fine-tuning continues training a pretrained model on new data, which itself requires choosing hyperparameters such as the learning rate.