CertSafari
    Databricks Certified Machine Learning Associate· Lessons

    Domain 3 · Lesson 33/48

    Grid, random and Bayesian hyperparameter search

    Perform random or grid search or Bayesian search as a method for tuning hyperparameters.

    15 min read
    2.07% of exam
    9 sources
    Published 22 Oct 2026
    Docs as of 30 Sep 2026

    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.
    How each strategy defines the space, picks settings and sets its cost
    StrategyWhat you defineHow the next setting is chosenWhat fixes the number of fits
    Grid search (GridSearchCV)A list of values per hyperparameterThe next untried combinationThe product of the list lengths
    Random search (hyperopt.rand.suggest)A distribution or choice per hyperparameterAn independent random drawThe trial count you set, such as max_evals
    Bayesian search (hyperopt.tpe.suggest)A distribution or choice per hyperparameterA draw steered by the scores of earlier trialsThe 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.

    Sources12

    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.

    A grid search over two hyperparameters of a pipeline, three values eachpython
    >>> 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?

    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?

    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?

    Sources3245

    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.

    A Ray Tune search space: continuous ranges as distributions, discrete options as choicespython
        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)

    Checkpoint 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?

    Sources4678

    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?

    Sources54

    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.

    An Optuna study on Spark executors: n_trials is the budget, and the default sampler is TPEpython
    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)
    Where the random-or-Bayesian choice is made in each library
    LibraryRandom searchBayesian search
    Hyperoptalgo=rand.suggestalgo=tpe.suggest
    OptunaPass a different samplerDefault: optuna.samplers.TPESampler
    Ray TuneDefault: samples from param_spacePass 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.

    Sources4976

    Sources

    (9)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 1.
      “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. 2.
      “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. 3.
      “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. 4.
      “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. 5.
      “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. 6.
      “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. 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. 8.
      “Scikit-learn also permits evaluation of multiple metrics in GridSearchCV, RandomizedSearchCV and cross_validate.”
      ↩︎ Random search: a fixed budget you set
    9. 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

    Spotted a mistake, or was something unclear? Tell us.