HillClimbingOptimizer.__init__()   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 24
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 21
dl 0
loc 24
rs 9.376
c 0
b 0
f 0
cc 1
nop 10

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
# Author: Simon Blanke
2
# Email: [email protected]
3
# License: MIT License
4
5
import numpy as np
6
7
from ..base_optimizer import BaseOptimizer
8
9
10
def max_list_idx(list_):
11
    max_item = max(list_)
12
    max_item_idx = [i for i, j in enumerate(list_) if j == max_item]
13
    return max_item_idx[-1:][0]
14
15
16
class HillClimbingOptimizer(BaseOptimizer):
17
    name = "Hill Climbing"
18
    _name_ = "hill_climbing"
19
    __name__ = "HillClimbingOptimizer"
20
21
    optimizer_type = "local"
22
    computationally_expensive = False
23
24
    def __init__(
25
        self,
26
        search_space,
27
        initialize={"grid": 4, "random": 2, "vertices": 4},
28
        constraints=[],
29
        random_state=None,
30
        rand_rest_p=0,
31
        nth_process=None,
32
        epsilon=0.03,
33
        distribution="normal",
34
        n_neighbours=3,
35
    ):
36
37
        super().__init__(
38
            search_space=search_space,
39
            initialize=initialize,
40
            constraints=constraints,
41
            random_state=random_state,
42
            rand_rest_p=rand_rest_p,
43
            nth_process=nth_process,
44
        )
45
        self.epsilon = epsilon
46
        self.distribution = distribution
47
        self.n_neighbours = n_neighbours
48
49
    @BaseOptimizer.track_new_pos
50
    @BaseOptimizer.random_iteration
51
    def iterate(self):
52
        return self.move_climb(
53
            self.pos_current,
54
            epsilon=self.epsilon,
55
            distribution=self.distribution,
56
        )
57
58
    @BaseOptimizer.track_new_score
59
    def evaluate(self, score_new):
60
        BaseOptimizer.evaluate(self, score_new)
61
        if len(self.scores_valid) == 0:
62
            return
63
64
        modZero = self.nth_trial % self.n_neighbours == 0
65
        if modZero:
66
            score_new_list_temp = self.scores_valid[-self.n_neighbours :]
67
            pos_new_list_temp = self.positions_valid[-self.n_neighbours :]
68
69
            idx = max_list_idx(score_new_list_temp)
70
            score = score_new_list_temp[idx]
71
            pos = pos_new_list_temp[idx]
72
73
            self._eval2current(pos, score)
74
            self._eval2best(pos, score)
75