deephyper.skopt.utils.use_named_args

Contents

deephyper.skopt.utils.use_named_args#

deephyper.skopt.utils.use_named_args(dimensions)[source]#

Wrapper / decorator for an objective function that uses named arguments to make it compatible with optimizers that use a single list of parameters.

Your objective function can be defined as being callable using named arguments: func(foo=123, bar=3.0, baz=’hello’) for a search-space with dimensions named [‘foo’, ‘bar’, ‘baz’]. But the optimizer will only pass a single list x of unnamed arguments when calling the objective function: func(x=[123, 3.0, ‘hello’]). This wrapper converts your objective function with named arguments into one that accepts a list as argument, while doing the conversion automatically.

The advantage of this is that you don’t have to unpack the list of arguments x yourself, which makes the code easier to read and also reduces the risk of bugs if you change the number of dimensions or their order in the search-space.

Examples

>>> # Define the search-space dimensions. They must all have names!
>>> from deephyper.skopt.space import Real
>>> from deephyper.skopt import forest_minimize
>>> from deephyper.skopt.utils import use_named_args
>>> dim1 = Real(name='foo', low=0.0, high=1.0)
>>> dim2 = Real(name='bar', low=0.0, high=1.0)
>>> dim3 = Real(name='baz', low=0.0, high=1.0)
>>>
>>> # Gather the search-space dimensions in a list.
>>> dimensions = [dim1, dim2, dim3]
>>>
>>> # Define the objective function with named arguments
>>> # and use this function-decorator to specify the
>>> # search-space dimensions.
>>> @use_named_args(dimensions=dimensions)
... def my_objective_function(foo, bar, baz):
...     return foo ** 2 + bar ** 4 + baz ** 8
>>>
>>> # Not the function is callable from the outside as
>>> # `my_objective_function(x)` where `x` is a list of unnamed arguments,
>>> # which then wraps your objective function that is callable as
>>> # `my_objective_function(foo, bar, baz)`.
>>> # The conversion from a list `x` to named parameters `foo`,
>>> # `bar`, `baz`
>>> # is done automatically.
>>>
>>> # Run the optimizer on the wrapped objective function which is called
>>> # as `my_objective_function(x)` as expected by `forest_minimize()`.
>>> result = forest_minimize(func=my_objective_function,
...                          dimensions=dimensions,
...                          n_calls=20, base_estimator="ET",
...                          random_state=4)
>>>
>>> # Print the best-found results in same format as the expected result.
>>> print("Best fitness: " + str(result.fun))
Best fitness: 0.1948080835239698
>>> print("Best parameters: {}".format(result.x))
Best parameters: [0.44134853091052617, 0.06570954323368307, 0.17586123323419825]
Parameters:

dimensions (list(Dimension)) – List of Dimension-objects for the search-space dimensions.

Returns:

wrapped_func – Wrapped objective function.

Return type:

callable