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
|
|
|
|