-
Notifications
You must be signed in to change notification settings - Fork 5
/
metrics.py
executable file
·167 lines (132 loc) · 4.75 KB
/
metrics.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
from abc import ABCMeta, abstractmethod
import time
import torch
import numpy as np
from utils import to_onehot
class Metric:
__metaclass__ = ABCMeta
def __init__(self, name=None, is_scalar=True, output_transform=lambda x: x, **kwargs):
self.reset()
self.is_scalar = is_scalar
self.output_transform = output_transform
if name:
self.name = name
else:
self.name = self.__class__.__name__
def reset(self):
"""Reset computed value. Need to reset other values used to compute in sub-Metrics.
"""
self.computed = None
@abstractmethod
def update(self, output, **kwargs):
pass
@abstractmethod
def compute(self):
"""Update self.computed with value
"""
pass
class EpochRecord(Metric):
"""An EpochRecord is used to compute a set of Metrics for one epoch
"""
def __init__(self, metrics, **kwargs):
self.metrics = metrics
super().__init__(**kwargs)
def reset(self):
super().reset()
for metric in self.metrics:
metric.reset()
def update(self, *output, **kwargs):
for metric in self.metrics:
metric.update(output, **kwargs)
def compute(self):
for metric in self.metrics:
metric.compute()
self.computed = {metric.name: metric.computed for metric in self.metrics}
class ClassAccuracy(Metric):
def __init__(self, num_classes, **kwargs):
super().__init__(is_scalar=False, **kwargs)
self.num_classes = num_classes
def reset(self):
super().reset()
self.correct = 0
self.n = 0
def update(self, output, **kwargs):
y_pred, y = self.output_transform(output)
dim = 1 if y_pred.dim() > 1 else 0
_, predicted = torch.max(y_pred, dim=dim)
predicted = to_onehot(predicted, self.num_classes)
y = to_onehot(y, self.num_classes)
correct = torch.eq(predicted, y)
correct[(1 - y.byte()).bool()] = 0
correct = torch.sum(correct, dim=0)
self.correct += correct
self.n += torch.sum(y, dim=0)
def compute(self):
self.computed = torch.div(self.correct.float(), self.n.float()).cpu().numpy()
# self.computed[torch.isnan(self.computed)] = 0
class AverageAccuracy(Metric):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def reset(self):
super().reset()
self.correct = 0
self.n = 0
def update(self, output, **kwargs):
y_pred, y = self.output_transform(output)
dim = 1 if y_pred.dim() > 1 else 0
_, predicted = torch.max(y_pred, dim=dim)
correct = torch.eq(predicted, y)
correct = correct.view(-1)
self.correct += torch.sum(correct).item()
self.n += correct.shape[0]
def compute(self):
if self.n == 0:
self.computed = np.nan
else:
self.computed = self.correct / self.n
class Loss(Metric):
def __init__(self, loss_fn, batch_size=lambda x: x.shape[0], **kwargs):
super().__init__(**kwargs)
self.loss_fn = loss_fn
self.batch_size = batch_size
def reset(self):
super().reset()
self.sum = 0
self.n = 0
def update(self, output, loss=None, **kwargs):
y_pred, y = self.output_transform(output)
if type(loss) is dict and self.name in loss.keys():
loss = loss[self.name]
else:
loss = None
if loss is None:
loss = self.loss_fn(y_pred, y, **kwargs)
N = self.batch_size(y)
self.sum += loss.item() * N
self.n += N
def compute(self):
if self.n == 0:
self.computed = np.nan
else:
self.computed = self.sum / self.n
class RunTime(Metric):
def __init__self(self, **kwargs):
super().__init__(**kwargs)
def reset(self):
super().reset()
self.start = None
self.end = None
def update(self, *args, **kwargs):
if self.start is None:
self.start = time.time()
self.end = time.time()
def compute(self):
self.computed = self.end - self.start
class FakeAccuracy(AverageAccuracy):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def update(self, *args, y_pred_fake=None, fake_class=None, **kwargs):
if y_pred_fake is None or fake_class is None:
return torch.Tensor([0])
y_fake = y_pred_fake.new_ones(y_pred_fake.shape[0]) * fake_class
super().update((y_pred_fake, y_fake), **kwargs)