The loop API is the most lightweight way to do optimization in Ax. The user makes one call to optimize
, which performs all of the optimization under the hood and returns the optimized parameters.
For more customizability of the optimization procedure, consider the Service or Developer API.
import numpy as np
from ax.plot.contour import plot_contour
from ax.plot.trace import optimization_trace_single_method
from ax.service.managed_loop import optimize
from ax.metrics.branin import branin
from ax.utils.measurement.synthetic_functions import hartmann6
from ax.utils.notebook.plotting import render, init_notebook_plotting
init_notebook_plotting()
[INFO 09-28 16:12:30] ax.utils.notebook.plotting: Injecting Plotly library into cell. Do not overwrite or delete cell.
First, we define an evaluation function that is able to compute all the metrics needed for this experiment. This function needs to accept a set of parameter values and can also accept a weight. It should produce a dictionary of metric names to tuples of mean and standard error for those metrics.
def hartmann_evaluation_function(parameterization):
x = np.array([parameterization.get(f"x{i+1}") for i in range(6)])
# In our case, standard error is 0, since we are computing a synthetic function.
return {"hartmann6": (hartmann6(x), 0.0), "l2norm": (np.sqrt((x ** 2).sum()), 0.0)}
If there is only one metric in the experiment – the objective – then evaluation function can return a single tuple of mean and SEM, in which case Ax will assume that evaluation corresponds to the objective. It can also return only the mean as a float, in which case Ax will treat SEM as unknown and use a model that can infer it. For more details on evaluation function, refer to the "Trial Evaluation" section in the docs.
The setup for the loop is fully compatible with JSON. The optimization algorithm is selected based on the properties of the problem search space.
best_parameters, values, experiment, model = optimize(
parameters=[
{
"name": "x1",
"type": "range",
"bounds": [0.0, 1.0],
"value_type": "float", # Optional, defaults to inference from type of "bounds".
"log_scale": False, # Optional, defaults to False.
},
{
"name": "x2",
"type": "range",
"bounds": [0.0, 1.0],
},
{
"name": "x3",
"type": "range",
"bounds": [0.0, 1.0],
},
{
"name": "x4",
"type": "range",
"bounds": [0.0, 1.0],
},
{
"name": "x5",
"type": "range",
"bounds": [0.0, 1.0],
},
{
"name": "x6",
"type": "range",
"bounds": [0.0, 1.0],
},
],
experiment_name="test",
objective_name="hartmann6",
evaluation_function=hartmann_evaluation_function,
minimize=True, # Optional, defaults to False.
parameter_constraints=["x1 + x2 <= 20"], # Optional.
outcome_constraints=["l2norm <= 1.25"], # Optional.
total_trials=30, # Optional.
)
[INFO 09-28 16:12:30] ax.service.utils.instantiation: Inferred value type of ParameterType.FLOAT for parameter x2. If that is not the expected value type, you can explicity specify 'value_type' ('int', 'float', 'bool' or 'str') in parameter dict. [INFO 09-28 16:12:30] ax.service.utils.instantiation: Inferred value type of ParameterType.FLOAT for parameter x3. If that is not the expected value type, you can explicity specify 'value_type' ('int', 'float', 'bool' or 'str') in parameter dict. [INFO 09-28 16:12:30] ax.service.utils.instantiation: Inferred value type of ParameterType.FLOAT for parameter x4. If that is not the expected value type, you can explicity specify 'value_type' ('int', 'float', 'bool' or 'str') in parameter dict. [INFO 09-28 16:12:30] ax.service.utils.instantiation: Inferred value type of ParameterType.FLOAT for parameter x5. If that is not the expected value type, you can explicity specify 'value_type' ('int', 'float', 'bool' or 'str') in parameter dict. [INFO 09-28 16:12:30] ax.service.utils.instantiation: Inferred value type of ParameterType.FLOAT for parameter x6. If that is not the expected value type, you can explicity specify 'value_type' ('int', 'float', 'bool' or 'str') in parameter dict. [INFO 09-28 16:12:30] ax.service.utils.instantiation: Created search space: SearchSpace(parameters=[RangeParameter(name='x1', parameter_type=FLOAT, range=[0.0, 1.0]), RangeParameter(name='x2', parameter_type=FLOAT, range=[0.0, 1.0]), RangeParameter(name='x3', parameter_type=FLOAT, range=[0.0, 1.0]), RangeParameter(name='x4', parameter_type=FLOAT, range=[0.0, 1.0]), RangeParameter(name='x5', parameter_type=FLOAT, range=[0.0, 1.0]), RangeParameter(name='x6', parameter_type=FLOAT, range=[0.0, 1.0])], parameter_constraints=[ParameterConstraint(1.0*x1 + 1.0*x2 <= 20.0)]). [INFO 09-28 16:12:30] ax.modelbridge.dispatch_utils: Using Bayesian optimization since there are more ordered parameters than there are categories for the unordered categorical parameters. [INFO 09-28 16:12:30] ax.modelbridge.dispatch_utils: Using Bayesian Optimization generation strategy: GenerationStrategy(name='Sobol+GPEI', steps=[Sobol for 12 trials, GPEI for subsequent trials]). Iterations after 12 will take longer to generate due to model-fitting. [INFO 09-28 16:12:30] ax.service.managed_loop: Started full optimization with 30 steps. [INFO 09-28 16:12:30] ax.service.managed_loop: Running optimization trial 1... /home/runner/work/Ax/Ax/ax/core/observation.py:274: FutureWarning: In a future version of pandas, a length 1 tuple will be returned when iterating over a groupby with a grouper equal to a list of length 1. Don't supply a list with a single grouper to avoid this warning. [INFO 09-28 16:12:30] ax.service.managed_loop: Running optimization trial 2... [INFO 09-28 16:12:30] ax.service.managed_loop: Running optimization trial 3... [INFO 09-28 16:12:30] ax.service.managed_loop: Running optimization trial 4... [INFO 09-28 16:12:30] ax.service.managed_loop: Running optimization trial 5... [INFO 09-28 16:12:30] ax.service.managed_loop: Running optimization trial 6... [INFO 09-28 16:12:30] ax.service.managed_loop: Running optimization trial 7... [INFO 09-28 16:12:30] ax.service.managed_loop: Running optimization trial 8... [INFO 09-28 16:12:30] ax.service.managed_loop: Running optimization trial 9... [INFO 09-28 16:12:30] ax.service.managed_loop: Running optimization trial 10... [INFO 09-28 16:12:30] ax.service.managed_loop: Running optimization trial 11... [INFO 09-28 16:12:30] ax.service.managed_loop: Running optimization trial 12... [INFO 09-28 16:12:30] ax.service.managed_loop: Running optimization trial 13... /opt/hostedtoolcache/Python/3.8.14/x64/lib/python3.8/site-packages/botorch/optim/optimize.py:306: RuntimeWarning: Optimization failed in `gen_candidates_scipy` with the following warning(s): [OptimizationWarning('Optimization failed within `scipy.optimize.minimize` with status 9.')] Trying again with a new set of initial conditions. /opt/hostedtoolcache/Python/3.8.14/x64/lib/python3.8/site-packages/botorch/optim/optimize.py:328: RuntimeWarning: Optimization failed on the second try, after generating a new set of initial conditions. [INFO 09-28 16:12:42] ax.service.managed_loop: Running optimization trial 14... /opt/hostedtoolcache/Python/3.8.14/x64/lib/python3.8/site-packages/botorch/optim/optimize.py:306: RuntimeWarning: Optimization failed in `gen_candidates_scipy` with the following warning(s): [OptimizationWarning('Optimization failed within `scipy.optimize.minimize` with status 9.')] Trying again with a new set of initial conditions. /opt/hostedtoolcache/Python/3.8.14/x64/lib/python3.8/site-packages/botorch/optim/optimize.py:328: RuntimeWarning: Optimization failed on the second try, after generating a new set of initial conditions. [INFO 09-28 16:12:55] ax.service.managed_loop: Running optimization trial 15... /opt/hostedtoolcache/Python/3.8.14/x64/lib/python3.8/site-packages/botorch/optim/optimize.py:306: RuntimeWarning: Optimization failed in `gen_candidates_scipy` with the following warning(s): [OptimizationWarning('Optimization failed within `scipy.optimize.minimize` with status 9.')] Trying again with a new set of initial conditions. /opt/hostedtoolcache/Python/3.8.14/x64/lib/python3.8/site-packages/botorch/optim/optimize.py:328: RuntimeWarning: Optimization failed on the second try, after generating a new set of initial conditions. [INFO 09-28 16:13:08] ax.service.managed_loop: Running optimization trial 16... /opt/hostedtoolcache/Python/3.8.14/x64/lib/python3.8/site-packages/botorch/optim/optimize.py:306: RuntimeWarning: Optimization failed in `gen_candidates_scipy` with the following warning(s): [OptimizationWarning('Optimization failed within `scipy.optimize.minimize` with status 9.')] Trying again with a new set of initial conditions. /opt/hostedtoolcache/Python/3.8.14/x64/lib/python3.8/site-packages/botorch/optim/optimize.py:328: RuntimeWarning: Optimization failed on the second try, after generating a new set of initial conditions. [INFO 09-28 16:13:20] ax.service.managed_loop: Running optimization trial 17... /opt/hostedtoolcache/Python/3.8.14/x64/lib/python3.8/site-packages/botorch/optim/optimize.py:306: RuntimeWarning: Optimization failed in `gen_candidates_scipy` with the following warning(s): [OptimizationWarning('Optimization failed within `scipy.optimize.minimize` with status 9.')] Trying again with a new set of initial conditions. /opt/hostedtoolcache/Python/3.8.14/x64/lib/python3.8/site-packages/botorch/optim/optimize.py:328: RuntimeWarning: Optimization failed on the second try, after generating a new set of initial conditions. [INFO 09-28 16:13:32] ax.service.managed_loop: Running optimization trial 18... /opt/hostedtoolcache/Python/3.8.14/x64/lib/python3.8/site-packages/botorch/optim/optimize.py:306: RuntimeWarning: Optimization failed in `gen_candidates_scipy` with the following warning(s): [OptimizationWarning('Optimization failed within `scipy.optimize.minimize` with status 9.')] Trying again with a new set of initial conditions. /opt/hostedtoolcache/Python/3.8.14/x64/lib/python3.8/site-packages/botorch/optim/optimize.py:328: RuntimeWarning: Optimization failed on the second try, after generating a new set of initial conditions. [INFO 09-28 16:13:44] ax.service.managed_loop: Running optimization trial 19... /opt/hostedtoolcache/Python/3.8.14/x64/lib/python3.8/site-packages/botorch/optim/optimize.py:306: RuntimeWarning: Optimization failed in `gen_candidates_scipy` with the following warning(s): [OptimizationWarning('Optimization failed within `scipy.optimize.minimize` with status 9.')] Trying again with a new set of initial conditions. /opt/hostedtoolcache/Python/3.8.14/x64/lib/python3.8/site-packages/botorch/optim/optimize.py:328: RuntimeWarning: Optimization failed on the second try, after generating a new set of initial conditions. [INFO 09-28 16:13:56] ax.service.managed_loop: Running optimization trial 20... /opt/hostedtoolcache/Python/3.8.14/x64/lib/python3.8/site-packages/botorch/optim/optimize.py:306: RuntimeWarning: Optimization failed in `gen_candidates_scipy` with the following warning(s): [OptimizationWarning('Optimization failed within `scipy.optimize.minimize` with status 9.')] Trying again with a new set of initial conditions. /opt/hostedtoolcache/Python/3.8.14/x64/lib/python3.8/site-packages/botorch/optim/optimize.py:328: RuntimeWarning: Optimization failed on the second try, after generating a new set of initial conditions. [INFO 09-28 16:14:08] ax.service.managed_loop: Running optimization trial 21... /opt/hostedtoolcache/Python/3.8.14/x64/lib/python3.8/site-packages/botorch/optim/optimize.py:306: RuntimeWarning: Optimization failed in `gen_candidates_scipy` with the following warning(s): [OptimizationWarning('Optimization failed within `scipy.optimize.minimize` with status 9.')] Trying again with a new set of initial conditions. /opt/hostedtoolcache/Python/3.8.14/x64/lib/python3.8/site-packages/botorch/optim/optimize.py:328: RuntimeWarning: Optimization failed on the second try, after generating a new set of initial conditions. [INFO 09-28 16:14:19] ax.service.managed_loop: Running optimization trial 22... [INFO 09-28 16:14:24] ax.service.managed_loop: Running optimization trial 23... [INFO 09-28 16:14:29] ax.service.managed_loop: Running optimization trial 24... [INFO 09-28 16:14:34] ax.service.managed_loop: Running optimization trial 25... [INFO 09-28 16:14:39] ax.service.managed_loop: Running optimization trial 26... [INFO 09-28 16:14:44] ax.service.managed_loop: Running optimization trial 27... [INFO 09-28 16:14:48] ax.service.managed_loop: Running optimization trial 28... [INFO 09-28 16:14:54] ax.service.managed_loop: Running optimization trial 29... [INFO 09-28 16:14:59] ax.service.managed_loop: Running optimization trial 30...
And we can introspect optimization results:
best_parameters
{'x1': 0.19372487101765848, 'x2': 0.17317519181499047, 'x3': 0.5143756879433657, 'x4': 0.2769825879747112, 'x5': 0.31721781462784565, 'x6': 0.6469683382255459}
means, covariances = values
means
{'hartmann6': -3.298383227394422, 'l2norm': 0.9633375165774383}
For comparison, minimum of Hartmann6 is:
hartmann6.fmin
-3.32237
Here we arbitrarily select "x1" and "x2" as the two parameters to plot for both metrics, "hartmann6" and "l2norm".
render(plot_contour(model=model, param_x='x1', param_y='x2', metric_name='hartmann6'))
render(plot_contour(model=model, param_x='x1', param_y='x2', metric_name='l2norm'))
We also plot optimization trace, which shows best hartmann6 objective value seen by each iteration of the optimization:
# `plot_single_method` expects a 2-d array of means, because it expects to average means from multiple
# optimization runs, so we wrap out best objectives array in another array.
best_objectives = np.array([[trial.objective_mean for trial in experiment.trials.values()]])
best_objective_plot = optimization_trace_single_method(
y=np.minimum.accumulate(best_objectives, axis=1),
optimum=hartmann6.fmin,
title="Model performance vs. # of iterations",
ylabel="Hartmann6",
)
render(best_objective_plot)
Total runtime of script: 2 minutes, 39.99 seconds.