What you will be able to do
- Explain how grid, random and Bayesian search each choose the next hyperparameter setting
- Count the model fits a grid search makes, with and without cross-validation folds
- Choose the search strategy that fits a fixed compute budget, a mix of continuous hyperparameters, or a requirement to test every candidate
- Select random or Bayesian search in Hyperopt, Optuna and Ray Tune
Key concept
Adaptive vs non-adaptive search — Grid and random search choose every setting without looking at earlier results. Bayesian search is adaptive: it uses the scores of finished trials to decide which setting to try next.
1.Three ways to choose the next hyperparameter setting
Hyperparameter tuning runs the same loop again and again: pick a setting, fit a model, score it. The three search strategies run that loop the same way. They differ only in how they pick the next setting, and that choice decides how many models you pay for and how good the best one is likely to be.
The three strategies:
- Grid search takes a fixed list of candidate values for each hyperparameter and fits every combination of those lists. A value that isn't on a list is never tried.
- Random search describes each hyperparameter as a distribution or a set of choices, and each trial draws a new sample. It is non-adaptive: the thirtieth trial knows nothing about how the first twenty-nine scored.
- Bayesian search also samples from distributions, but it looks at the scores of finished trials to decide where to sample next. Hyperopt's Tree of Parzen Estimators (TPE) is the Bayesian algorithm you will see most on Databricks.
| Strategy | What you define | How the next setting is chosen | What fixes the number of fits |
|---|---|---|---|
| Grid search (GridSearchCV) | A list of values per hyperparameter | The next untried combination | The product of the list lengths |
| Random search (hyperopt.rand.suggest) | A distribution or choice per hyperparameter | An independent random draw | The trial count you set, such as max_evals |
| Bayesian search (hyperopt.tpe.suggest) | A distribution or choice per hyperparameter | A draw steered by the scores of earlier trials | The trial count you set, such as max_evals |
Checkpoint 1 of 8· Match them up
Match each search strategy to how it picks the next hyperparameter setting.
Tap a term, then the definition that fits it.
Only grid search runs through fixed lists and fits every combination. Random search and TPE both sample from distributions for a trial count you set, such as max_evals. TPE is adaptive and uses past scores to steer its next draw. Random search is non-adaptive.
“hyperopt.tpe.suggest: Tree of Parzen Estimators, a Bayesian approach which iteratively and adaptively selects new hyperparameter settings to explore based on past results”Source: docs.databricks.com
2.Grid search: every combination of fixed lists
In scikit-learn, GridSearchCV takes a param_grid that maps each hyperparameter name to a list of values. The example below lists three values for a PCA step's n_components and three for an SVC's C. That makes 3 × 3 = 9 combinations, and the search fits a model for each configuration. The grid's size is always the product of its list lengths.
>>> from sklearn.model_selection import GridSearchCV
>>> param_grid = dict(reduce_dim__n_components=[2, 5, 10],
... clf__C=[0.1, 10, 100])
>>> grid_search = GridSearchCV(pipe, param_grid=param_grid)Cross-validation multiplies that count. In each fold, one part of the data is held out for testing and the model trains on the rest, so every combination is fit once per fold. Take a random forest with max_depth in [3, 5, 7] and min_samples_leaf in [1, 2, 5, 10], run with cv=5. That is 3 × 4 = 12 combinations times 5 folds, or 60 fits. Twelve forgets the folds. Three hundred multiplies by 5 one time too many. Counting fits for other grid and fold setups belongs to model counts for grid search with cross-validation.
Testing every combination comes with a guarantee the other strategies can't make. Every listed combination gets scored, so grid search is certain to find the best of the candidates you specified. Suppose a compliance review asks for proof that the best logistic regression was chosen from 4 values of C and 2 penalty types. A 4 × 2 grid gives that proof with 8 combinations. Random search with 8 draws doesn't, because independent draws can repeat a setting and miss another. TPE doesn't either. Its search is stochastic, so it promises no particular result.
The cost of that guarantee is that a grid only accepts lists. Hyperopt, by contrast, lets you describe a numeric hyperparameter as a distribution, such as uniform or log-uniform. A grid can't take one. For a continuous hyperparameter such as learning rate, you pick the discrete values yourself, and the grid never tries anything between them. Each new hyperparameter also multiplies the grid. Six hyperparameters at just two values each make 2⁶ = 64 combinations per fold.
Checkpoint 2 of 8· Check yourself
A team has a budget of at most 40 model fits. They need to tune six hyperparameters, one of them a continuous learning rate they want sampled on a log scale. A colleague proposes a GridSearchCV with two candidate values per hyperparameter. What is wrong with that plan?
A grid's size is the product of its list lengths, so 2⁶ = 64 combinations per fold, and cross-validation multiplies that again. A grid only takes lists of values. A distribution such as log-uniform needs a tool like Hyperopt, whose search space accepts one.
“You can choose a categorical option such as algorithm, or probabilistic distribution for numeric values such as uniform and log.”Source: docs.databricks.com
Checkpoint 3 of 8· Exam question
A team is tuning a logistic regression model with only two hyperparameters: regularization strength C (4 candidate values) and penalty type (2 candidate values). For a compliance review, they need a documented guarantee that the best-performing combination among those specified values is found. Which search approach satisfies this requirement?
Correct answer: A — Use GridSearchCV over the 4 x 2 grid, since it exhaustively evaluates all eight combinations and is guaranteed to identify the best-performing one among the specified values.
- A. This is correct:
GridSearchCVfits a model for every combination in the specified grid, so all eight combinations are evaluated and the best-performing one among them is guaranteed to be found. - B. Random sampling with
n_iter=8draws eight candidates independently and can sample the same combination more than once, so it does not guarantee that all eight distinct grid combinations are actually visited. - C. The Tree-structured Parzen Estimator is a heuristic that prioritizes promising regions based on prior trials; it does not exhaustively evaluate every combination and offers no guarantee of finding the true best value among the specified options.
- D. Sampling
Cfrom a continuous distribution produces arbitrary real-valued draws and is very unlikely to land exactly on the four specified grid values, so it does not guarantee coverage of the discrete grid.
Checkpoint 4 of 8· Exam question
A data scientist runs GridSearchCV with param_grid = {'max_depth': [3, 5, 7], 'min_samples_leaf': [1, 2, 5, 10]} and cv=5 on a random forest classifier. Assuming no combination is skipped, how many individual models does this fit in total?
Correct answer: C — 60 model fits
- A. This equals the number of hyperparameter combinations (3 x 4 = 12) but omits the 5-fold cross-validation refit for each combination, so it undercounts the total fits.
- B. This comes from adding the counts of the two parameter lists (3 + 4 = 7) and then multiplying by 5, which mixes up how the grid combines parameter values and does not reflect the actual combinatorics.
- C. This is correct: there are 3 x 4 = 12 hyperparameter combinations, and
cv=5fits a separate model for each combination on every fold, giving 12 x 5 = 60 total model fits. - D. This applies the 5-fold multiplier twice (12 x 5 x 5 = 300), which double-counts the cross-validation step and overstates the true number of fits.
3.Random search: a fixed budget you set
In random search, the budget is a setting you choose. In Hyperopt it is max_evals, the number of settings to try and therefore the number of models to fit. In Optuna it is n_trials, and in Ray Tune it is num_samples. Adding a hyperparameter adds one more value to each draw, not more draws. Forty trials stay forty whether you tune two hyperparameters or six. Pick the number from your compute cap. The search doesn't size it for you. In scikit-learn, RandomizedSearchCV plays the same role that GridSearchCV plays for grids.
param_space={
"lr": tune.loguniform(1e-5, 1e-3),
"lora_r": tune.choice([8, 16, 32]),
"lora_alpha_ratio": tune.choice([1, 2]),
"lora_dropout": tune.uniform(0.0, 0.1),
"weight_decay": tune.choice([0.0, 0.01]),
"batch_size": tune.choice([4, 8]),
},Distributions are where random search gets ahead when only a few hyperparameters really matter. Two values per hyperparameter means a 64-point grid tests exactly two learning rates, however many fits it spends. Forty random trials draw forty separate values from a continuous range like tune.loguniform(1e-5, 1e-3), so you get forty learning rates and forty subsample ratios. The hyperparameters that barely matter are sampled in the same trials, so they cost no extra fits.
Random trials don't depend on each other, so more hardware cuts wall-clock time without changing the search. Ray Tune can give each trial one whole GPU and keeps as many trials in flight as the cluster has GPUs: on a 4-GPU cluster, 4 trials run at once. Wall-clock time therefore tracks the number of samples (num_samples) divided by the number of accelerators. When a sweep runs too long, add accelerators rather than shrinking the search.
Checkpoint 5 of 8· Fill the gap
Your compute cap allows 16 model fits. Which fmin() argument fixes that budget, so the count stays at 16 however many hyperparameters the search space holds?
argmin = fmin(
fn=objective,
space=search_space,
algo=algo,
? =16)In Hyperopt, max_evals is the number of hyperparameter settings to try, which is the number of models to fit. You set it from your compute cap, and adding hyperparameters adds values to each draw, not more draws. Optuna calls its budget n_trials and Ray Tune calls it num_samples, but neither is an fmin() argument.
Source: docs.databricks.comCheckpoint 6 of 8· Exam question
A data scientist is tuning a gradient boosting model with six hyperparameters, several of which are continuous (for example, learning rate and subsample ratio). Compute time is capped at a fixed budget of 40 model fits, and preliminary analysis suggests only two or three of the six hyperparameters meaningfully affect performance. Which search strategy should the data scientist use to stay within budget while tuning effectively?
Correct answer: A — Use RandomizedSearchCV with n_iter=40, since the evaluation budget stays fixed regardless of dimensionality and hyperparameters that do not influence performance do not reduce sampling efficiency.
- A. This is correct: with a fixed
n_iter, the total number of fits never grows with the number of hyperparameters, and because random sampling does not need to cover every combination, hyperparameters with little real effect on the score do not cost extra evaluations. - B. A coarse grid of two values across six hyperparameters produces 2^6 = 64 combinations, which already exceeds the 40-fit budget, so grid search cannot guarantee staying within the limit as dimensionality grows.
- C.
GridSearchCVrequires an explicit list of discrete values for each parameter inparam_grid; it has no mechanism to accept or discretize a continuous distribution object, so this configuration is not valid. - D. The
n_iterparameter ofRandomizedSearchCVdefaults to a fixed value and is set explicitly by the user; it does not automatically scale with the number of hyperparameters being tuned.
4.Bayesian search: letting past trials choose the next one
Bayesian search spends the same kind of budget more carefully. TPE looks at the losses of completed trials and chooses new settings where the results look promising. Each fit therefore teaches it something, which random sampling cannot do. Bayesian approaches can be much more efficient than grid and random search. With TPE you can afford to search more hyperparameters over wider ranges. Domain knowledge still pays off: narrowing the ranges to sensible values gives better results.
Because Bayesian search learns as it goes, it sits awkwardly with running many trials at once. Trials launched together can't learn from each other. For the same number of trials, lower parallelism can therefore give better results, because each new suggestion sees more finished trials. How to set that parallelism is covered in parallelizing single-node models for tuning.
Being adaptive doesn't make the search predictable. TPE is stochastic, so the best loss usually doesn't improve with every run, and nothing guarantees it lands on the global optimum. These methods often find good hyperparameters sooner than other approaches. Only a grid can prove that every listed candidate was checked.
Checkpoint 7 of 8· Check yourself
A team tunes a model with Hyperopt using tpe.suggest and max_evals=48. Which statement about this run holds?
TPE adapts by learning from completed trials, and trials launched together can't learn from each other, so lower parallelism lets each suggestion see more results. TPE is stochastic: its loss doesn't improve steadily and nothing guarantees it reaches the global optimum.
“lower parallelism may lead to better results since each iteration has access to more past results.”Source: docs.databricks.com
5.Choosing random or Bayesian search in Hyperopt, Optuna and Ray Tune
In Hyperopt, the strategy is one argument. fmin takes an objective, a search space, an algo and max_evals (see Hyperopt fmin (objective, search space, algo, max_evals)). You switch between random and Bayesian search by changing algo alone. The two common values are hyperopt.rand.suggest for random search and hyperopt.tpe.suggest for TPE. Hyperopt has no grid algorithm. For an exhaustive search over fixed lists, use GridSearchCV.
Hyperopt is no longer maintained, and it isn't included in Databricks Runtime for Machine Learning after 16.4 LTS ML. Databricks recommends Optuna for single-node tuning and Ray Tune in place of Hyperopt's distributed tuning. Each has its own default strategy. Optuna is Bayesian by default: an Optuna study uses optuna.samplers.TPESampler unless you pass a different sampler. Its default MedianPruner also stops unpromising trials early. Ray Tune samples randomly from param_space unless you give TuneConfig a search_alg, for example Optuna.
from mlflow.pyspark.optuna.study import MlflowSparkStudy
mlflow_study = MlflowSparkStudy(
study_name="spark-mlflow-tuning",
storage=mlflow_storage,
)
mlflow_study.optimize(objective, n_trials=8, n_jobs=4)| Library | Random search | Bayesian search |
|---|---|---|
| Hyperopt | algo=rand.suggest | algo=tpe.suggest |
| Optuna | Pass a different sampler | Default: optuna.samplers.TPESampler |
| Ray Tune | Default: samples from param_space | Pass a search_alg such as Optuna |
Checkpoint 8 of 8· Match them up
A team moving off Hyperopt sets up several tuning jobs. Pair each setup with the search it actually runs.
Tap a term, then the definition that fits it.
Each library has its own default. Optuna uses TPE unless you pass a different sampler. Ray Tune samples randomly unless you give TuneConfig a search_alg. In Hyperopt, the algo argument switches between random search and TPE. None of these run a grid, so an exhaustive search over fixed lists needs GridSearchCV.
“To choose configurations instead of sampling them randomly, pass TuneConfig a search_alg such as Optuna.”Source: docs.databricks.com
Sources
(9)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.https://docs.databricks.com/aws/en/machine-learning/automl-hyperparam-tuning/hyperopt-spark-mlflow-integrationOfficial docs
“hyperopt.rand.suggest: Random search, a non-adaptive approach that samples over the search space”
↩︎ Three ways to choose the next hyperparameter setting“Tree of Parzen Estimators, a Bayesian approach which iteratively and adaptively selects new hyperparameter settings to explore based on past results”
↩︎ Three ways to choose the next hyperparameter setting“a Bayesian approach which iteratively and adaptively selects new hyperparameter settings to explore based on past results”
↩︎ Key concept“hyperopt.rand.suggest: Random search, a non-adaptive approach that samples over the search space”
↩︎ Exam trap 2“hyperopt.tpe.suggest: Tree of Parzen Estimators, a Bayesian approach which iteratively and adaptively selects new hyperparameter settings to explore based on past results”
↩︎ Checkpoint - 2.https://scikit-learn.org/stable/modules/cross_validation.htmlSecondary source
“The best parameters can be determined by grid search techniques.”
↩︎ Three ways to choose the next hyperparameter setting“and the fold left out is used for test.”
↩︎ Grid search: every combination of fixed lists - 3.https://scikit-learn.org/stable/modules/compose.htmlSecondary source
“a grid search in which the transformers can be fitted only once and reused for each configuration”
↩︎ Grid search: every combination of fixed lists“a grid search in which the transformers can be fitted only once and reused for each configuration”
↩︎ Exam trap 1“a grid search in which the transformers can be fitted only once and reused for each configuration”
↩︎ Prediction - 4.https://docs.databricks.com/aws/en/machine-learning/automl-hyperparam-tuning/hyperopt-conceptsOfficial docs
“You can choose a categorical option such as algorithm, or probabilistic distribution for numeric values such as uniform and log.”
↩︎ Grid search: every combination of fixed lists“Number of hyperparameter settings to try (the number of models to fit).”
↩︎ Random search: a fixed budget you set“lower parallelism may lead to better results since each iteration has access to more past results”
↩︎ Bayesian search: letting past trials choose the next one“Most commonly used are hyperopt.rand.suggest for Random Search and hyperopt.tpe.suggest for TPE.”
↩︎ Choosing random or Bayesian search in Hyperopt, Optuna and Ray Tune“Most commonly used are hyperopt.rand.suggest for Random Search and hyperopt.tpe.suggest for TPE.”
↩︎ Exam trap 4“lower parallelism may lead to better results since each iteration has access to more past results.”
↩︎ Checkpoint - 5.https://docs.databricks.com/aws/en/machine-learning/automl-hyperparam-tuning/hyperopt-best-practicesOfficial docs
“Because Hyperopt uses stochastic search algorithms, the loss usually does not decrease monotonically with each run.”
↩︎ Grid search: every combination of fixed lists“Bayesian approaches can be much more efficient than grid search and random search.”
↩︎ Bayesian search: letting past trials choose the next one“you can explore more hyperparameters and larger ranges. Using domain knowledge to restrict the search domain can optimize tuning and produce better results.”
↩︎ Bayesian search: letting past trials choose the next one“However, these methods often find the best hyperparameters more quickly than other methods.”
↩︎ Bayesian search: letting past trials choose the next one“Because Hyperopt uses stochastic search algorithms, the loss usually does not decrease monotonically with each run.”
↩︎ Exam trap 3 - 6.https://docs.databricks.com/aws/en/machine-learning/ai-runtime/cli/examples/ray-tune-loraOfficial docs
“Wall-clock time tracks NUM_SAMPLES / num_accelerators, so raise num_accelerators rather than shrinking the search when a sweep takes too long.”
↩︎ Random search: a fixed budget you set“Ray Tune keeps 4 trials in flight because the cluster has 4 GPUs”
↩︎ Random search: a fixed budget you set“To choose configurations instead of sampling them randomly, pass TuneConfig a search_alg such as Optuna.”
↩︎ Choosing random or Bayesian search in Hyperopt, Optuna and Ray Tune - 7.
“Create a Study, and optimize the objective function with 8 trials (8 calls of the objective function with different values of x).”
↩︎ Random search: a fixed budget you set“optuna.samplers.TPESampler is used as the default.”
↩︎ Choosing random or Bayesian search in Hyperopt, Optuna and Ray Tune“optuna.pruners.MedianPruner is used as the default.”
↩︎ Choosing random or Bayesian search in Hyperopt, Optuna and Ray Tune - 8.https://scikit-learn.org/stable/modules/model_evaluation.htmlSecondary source
“Scikit-learn also permits evaluation of multiple metrics in GridSearchCV, RandomizedSearchCV and cross_validate.”
↩︎ Random search: a fixed budget you set - 9.
“Databricks recommends using either Optuna for single-node optimization or RayTune for a similar experience to the deprecated Hyperopt distributed hyperparameter tuning functionality.”
↩︎ Choosing random or Bayesian search in Hyperopt, Optuna and Ray Tune