gradient_free_optimizers.optimizers.local_opt.hill_climbing_optimizer   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 75
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 6
eloc 56
dl 0
loc 75
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A HillClimbingOptimizer.__init__() 0 24 1
A HillClimbingOptimizer.iterate() 0 7 1
A HillClimbingOptimizer.evaluate() 0 17 3

1 Function

Rating   Name   Duplication   Size   Complexity  
A max_list_idx() 0 4 1
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