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:
- Define an objective function to minimize (
fn). - Define a search space over the hyperparameters (
space). - Select a search algorithm (
algo). - Run
fmin()with a budget (max_evals), plus optionaltrialsandearly_stop_fnarguments.
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.
Each fmin() argument covers one part of the workflow. fn holds the training and scoring code. space says where to look, and algo says how to choose the next point. max_evals counts trials, meaning hyperparameter settings tried and models fitted. It is not a time limit or a count of internal iterations.
“max_evals | Number of hyperparameter settings to try (the number of models to fit).”Source: docs.databricks.com
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.
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?
fmin minimizes whatever number the objective returns and has no idea what the metric means. If it gets accuracy unchanged, it searches for the lowest accuracy. To maximize accuracy, return -accuracy.
“Hyperopt tries to minimize the objective function. A higher accuracy value means a better model, so you must return the negative accuracy.”Source: docs.databricks.com
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?
Correct answer: A — Return the negative of the mean cross-validated accuracy, because fmin always minimizes the returned loss and negating a score to be maximized turns it into a quantity to minimize.
- A. This is correct:
fminis designed only to minimize the scalar it receives, so any metric that should be maximized, like accuracy, has to be negated before it is returned from the objective function. - B. This is incorrect:
fminhas no built-in logic to detect metric names or flip its optimization direction; it always treats the returned number as a loss to minimize, regardless of what the metric represents. - C. This is incorrect:
fmindoes not inspect a returned model object or call itsscoremethod itself; the objective function is responsible for computing and returning the numeric loss explicitly. - D. This is incorrect: multiplying a score by the trial index does not communicate a meaningful loss and would make the objective function noisy and non-monotonic instead of guiding the search toward better configurations.
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.
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?
Categorical hyperparameters such as the algorithm come from a list through hp.choice. Numeric ones come from a probability distribution, and a log scale suits C because its effect depends on order of magnitude. Conditional hyperparameters also mean the space does not have to be limited to shared parameters.
“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 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?
Correct answer: A — Use hp.quniform for n_estimators so the sampled value rounds to an integer step size, and use hp.loguniform for learning_rate so values are drawn evenly across orders of magnitude.
- A. This is correct:
hp.quniformrounds continuous samples to a chosen step son_estimatorsstays an integer count of trees, andhp.loguniformsamples in log space so small learning rates get proportionally as much exploration as large ones. - B. This is incorrect: plain
hp.uniformreturns a float, son_estimatorswould not reliably land on whole tree counts, and applying the same linear scheme tolearning_rateignores that small rates need finer relative exploration. - C. This is incorrect:
hp.choicerestrictsn_estimatorsto a hand-picked list rather than letting the search explore a range, andhp.normalconcentrateslearning_ratesamples near zero instead of spanning the useful range evenly. - D. This is incorrect:
hp.randintforces the range to start at zero and offers no step control forn_estimators, and a linearhp.uniformforlearning_rateunder-samples the small-value region that usually matters most.
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.
| algo value | Strategy | How the next setting is chosen |
|---|---|---|
| hyperopt.tpe.suggest | Tree of Parzen Estimators (Bayesian) | Adaptively, using the losses of earlier trials to favour promising regions |
| hyperopt.rand.suggest | Random search | Independently 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?
TPE uses past losses to favour promising regions, but it is still a stochastic search with no guarantee of steady improvement. A worse loss after a better one is normal, and fmin reports the lowest loss across all trials. rand.suggest is the non-adaptive option, so switching to it would not make the search build on past results.
“Because Hyperopt uses stochastic search algorithms, the loss usually does not decrease monotonically with each run.”Source: docs.databricks.com
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?
Correct answer: A — tpe.suggest uses results from earlier trials to model which regions of the search space look promising, while rand.suggest draws each configuration independently of prior outcomes.
- A. This is correct: the Tree-structured Parzen Estimator behind
tpe.suggestbuilds a probabilistic model from previously evaluated trials to propose promising next points, whereas random search samples each new point independently of history. - B. This is incorrect: neither search algorithm requires a specific
Trialsimplementation; bothtpe.suggestandrand.suggestcan be paired with either plainTrialsorSparkTrials. - C. This is incorrect: both algorithms can sample from any combination of
hp.choice,hp.uniform, and other space definitions; neither is restricted to discrete-only or continuous-only parameters. - D. This is incorrect: no Hyperopt search algorithm guarantees finding the global optimum, and random search does not have a special limitation that caps it at a local optimum; both are heuristic searches over a finite evaluation budget.
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.
argmin = fmin(
fn=objective,
space=search_space,
algo=algo,
max_evals=16)
# Print the best value found for C
print("Best value found: ", argmin)| Argument | What it controls | Default or guidance |
|---|---|---|
| max_evals | Number of hyperparameter settings to try (models to fit) | Set it to your tuning budget |
| trials | A Trials or SparkTrials object that records every trial | Trials for distributed algorithms such as MLlib; SparkTrials for single-machine ones such as scikit-learn |
| early_stop_fn | Function that can end the run before max_evals is reached | None |
| max_queue_len | Number of settings generated ahead of time | 1; 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)max_evals is the number of hyperparameter settings to try, which is also the number of models fitted. It is not a time limit. max_queue_len sets how many settings are generated ahead of time, and early_stop_fn can end the run before the budget is used up.
Source: docs.databricks.comCheckpoint 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?
For hp.choice, both the fmin result and the value logged to MLflow are the index into the choice list. hyperopt.space_eval() converts the result back into the real parameter values that you can use to configure the final model.
“Therefore the parameter logged in MLflow is also the index. Use hyperopt.space_eval() to retrieve the parameter values.”Source: docs.databricks.com
Sources
(3)
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
“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.https://docs.databricks.com/aws/en/machine-learning/automl-hyperparam-tuning/hyperopt-conceptsOfficial docs
“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.https://docs.databricks.com/aws/en/machine-learning/automl-hyperparam-tuning/hyperopt-best-practicesOfficial docs
“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