In this example, we create a ConfigurationSpace then add two UniformFloatHyperparameter into it.
The parameter x1 ranges from -5 to 10. The parameter x2 ranges from 0 to 15.
Other types of hyperparameter are also supported in ConfigSpace.
Here are examples of how to define Integer and Categorical hyperparameters:
Second, define the objective function to be optimized.
Note that OpenBox aims to minimize the objective function.
Here we use the Branin function.
importnumpyasnpfromopenbox.utils.config_spaceimportConfiguration# Define Objective Functiondefbranin(config:Configuration):# convert Configuration to dictconfig_dict=config.get_dictionary()x1=config_dict['x1']x2=config_dict['x2']# calculatea=1.b=5.1/(4.*np.pi**2)c=5./np.pir=6.s=10.t=1./(8.*np.pi)y=a*(x2-b*x1**2+c*x1-r)**2+s*(1-t)*np.cos(x1)+s# return result dictionaryret=dict(objs=(y,))returnret
The input of the objective function is a Configuration object sampled from ConfigurationSpace
as we defined above.
Call config.get_dictionary() to covert Configuration to Python dict form.
After evaluation, the objective function should return a dict (Recommended).
The result dict should contain:
‘objs’: A list/tuple of objective values (to be minimized).
In the example above, we have one objective so return a tuple contains a single value.
‘constraints’: A list/tuple of constraint values.
If the problem is not constrained, return None or do not include this key in the dict.
Constraints less than zero (“<=0”) implies feasibility.
In addition to the recommended usage, for single objective problem with no constraint,
just return a single value is supported, too.
After we define the configuration space and the objective function, we could run optimization process,
search over the configuration space and try to find minimum value of the objective.
fromopenbox.optimizer.generic_smboimportSMBO# Run Optimizationbo=SMBO(branin,config_space,num_objs=1,num_constraints=0,max_runs=50,surrogate_type='gp',time_limit_per_trial=180,task_id='quick_start')history=bo.run()
Here we simply create a SMBO object, passing the objective function branin and the
configuration space config_space to it.
num_objs=1 and num_constraints=0 indicates our branin function returns a single objective value with no
constraint.
max_runs=50 means the optimization will take 50 rounds (50 times of objective function evaluation).
surrogate_type=‘gp’. For mathematical problem, we suggest using Gaussian Process (‘gp’) as Bayesian surrogate
model. For practical problems such as hyperparameter optimization (HPO), we suggest using Random Forest (‘prf’).
time_limit_per_trial sets the time budget (seconds) of each objective function evaluation. Once the
evaluation time exceeds this limit, objective function will return as a failed trial.
task_id is set to identify the optimization process.
Then, call bo.run() to start the optimization process and wait for the result to return.