CertSafari
    Databricks Certified Machine Learning Associate· Lessons

    Domain 3 · Lesson 32/48

    Tuning hyperparameters with Hyperopt fmin

    Use Hyperopt's fmin operation to tune a model's hyperparameters

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

    What you will be able to do

    • Write an objective function that returns a loss fmin can minimize, including negating a score where higher is better
    • Build a search space from hp.choice and numeric distributions, and pick a uniform or log-scaled distribution for each parameter
    • Explain what tpe.suggest does differently from rand.suggest when passed as algo
    • Set max_evals, trials, early_stop_fn and max_queue_len, and use space_eval to recover the real values behind fmin's result

    Key concept

    fmin as a loss minimizer over a search space — fmin repeatedly takes a hyperparameter setting from the search space, passes it to your objective function and records the loss that function returns. After max_evals settings it returns the one with the lowest loss. Hyperopt does not know what your metric means, so the only thing it acts on is the number you return.

    1.The four parts of an fmin workflow

    Hyperopt is a Python library that tunes hyperparameters by trial. You give it a function that trains a model and scores it, and it decides which settings to try next. Each fmin() call is one tuning run, and its arguments split the job into four parts:

    1. Define an objective function to minimize (fn).
    2. Define a search space over the hyperparameters (space).
    3. Select a search algorithm (algo).
    4. Run fmin() with a budget (max_evals), plus optional trials and early_stop_fn arguments.

    A trial is one pass through this loop: Hyperopt picks one point in the space, the objective fits one model with those hyperparameters, and Hyperopt records the loss. Then Hyperopt generates another point and repeats. Most of your code goes into the objective. The other arguments are short declarations that control where Hyperopt looks and for how long.

    Checkpoint 1 of 9· Match them up

    Match each fmin() argument to the part of the tuning workflow it supplies

    Tap a term, then the definition that fits it.

    Sources12

    2.Writing the objective: return a loss to minimize

    The objective function receives one hyperparameter setting and returns a loss. It usually builds the model, trains it and calculates a score. It can return the loss as a plain number or as a dictionary. The dictionary form uses a 'loss' key and a 'status' key set to STATUS_OK.

    An objective for a scikit-learn SVC: train it, score it with cross-validation, and return the negated accuracy as the losspython
    def objective(C):
        # Create a support vector classifier model
        clf = SVC(C=C)
    
        # Use the cross-validation accuracy to compare the models' performance
        accuracy = cross_val_score(clf, X, y).mean()
    
        # Hyperopt tries to minimize the objective function. A higher accuracy value means a better model, so you must return the negative accuracy.
        return {'loss': -accuracy, 'status': STATUS_OK}

    The minus sign is the most important character in that function. fmin always minimizes the returned value. It doesn't check the metric's name, and it has no setting that switches it to maximizing. Accuracy, AUC and F1 are all higher-is-better scores, so the objective returns their negative: maximizing accuracy is the same as minimizing −accuracy. If you return accuracy unchanged, the run still completes without errors, but it carefully searches for the worst model. Each metric's direction is covered in Metric direction: higher-is-better vs lower-is-better (neg_ scorers, minimized losses). For fmin, the rule is to negate any score you want to maximize. A metric that is already lower-is-better, such as RMSE, can be returned unchanged.

    The returned value has to be the score itself. Returning the fitted estimator doesn't work, because Hyperopt never calls a model's score method. Changing the loss artificially, for example multiplying it by the trial number, also doesn't work: Hyperopt would compare a number that no longer measures model quality. One failure is easy to spot in the results. A reported loss of NaN usually means the objective itself returned NaN for that setting. It doesn't affect the other trials, and adjusting the search space or the objective prevents it.

    Checkpoint 2 of 9· Check yourself

    A data scientist's objective function ends with return {'loss': accuracy, 'status': STATUS_OK}, where accuracy is the mean cross-validation accuracy. What happens when they run fmin with this objective?

    Checkpoint 3 of 9· Exam question

    A data scientist is tuning a scikit-learn RandomForestClassifier with Hyperopt's fmin and wants the search to converge on the configuration with the highest cross-validated accuracy. Inside the objective function passed as fn, which return value correctly points fmin toward that configuration?

    Sources213

    3.Defining the search space with hp functions

    The search space tells Hyperopt which values each hyperparameter can take and how likely each value is to be sampled. You build it with functions from hp, and each one gives a hyperparameter a label and a distribution. There are two broad kinds of hyperparameter. A categorical one, such as which algorithm to use, comes from a list through hp.choice. A numeric one comes from a probability distribution, either uniform or log-scaled.

    A one-parameter search space: C is drawn from a log-normal distributionpython
    search_space = hp.lognormal('C', 0, 1.0)

    For each numeric parameter, choose between a uniform and a log scale based on how it affects the model. A uniform distribution samples every part of the range equally, which suits parameters that matter on a linear scale. A log scale samples evenly across orders of magnitude. It suits parameters such as a regularization strength C or a learning rate, where the step from 0.001 to 0.01 matters as much as the step from 0.1 to 1. On a linear scale, almost every sample from that range would land between 0.1 and 1, and the small values would hardly be tested. Parameters that must be whole numbers, such as a number of trees, need a distribution that produces whole-number steps. A real-valued uniform distribution would pass fractional values like 212.7 to the model.

    Two more points make the space work better. First, use what you already know to keep ranges narrow, because a smaller domain gives better results for the same budget. Second, Hyperopt supports conditional hyperparameters. These are parameters that apply to only some of the options of another parameter. If you compare several flavours of gradient descent, for example, each flavour can bring its own settings into the search. You don't have to limit the space to the parameters they all share.

    Checkpoint 4 of 9· Check yourself

    Which search space definition fits a tuning run that picks between logistic regression and an SVC, and also tunes the regularization strength C?

    Checkpoint 5 of 9· Exam question

    A team is defining the search space for fmin to tune a gradient-boosted tree model. n_estimators must always be a whole number of trees, while learning_rate should be sampled on a scale where small values are explored proportionally more finely than large ones. Which pairing of Hyperopt space functions matches these two requirements?

    Sources23

    4.Choosing the algo: tpe.suggest versus rand.suggest

    The algo argument sets the search strategy, and two values are used most often. The strategies themselves are compared in Grid vs random vs Bayesian hyperparameter search. In fmin, choosing a strategy comes down to which suggest function you pass.

    The two common algo values for fmin
    algo valueStrategyHow the next setting is chosen
    hyperopt.tpe.suggestTree of Parzen Estimators (Bayesian)Adaptively, using the losses of earlier trials to favour promising regions
    hyperopt.rand.suggestRandom searchIndependently of earlier results, sampling across the whole space

    The only real difference is whether earlier results influence later picks. TPE records the loss of each trial and moves its sampling toward the regions that have done well so far. Random search treats trial 50 the same as trial 1. This adaptivity makes the Bayesian approach much more efficient than grid or random search, so with TPE you can afford more hyperparameters and wider ranges. Both values work with any parameter type in the space, continuous or categorical. The choice of algo is also separate from where trials run: the basic single-machine fmin call sets algo=tpe.suggest and has no trials argument at all.

    TPE does not guarantee the global optimum within a fixed budget. Both algorithms are stochastic, so the loss usually goes up and down from one trial to the next instead of falling steadily. Even so, these methods often find good hyperparameters faster than the alternatives. A trial with a worse loss than the one before it is normal search behaviour, not a bug.

    Checkpoint 6 of 9· Check yourself

    In a 40-trial fmin run with algo=tpe.suggest, trial 23 reports a higher loss than trial 22. How should this be read?

    Checkpoint 7 of 9· Exam question

    Within Hyperopt, what is the key behavioral difference between passing algo=hyperopt.tpe.suggest versus algo=hyperopt.rand.suggest to fmin?

    Sources13

    5.Running fmin and reading the result

    The call combines the parts above with a budget. max_evals is the number of hyperparameter settings to try, which is also the number of models that will be fitted. It is not a time limit or a count of algorithm iterations. fmin returns the best setting it found.

    Running fmin with TPE and a budget of 16 models, then printing the best setting foundpython
    argmin = fmin(
      fn=objective,
      space=search_space,
      algo=algo,
      max_evals=16)
    
    # Print the best value found for C
    print("Best value found: ", argmin)
    fmin arguments beyond fn, space and algo
    ArgumentWhat it controlsDefault or guidance
    max_evalsNumber of hyperparameter settings to try (models to fit)Set it to your tuning budget
    trialsA Trials or SparkTrials object that records every trialTrials for distributed algorithms such as MLlib; SparkTrials for single-machine ones such as scikit-learn
    early_stop_fnFunction that can end the run before max_evals is reachedNone
    max_queue_lenNumber of settings generated ahead of time1; can be raised, but generally no larger than the SparkTrials parallelism

    The trials object is the record of the run. Every finished trial and its loss is stored there, so the results are still available after fmin returns, and TPE uses those past results to pick the next setting. Which class to pass depends on where the training happens, as covered in SparkTrials vs Trials. early_stop_fn receives that same object. Its signature is Trials, *args in and bool, *args out: the boolean says whether to stop, and the returned *args are passed back in on the next call so the function can keep state between calls. With SparkTrials, this function is polled rather than run after every trial.

    For a categorical parameter, the result is easy to misread. For each hp.choice dimension, fmin's result holds the index of the winning option, and the value logged to MLflow is that index too. Passing the result through hyperopt.space_eval() converts it into the real parameter values, so you can configure the final model directly. Without that step, a kernel recorded as 1 is easily mistaken for a setting someone chose deliberately.

    Checkpoint 8 of 9· Fill the gap

    Fill in the blank: which fmin() argument caps this tuning run at 16 hyperparameter settings, so that 16 models are fitted?

    argmin = fmin(
      fn=objective,
      space=search_space,
      algo=algo,
       ? =16)
    
    # Print the best value found for C
    print("Best value found: ", argmin)

    Checkpoint 9 of 9· Check yourself

    After tuning, the MLflow run shows the parameter 'solver' (defined with hp.choice over three solver names) with the value 2. How should the final model's solver be set?

    Sources23

    Sources

    (3)

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

    1. 1.
      “Define a search space over hyperparameters.”
      ↩︎ The four parts of an fmin workflow
      “Hyperopt tries to minimize the objective function.”
      ↩︎ Writing the objective: return a loss to minimize
      “a Bayesian approach which iteratively and adaptively selects new hyperparameter settings to explore based on past results”
      ↩︎ Choosing the algo: tpe.suggest versus rand.suggest
      “Random search, a non-adaptive approach that samples over the search space”
      ↩︎ Choosing the algo: tpe.suggest versus rand.suggest
      “Hyperopt tries to minimize the objective function. A higher accuracy value means a better model, so you must return the negative accuracy.”
      ↩︎ Exam trap 1
      “Hyperopt tries to minimize the objective function. A higher accuracy value means a better model, so you must return the negative accuracy.”
      ↩︎ Checkpoint
    2. 2.
      “In Hyperopt, a trial generally corresponds to fitting one model on one setting of hyperparameters.”
      ↩︎ The four parts of an fmin workflow
      “Hyperopt is not included in Databricks Runtime for Machine Learning after 16.4 LTS ML.”
      ↩︎ The four parts of an fmin workflow
      “This function can return the loss as a scalar value or in a dictionary”
      ↩︎ Writing the objective: return a loss to minimize
      “You can choose a categorical option such as algorithm, or probabilistic distribution for numeric values such as uniform and log.”
      ↩︎ Defining the search space with hp functions
      “Number of hyperparameter settings to try (the number of models to fit).”
      ↩︎ Running fmin and reading the result
      “An optional early stopping function to determine if fmin should stop before max_evals is reached.”
      ↩︎ Running fmin and reading the result
      “the early stopping function is not guaranteed to run after every trial, and is instead polled”
      ↩︎ Running fmin and reading the result
      “Use Trials when you call distributed training algorithms such as MLlib methods or Horovod in the objective function.”
      ↩︎ Running fmin and reading the result
      “Hyperopt calls this function with values generated from the hyperparameter space provided in the space argument.”
      ↩︎ Key concept
      “Number of hyperparameter settings to try (the number of models to fit).”
      ↩︎ Exam trap 4
      “max_evals | Number of hyperparameter settings to try (the number of models to fit).”
      ↩︎ Checkpoint
    3. 3.
      “A reported loss of NaN (not a number) usually means the objective function passed to fmin() returned NaN.”
      ↩︎ Writing the objective: return a loss to minimize
      “Using domain knowledge to restrict the search domain can optimize tuning and produce better results.”
      ↩︎ Defining the search space with hp functions
      “Take advantage of Hyperopt support for conditional dimensions and hyperparameters.”
      ↩︎ Defining the search space with hp functions
      “Bayesian approaches can be much more efficient than grid search and random search.”
      ↩︎ Choosing the algo: tpe.suggest versus rand.suggest
      “the loss usually does not decrease monotonically with each run”
      ↩︎ Choosing the algo: tpe.suggest versus rand.suggest
      “Therefore the parameter logged in MLflow is also the index.”
      ↩︎ Running fmin and reading the result
      “Because Hyperopt uses stochastic search algorithms, the loss usually does not decrease monotonically with each run.”
      ↩︎ Exam trap 2
      “Use hyperopt.space_eval() to retrieve the parameter values.”
      ↩︎ Exam trap 3
      “Because Hyperopt uses stochastic search algorithms, the loss usually does not decrease monotonically with each run.”
      ↩︎ Checkpoint
      “When you use hp.choice(), Hyperopt returns the index of the choice list.”
      ↩︎ Prediction
      “Therefore the parameter logged in MLflow is also the index. Use hyperopt.space_eval() to retrieve the parameter values.”
      ↩︎ Checkpoint

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