Passed
Push — master ( 588022...8a2a5a )
by Simon
01:36
created

DownhillSimplexOptimizer._get_gfo_class()   A

Complexity

Conditions 1

Size

Total Lines 11
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 11
rs 10
c 0
b 0
f 0
cc 1
nop 1
1
from hyperactive.opt._adapters._gfo import _BaseGFOadapter
2
3
4
class DownhillSimplexOptimizer(_BaseGFOadapter):
5
    """Downhill simplex optimizer.
6
7
    Parameters
8
    ----------
9
    search_space : dict[str, list]
10
        The search space to explore. A dictionary with parameter
11
        names as keys and a numpy array as values.
12
    initialize : dict[str, int]
13
        The method to generate initial positions. A dictionary with
14
        the following key literals and the corresponding value type:
15
        {"grid": int, "vertices": int, "random": int, "warm_start": list[dict]}
16
    constraints : list[callable]
17
        A list of constraints, where each constraint is a callable.
18
        The callable returns `True` or `False` dependend on the input parameters.
19
    random_state : None, int
20
        If None, create a new random state. If int, create a new random state
21
        seeded with the value.
22
    rand_rest_p : float
23
        The probability of a random iteration during the the search process.
24
    alpha : float
25
        The reflection parameter of the simplex algorithm.
26
    gamma : float
27
        The expansion parameter of the simplex algorithm.
28
    beta : float
29
        The contraction parameter of the simplex algorithm.
30
    sigma : float
31
        The shrinking parameter of the simplex algorithm.
32
    n_iter : int, default=100
33
        The number of iterations to run the optimizer.
34
    verbose : bool, default=False
35
        If True, print the progress of the optimization process.
36
    experiment : BaseExperiment, optional
37
        The experiment to optimize parameters for.
38
        Optional, can be passed later via ``set_params``.
39
40
    Examples
41
    --------
42
    Basic usage of DownhillSimplexOptimizer with a scikit-learn experiment:
43
44
    1. defining the experiment to optimize:
45
    >>> from hyperactive.experiment.integrations import SklearnCvExperiment
46
    >>> from sklearn.datasets import load_iris
47
    >>> from sklearn.svm import SVC
48
    >>>
49
    >>> X, y = load_iris(return_X_y=True)
50
    >>>
51
    >>> sklearn_exp = SklearnCvExperiment(
52
    ...     estimator=SVC(),
53
    ...     X=X,
54
    ...     y=y,
55
    ... )
56
57
    2. setting up the downhillSimplexOptimizer optimizer:
58
    >>> from hyperactive.opt import DownhillSimplexOptimizer
59
    >>> import numpy as np
60
    >>>
61
    >>> config = {
62
    ...     "search_space": {
63
    ...         "C": [0.01, 0.1, 1, 10],
64
    ...         "gamma": [0.0001, 0.01, 0.1, 1, 10],
65
    ...     },
66
    ...     "n_iter": 100,
67
    ... }
68
    >>> optimizer = DownhillSimplexOptimizer(experiment=sklearn_exp, **config)
69
70
    3. running the optimization:
71
    >>> best_params = optimizer.run()
72
73
    Best parameters can also be accessed via:
74
    >>> best_params = optimizer.best_params_
75
    """
76
77
    _tags = {
78
        "info:name": "Downhill Simplex",
79
        "info:local_vs_global": "local",
80
        "info:explore_vs_exploit": "exploit",
81
        "info:compute": "low",
82
    }
83
84
    def __init__(
85
        self,
86
        search_space=None,
87
        initialize=None,
88
        constraints=None,
89
        random_state=None,
90
        rand_rest_p=0.1,
91
        alpha=1,
92
        gamma=2,
93
        beta=0.5,
94
        sigma=0.5,
95
        n_iter=100,
96
        verbose=False,
97
        experiment=None,
98
    ):
99
        self.random_state = random_state
100
        self.rand_rest_p = rand_rest_p
101
        self.alpha = alpha
102
        self.gamma = gamma
103
        self.beta = beta
104
        self.sigma = sigma
105
        self.search_space = search_space
106
        self.initialize = initialize
107
        self.constraints = constraints
108
        self.n_iter = n_iter
109
        self.experiment = experiment
110
        self.verbose = verbose
111
112
        super().__init__()
113
114
    def _get_gfo_class(self):
115
        """Get the GFO class to use.
116
117
        Returns
118
        -------
119
        class
120
            The GFO class to use. One of the concrete GFO classes
121
        """
122
        from gradient_free_optimizers import DownhillSimplexOptimizer
123
124
        return DownhillSimplexOptimizer
125
126
    @classmethod
127
    def get_test_params(cls, parameter_set="default"):
128
        """Get the test parameters for the optimizer.
129
130
        Returns
131
        -------
132
        dict with str keys
133
            The test parameters dictionary.
134
        """
135
        import numpy as np
136
137
        params = super().get_test_params()
138
        experiment = params[0]["experiment"]
139
        more_params = {
140
            "experiment": experiment,
141
            "alpha": 0.33,
142
            "beta": 0.33,
143
            "gamma": 0.33,
144
            "sigma": 0.33,
145
            "search_space": {
146
                "C": [0.01, 0.1, 1, 10],
147
                "gamma": [0.0001, 0.01, 0.1, 1, 10],
148
            },
149
            "n_iter": 100,
150
        }
151
        params.append(more_params)
152
        return params
153