-
Notifications
You must be signed in to change notification settings - Fork 0
/
early_stopping.py
93 lines (66 loc) · 2.28 KB
/
early_stopping.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import numpy as np
class EarlyStoppingCriterion(object):
def __init__(self, patience):
self.patience = patience
def should_stop(self, epoch, val_loss, val_accuracy):
raise NotImplementedError
def after_stopping_ops(self):
raise NotImplementedError
def reset(self):
raise NotImplementedError
class NoStoppingCriterion(EarlyStoppingCriterion): # not used
def should_stop(self, epoch, val_loss, val_accuracy):
return False
def after_stopping_ops(self):
pass
def reset(self):
pass
class GCNCriterion(EarlyStoppingCriterion): # not used
def __init__(self, patience):
super().__init__(patience)
self.val_losses = []
def should_stop(self, epoch, val_loss, val_accuracy):
self.val_losses.append(val_loss)
return epoch >= self.patience and self.val_losses[-1] > np.mean(
self.val_losses[-(self.patience + 1):-1])
def after_stopping_ops(self):
pass
def reset(self):
self.val_losses = []
class LossDecreaseCriterion(EarlyStoppingCriterion):
def __init__(self, patience):
super().__init__(patience)
self.min_loss = 100
self.counter = 0
def should_stop(self, epoch, val_loss, val_accuracy):
if val_loss < self.min_loss:
self.counter = 0
self.min_loss = val_loss
else:
self.counter += 1
return self.counter >= self.patience
def after_stopping_ops(self):
pass
def reset(self):
self.min_loss = 100
self.counter = 0
class AccuracyAndLossVariationsCriterion(EarlyStoppingCriterion):
def __init__(self, patience):
super().__init__(patience)
self.min_loss = 100
self.max_accuracy = 0
self.counter = 0
def should_stop(self, epoch, val_loss, val_accuracy):
if val_loss < self.min_loss and val_accuracy > self.max_accuracy:
self.counter = 0
self.max_accuracy = val_accuracy
self.min_loss = val_loss
else:
self.counter += 1
return self.counter >= self.patience
def after_stopping_ops(self):
pass
def reset(self):
self.min_loss = 100
self.max_accuracy = 0
self.counter = 0