Passed
Push — master ( 613b45...e6e7ce )
by Simon
01:49 queued 15s
created

_BaseGFOadapter.__init__()   A

Complexity

Conditions 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 2
nop 1
1
"""Adapter for gfo package."""
2
# copyright: hyperactive developers, MIT License (see LICENSE file)
3
4
from hyperactive.base import BaseOptimizer
5
from skbase.utils.stdout_mute import StdoutMute
6
7
__all__ = ["_BaseGFOadapter"]
8
9
10
class _BaseGFOadapter(BaseOptimizer):
11
    """Adapter base class for gradient-free-optimizers.
12
13
    * default tag setting
14
    * default _run method
15
    * default get_search_config
16
    * default get_test_params
17
    * Handles defaults for "initialize" parameter
18
    * extension interface: _get_gfo_class, docstring, tags
19
    """
20
21
    _tags = {
22
        "authors": "SimonBlanke",
23
        "python_dependencies": ["gradient-free-optimizers>=1.5.0"],
24
    }
25
26
    def __init__(self):
27
28
        super().__init__()
29
30
        if self.initialize is None:
31
            self._initialize = {"grid": 4, "random": 2, "vertices": 4}
32
        else:
33
            self._initialize = self.initialize
34
35
    def _get_gfo_class(self):
36
        """Get the GFO class to use.
37
38
        Returns
39
        -------
40
        class
41
            The GFO class to use. One of the concrete GFO classes
42
        """
43
        raise NotImplementedError(
44
            "This method should be implemented in a subclass."
45
        )
46
47
    def get_search_config(self):
48
        """Get the search configuration.
49
50
        Returns
51
        -------
52
        dict with str keys
53
            The search configuration dictionary.
54
        """
55
        search_config = super().get_search_config()
56
        search_config["initialize"] = self._initialize
57
        del search_config["verbose"]
58
        return search_config
59
60
    def _run(self, experiment, **search_config):
61
        """Run the optimization search process.
62
        Parameters
63
        ----------
64
        experiment : BaseExperiment
65
            The experiment to optimize parameters for.
66
        search_config : dict with str keys
67
            identical to return of ``get_search_config``.
68
        Returns
69
        -------
70
        dict with str keys
71
            The best parameters found during the search.
72
            Must have keys a subset or identical to experiment.paramnames().
73
        """
74
        n_iter = search_config.pop("n_iter", 100)
75
        max_time = search_config.pop("max_time", None)
76
77
        gfo_cls = self._get_gfo_class()
78
        hcopt = gfo_cls(**search_config)
79
80
        with StdoutMute(active=not self.verbose):
81
            hcopt.search(
82
                objective_function=experiment.score,
83
                n_iter=n_iter,
84
                max_time=max_time,
85
            )
86
        best_params = hcopt.best_para
87
        return best_params
88
89
    @classmethod
90
    def get_test_params(cls, parameter_set="default"):
91
        """Return testing parameter settings for the skbase object.
92
93
        ``get_test_params`` is a unified interface point to store
94
        parameter settings for testing purposes. This function is also
95
        used in ``create_test_instance`` and ``create_test_instances_and_names``
96
        to construct test instances.
97
98
        ``get_test_params`` should return a single ``dict``, or a ``list`` of ``dict``.
99
100
        Each ``dict`` is a parameter configuration for testing,
101
        and can be used to construct an "interesting" test instance.
102
        A call to ``cls(**params)`` should
103
        be valid for all dictionaries ``params`` in the return of ``get_test_params``.
104
105
        The ``get_test_params`` need not return fixed lists of dictionaries,
106
        it can also return dynamic or stochastic parameter settings.
107
108
        Parameters
109
        ----------
110
        parameter_set : str, default="default"
111
            Name of the set of test parameters to return, for use in tests. If no
112
            special parameters are defined for a value, will return `"default"` set.
113
114
        Returns
115
        -------
116
        params : dict or list of dict, default = {}
117
            Parameters to create testing instances of the class
118
            Each dict are parameters to construct an "interesting" test instance, i.e.,
119
            `MyClass(**params)` or `MyClass(**params[i])` creates a valid test instance.
120
            `create_test_instance` uses the first (or only) dictionary in `params`
121
        """
122
        import numpy as np
123
        from hyperactive.experiment.integrations import SklearnCvExperiment
124
125
        sklearn_exp = SklearnCvExperiment.create_test_instance()
126
        params_sklearn = {
127
            "experiment": sklearn_exp,
128
            "search_space": {
129
                "C": np.array([0.01, 0.1, 1, 10]),
130
                "gamma": np.array([0.0001, 0.01, 0.1, 1, 10]),
131
            },
132
            "n_iter": 100,
133
        }
134
135
        from hyperactive.experiment.toy import Ackley
136
137
        ackley_exp = Ackley.create_test_instance()
138
        params_ackley = {
139
            "experiment": ackley_exp,
140
            "search_space": {
141
                "x0": np.linspace(-5, 5, 10),
142
                "x1": np.linspace(-5, 5, 10),
143
            },
144
            "n_iter": 100,
145
        }
146
        
147
        return [params_sklearn, params_ackley]
148