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.

By OmniAI Editorial · Nov 22, 2026 · 14 min read

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.

ModelKey hyperparameters
Linear and logistic regressionRegularisation strength (C or alpha), penalty type (L1, L2, elastic net)
Decision treeMax depth, minimum samples per leaf, minimum samples to split
Random forestNumber 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 machineC, kernel, gamma
k-nearest neighboursNumber of neighbours, distance metric, weighting
Neural networksLearning 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.

Two light square panels: the left with grey dots in a regular five-by-five grid, the right with grey dots scattered randomly and one orange dot inside a dotted ink oval.
Grid search tests a few values of each setting; random search tries many more distinct values for the same budget.

Grid search vs random search is the most common comparison, and the evidence favours random search for most problems.

Grid searchRandom search
How it samplesEvery combination of listed valuesRandom combinations from ranges or distributions
CostGrows exponentially with the number of hyperparametersFixed: you choose the number of trials
Coverage of important hyperparametersOnly the few values you listedMany distinct values of each
Finds the best regionIf it lies on the gridWith high probability given enough trials
ParallelFullyFully
Best forOne or two hyperparameters with few, discrete valuesThree or more hyperparameters, continuous ranges
scikit-learn classGridSearchCVRandomizedSearchCV

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 trialsChance at least one lands in the top 5%
20about 64%
60about 95%
100about 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 end

Two 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 typeTune firstThenUsually leave at defaults at first
Neural networksLearning rate (and its schedule)Batch size, weight decay, dropout, model width and depthOptimiser momentum terms, epsilon
Gradient boosting (XGBoost, LightGBM)Learning rate with number of trees (use early stopping), max depth or number of leavesSubsample, column sample, min child weight, L1 and L2 regularisationRarely changed niche settings
Random forestMax features per split, min samples per leafNumber of trees (more is usually better, up to cost), max depthSplit criterion
SVMC and gamma, together, on log scalesKernel—
Regularised linear modelsRegularisation strengthPenalty 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:

  1. Fix a learning rate around 0.05 to 0.1 and set a large maximum number of trees.
  2. 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.
  3. 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.
  4. Add regularisation (L1 and L2 penalties, sampled on log scales) if the model still overfits.
  5. 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.
Three light boxes joined by ink arrows: a large one with six grey bars, a smaller one with three grey bars, and, behind a dotted ink line, a small box holding one grey block outlined in orange.
Tune on validation data and touch the test set only once.

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

ToolMethodsGood for
scikit-learnGrid, random, successive halving (experimental)Classic machine learning models, quick experiments
OptunaTPE (Bayesian), CMA-ES, random, grid, pruningGeneral-purpose tuning in Python, including deep learning
Ray TuneRandom, Bayesian, Hyperband, ASHA, population-based trainingDistributed tuning across many machines
KerasTunerRandom, Bayesian, HyperbandKeras and TensorFlow models
Cloud servicesManaged Bayesian search on cloud training jobsTeams 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.

All articles

Read next

Language

EnglishEnglish · en TürkçeTurkish · tr DeutschGerman · de العربيةArabic · ar

Account

Enter your email. We’ll send you a sign-in link and a 6-digit code. No password needed.

Sign in

Theme

Language

Show our email address

To keep spam out of our inbox, please confirm your own email first. We will send you a 6-digit code.

We send codes only to these providers: gmail.com, googlemail.com, outlook.com, hotmail.com, live.com, msn.com, proton.me, protonmail.com, pm.me, icloud.com, me.com, mac.com, yahoo.com, aol.com, gmx.de, gmx.net, web.de, t-online.de, yandex.com, omniai.blog