StopRun.__init__()   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 5
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 5
rs 10
c 0
b 0
f 0
cc 1
nop 5
1
# Author: Simon Blanke
2
# Email: [email protected]
3
# License: MIT License
4
5
6
import logging
7
import time
8
import numpy as np
9
10
11
def time_exceeded(start_time, max_time):
12
    run_time = time.time() - start_time
13
    return max_time and run_time > max_time
14
15
16
def score_exceeded(score_best, max_score):
17
    return max_score and score_best >= max_score
18
19
20
def no_change(score_new_list, early_stopping):
21
    if "n_iter_no_change" not in early_stopping:
22
        logging.warning(
23
            "Warning n_iter_no_change-parameter must be set in order for early stopping to work"
24
        )
25
        return False
26
27
    n_iter_no_change = early_stopping["n_iter_no_change"]
28
    if len(score_new_list) <= n_iter_no_change:
29
        return False
30
31
    scores_np = np.array(score_new_list)
32
33
    max_score = max(score_new_list)
34
    max_index = np.argmax(scores_np)
35
    length_pos = len(score_new_list)
36
37
    diff = length_pos - max_index
38
39
    if diff > n_iter_no_change:
40
        return True
41
42
    first_n = length_pos - n_iter_no_change
43
    scores_first_n = score_new_list[:first_n]
44
45
    max_first_n = max(scores_first_n)
46
47
    if "tol_abs" in early_stopping and early_stopping["tol_abs"] is not None:
48
        tol_abs = early_stopping["tol_abs"]
49
50
        if abs(max_first_n - max_score) < tol_abs:
51
            return True
52
53
    if "tol_rel" in early_stopping and early_stopping["tol_rel"] is not None:
54
        tol_rel = early_stopping["tol_rel"]
55
56
        percent_imp = ((max_score - max_first_n) / abs(max_first_n)) * 100
57
        if percent_imp < tol_rel:
58
            return True
59
60
61
class StopRun:
62
    def __init__(self, start_time, max_time, max_score, early_stopping):
63
        self.start_time = start_time
64
        self.max_time = max_time
65
        self.max_score = max_score
66
        self.early_stopping = early_stopping
67
68
    def update(self, score_best, score_new_list):
69
        self.score_best = score_best
70
        self.score_new_list = score_new_list
71
72
    def check(self):
73
        if self.max_time and time_exceeded(self.start_time, self.max_time):
74
            return True
75
        elif self.max_score and score_exceeded(self.score_best, self.max_score):
76
            return True
77
        elif self.early_stopping and no_change(
78
            self.score_new_list, self.early_stopping
79
        ):
80
            return True
81