Passed
Push — master ( 39ef7f...f70242 )
by Simon
01:57
created

hyperactive.optimizers.local.stochastic_hill_climbing.StochasticHillClimbingOptimizer._init_opt_positioner()   A

Complexity

Conditions 1

Size

Total Lines 2
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 2
rs 10
c 0
b 0
f 0
cc 1
nop 4
1
# Author: Simon Blanke
2
# Email: [email protected]
3
# License: MIT License
4
5
6
import random
7
8
from . import HillClimbingOptimizer
9
10
11
class StochasticHillClimbingOptimizer(HillClimbingOptimizer):
12
    def __init__(self, *args, **kwargs):
13
        super().__init__(*args, **kwargs)
14
15
    def _consider(self, _p_, p_accept):
16
        rand = random.uniform(0, self._arg_.r)
17
18
        if p_accept > rand:
19
            _p_.score_current = _p_.score_new
20
            _p_.pos_current = _p_.pos_new
21
22
    def _accept(self, _p_):
23
        score_diff_norm = (_p_.score_new - _p_.score_current) / (
24
            _p_.score_new + _p_.score_current
25
        )
26
        if score_diff_norm == 0:
27
            return 100
28
        else:
29
            return 0.001 / abs(score_diff_norm)
30
31
    def _iterate(self, i, _cand_, _p_, X, y):
32
        _p_.pos_new = _p_.move_climb(_cand_, _p_.pos_current)
33
        _p_.score_new = _cand_.eval_pos(_p_.pos_new, X, y)
34
35
        if _p_.score_new > _cand_.score_best:
36
            _cand_, _p_ = self._update_pos(_cand_, _p_)
37
        else:
38
            p_accept = self._accept(_p_)
39
            self._consider(_p_, p_accept)
40
41
        return _cand_
42