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

SpiralOptimization.get_test_params()   A

Complexity

Conditions 1

Size

Total Lines 25
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

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