hyperactive.opt.gfo._differential_evolution   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 146
Duplicated Lines 97.26 %

Importance

Changes 0
Metric Value
wmc 3
eloc 51
dl 142
loc 146
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A DifferentialEvolution.get_test_params() 24 24 1
A DifferentialEvolution._get_gfo_class() 11 11 1
A DifferentialEvolution.__init__() 27 27 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
from hyperactive.opt._adapters._gfo import _BaseGFOadapter
2
3
4 View Code Duplication
class DifferentialEvolution(_BaseGFOadapter):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
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.solve()
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
        params = super().get_test_params()
132
        experiment = params[0]["experiment"]
133
        more_params = {
134
            "experiment": experiment,
135
            "population": 8,
136
            "mutation_rate": 0.8,
137
            "crossover_rate": 0.7,
138
            "search_space": {
139
                "C": [0.01, 0.1, 1, 10],
140
                "gamma": [0.0001, 0.01, 0.1, 1, 10],
141
            },
142
            "n_iter": 100,
143
        }
144
        params.append(more_params)
145
        return params
146