DifferentialEvolution.__init__()   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 27
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 25
dl 0
loc 27
rs 9.28
c 0
b 0
f 0
cc 1
nop 12

How to fix   Many Parameters   

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
from hyperactive.opt._adapters._gfo import _BaseGFOadapter
2
3
4
class DifferentialEvolution(_BaseGFOadapter):
5
    """Differential evolution 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
    population  : int
25
        The number of individuals in the population.
26
    mutation_rate : float
27
        The mutation rate.
28
    crossover_rate : float
29
        The crossover rate.
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 DifferentialEvolution 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 differentialEvolution optimizer:
56
    >>> from hyperactive.opt import DifferentialEvolution
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 = DifferentialEvolution(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": "Differential Evolution",
77
        "info:local_vs_global": "global",
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=10,
90
        mutation_rate=0.9,
91
        crossover_rate=0.9,
92
        n_iter=100,
93
        verbose=False,
94
        experiment=None,
95
    ):
96
        self.random_state = random_state
97
        self.rand_rest_p = rand_rest_p
98
        self.population = population
99
        self.mutation_rate = mutation_rate
100
        self.crossover_rate = crossover_rate
101
        self.search_space = search_space
102
        self.initialize = initialize
103
        self.constraints = constraints
104
        self.n_iter = n_iter
105
        self.experiment = experiment
106
        self.verbose = verbose
107
108
        super().__init__()
109
110
    def _get_gfo_class(self):
111
        """Get the GFO class to use.
112
113
        Returns
114
        -------
115
        class
116
            The GFO class to use. One of the concrete GFO classes
117
        """
118
        from gradient_free_optimizers import DifferentialEvolutionOptimizer
119
120
        return DifferentialEvolutionOptimizer
121
122
    @classmethod
123
    def get_test_params(cls, parameter_set="default"):
124
        """Get the test parameters for the optimizer.
125
126
        Returns
127
        -------
128
        dict with str keys
129
            The test parameters dictionary.
130
        """
131
        import numpy as np
132
133
        params = super().get_test_params()
134
        experiment = params[0]["experiment"]
135
        more_params = {
136
            "experiment": experiment,
137
            "population": 8,
138
            "mutation_rate": 0.8,
139
            "crossover_rate": 0.7,
140
            "search_space": {
141
                "C": [0.01, 0.1, 1, 10],
142
                "gamma": [0.0001, 0.01, 0.1, 1, 10],
143
            },
144
            "n_iter": 100,
145
        }
146
        params.append(more_params)
147
        return params
148