Passed
Push — master ( 87bd68...af4dfb )
by Simon
01:51
created

hyperactive.optimizers.local.stochastic_hill_climbing   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 8
eloc 28
dl 0
loc 45
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A StochasticHillClimbingOptimizer.__init__() 0 2 1
A StochasticHillClimbingOptimizer._consider() 0 6 2
A StochasticHillClimbingOptimizer._score_norm() 0 5 1
A StochasticHillClimbingOptimizer._stochastic_hill_climb_iter() 0 8 2
A StochasticHillClimbingOptimizer._accept() 0 2 1
A StochasticHillClimbingOptimizer._iterate() 0 4 1
1
# Author: Simon Blanke
2
# Email: [email protected]
3
# License: MIT License
4
5
import random
6
import numpy as np
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_.p_down)
17
18
        if p_accept > rand:
19
            _p_.score_current = _p_.score_new
20
            _p_.pos_current = _p_.pos_new
21
22
    def _score_norm(self, _p_):
23
        return (
24
            100
25
            * (_p_.score_current - _p_.score_new)
26
            / (_p_.score_current + _p_.score_new)
27
        )
28
29
    def _accept(self, _p_):
30
        return np.exp(-self._score_norm(_p_))
31
32
    def _stochastic_hill_climb_iter(self, _cand_, _p_, X, y):
33
        _cand_, _p_ = self._hill_climb_iter(_cand_, _p_, X, y)
34
35
        if _p_.score_new <= _cand_.score_best:
36
            p_accept = self._accept(_p_)
37
            self._consider(_p_, p_accept)
38
39
        return _cand_
40
41
    def _iterate(self, i, _cand_, _p_, X, y):
42
        _cand_ = self._stochastic_hill_climb_iter(_cand_, _p_, X, y)
43
44
        return _cand_
45