-
Notifications
You must be signed in to change notification settings - Fork 0
/
metrics.py
302 lines (249 loc) · 10.9 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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
'''
Metrics to measure calibration of a trained deep neural network.
References:
[1] C. Guo, G. Pleiss, Y. Sun, and K. Q. Weinberger. On calibration of modern neural networks.
arXiv preprint arXiv:1706.04599, 2017.
'''
import math
import torch
import numpy as np
from torch import nn
from torch.nn import functional as F
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix
# Some keys used for the following dictionaries
COUNT = 'count'
CONF = 'conf'
ACC = 'acc'
BIN_ACC = 'bin_acc'
BIN_CONF = 'bin_conf'
def _bin_initializer(bin_dict, num_bins=10):
for i in range(num_bins):
bin_dict[i][COUNT] = 0
bin_dict[i][CONF] = 0
bin_dict[i][ACC] = 0
bin_dict[i][BIN_ACC] = 0
bin_dict[i][BIN_CONF] = 0
def _populate_bins(confs, preds, labels, num_bins=10):
bin_dict = {}
for i in range(num_bins):
bin_dict[i] = {}
_bin_initializer(bin_dict, num_bins)
num_test_samples = len(confs)
for i in range(0, num_test_samples):
confidence = confs[i]
prediction = preds[i]
label = labels[i]
binn = int(math.ceil(((num_bins * confidence) - 1)))
bin_dict[binn][COUNT] = bin_dict[binn][COUNT] + 1
bin_dict[binn][CONF] = bin_dict[binn][CONF] + confidence
bin_dict[binn][ACC] = bin_dict[binn][ACC] + \
(1 if (label == prediction) else 0)
for binn in range(0, num_bins):
if (bin_dict[binn][COUNT] == 0):
bin_dict[binn][BIN_ACC] = 0
bin_dict[binn][BIN_CONF] = 0
else:
bin_dict[binn][BIN_ACC] = float(
bin_dict[binn][ACC]) / bin_dict[binn][COUNT]
bin_dict[binn][BIN_CONF] = bin_dict[binn][CONF] / \
float(bin_dict[binn][COUNT])
return bin_dict
def expected_calibration_error(confs, preds, labels, num_bins=10):
bin_dict = _populate_bins(confs, preds, labels, num_bins)
num_samples = len(labels)
ece = 0
for i in range(num_bins):
bin_accuracy = bin_dict[i][BIN_ACC]
bin_confidence = bin_dict[i][BIN_CONF]
bin_count = bin_dict[i][COUNT]
ece += (float(bin_count) / num_samples) * \
abs(bin_accuracy - bin_confidence)
return ece
def maximum_calibration_error(confs, preds, labels, num_bins=10):
bin_dict = _populate_bins(confs, preds, labels, num_bins)
ce = []
for i in range(num_bins):
bin_accuracy = bin_dict[i][BIN_ACC]
bin_confidence = bin_dict[i][BIN_CONF]
ce.append(abs(bin_accuracy - bin_confidence))
return max(ce)
def average_calibration_error(confs, preds, labels, num_bins=10):
bin_dict = _populate_bins(confs, preds, labels, num_bins)
non_empty_bins = 0
ace = 0
for i in range(num_bins):
bin_accuracy = bin_dict[i][BIN_ACC]
bin_confidence = bin_dict[i][BIN_CONF]
bin_count = bin_dict[i][COUNT]
if bin_count > 0:
non_empty_bins += 1
ace += abs(bin_accuracy - bin_confidence)
return ace / float(non_empty_bins)
def l2_error(confs, preds, labels, num_bins=15):
bin_dict = _populate_bins(confs, preds, labels, num_bins)
num_samples = len(labels)
l2_sum = 0
for i in range(num_bins):
bin_accuracy = bin_dict[i][BIN_ACC]
bin_confidence = bin_dict[i][BIN_CONF]
bin_count = bin_dict[i][COUNT]
l2_sum += (float(bin_count) / num_samples) * \
(bin_accuracy - bin_confidence)**2
l2_error = math.sqrt(l2_sum)
return l2_error
def test_classification_net_logits(logits, labels):
'''
This function reports classification accuracy and confusion matrix given logits and labels
from a model.
'''
labels_list = []
predictions_list = []
confidence_vals_list = []
softmax = F.softmax(logits, dim=1)
confidence_vals, predictions = torch.max(softmax, dim=1)
labels_list.extend(labels.cpu().numpy().tolist())
predictions_list.extend(predictions.cpu().numpy().tolist())
confidence_vals_list.extend(confidence_vals.cpu().numpy().tolist())
accuracy = accuracy_score(labels_list, predictions_list)
return confusion_matrix(labels_list, predictions_list), accuracy, labels_list,\
predictions_list, confidence_vals_list
def test_classification_net(model, data_loader, device):
'''
This function reports classification accuracy and confusion matrix over a dataset.
'''
model.eval()
labels_list = []
predictions_list = []
confidence_vals_list = []
with torch.no_grad():
for i, (data, label) in enumerate(data_loader):
data = data.to(device)
label = label.to(device)
logits = model(data)
softmax = F.softmax(logits, dim=1)
confidence_vals, predictions = torch.max(softmax, dim=1)
labels_list.extend(label.cpu().numpy().tolist())
predictions_list.extend(predictions.cpu().numpy().tolist())
confidence_vals_list.extend(confidence_vals.cpu().numpy().tolist())
accuracy = accuracy_score(labels_list, predictions_list)
return confusion_matrix(labels_list, predictions_list), accuracy, labels_list,\
predictions_list, confidence_vals_list
# Calibration error scores in the form of loss metrics
class ECELoss(nn.Module):
'''
Compute ECE (Expected Calibration Error)
'''
def __init__(self, n_bins=15):
super(ECELoss, self).__init__()
bin_boundaries = torch.linspace(0, 1, n_bins + 1)
self.bin_lowers = bin_boundaries[:-1]
self.bin_uppers = bin_boundaries[1:]
def forward(self, logits, labels):
softmaxes = F.softmax(logits, dim=1)
confidences, predictions = torch.max(softmaxes, 1)
accuracies = predictions.eq(labels)
ece = torch.zeros(1, device=logits.device)
for bin_lower, bin_upper in zip(self.bin_lowers, self.bin_uppers):
# Calculated |confidence - accuracy| in each bin
in_bin = confidences.gt(bin_lower.item()) * confidences.le(bin_upper.item())
prop_in_bin = in_bin.float().mean()
if prop_in_bin.item() > 0:
accuracy_in_bin = accuracies[in_bin].float().mean()
avg_confidence_in_bin = confidences[in_bin].mean()
ece += torch.abs(avg_confidence_in_bin - accuracy_in_bin) * prop_in_bin
return ece
class AdaptiveECELoss(nn.Module):
'''
Compute Adaptive ECE
'''
def __init__(self, n_bins=15):
super(AdaptiveECELoss, self).__init__()
self.nbins = n_bins
def histedges_equalN(self, x):
npt = len(x)
return np.interp(np.linspace(0, npt, self.nbins + 1),
np.arange(npt),
np.sort(x))
def forward(self, logits, labels):
softmaxes = F.softmax(logits, dim=1)
confidences, predictions = torch.max(softmaxes, 1)
accuracies = predictions.eq(labels)
n, bin_boundaries = np.histogram(confidences.cpu().detach(), self.histedges_equalN(confidences.cpu().detach()))
#print(n,confidences,bin_boundaries)
self.bin_lowers = bin_boundaries[:-1]
self.bin_uppers = bin_boundaries[1:]
ece = torch.zeros(1, device=logits.device)
for bin_lower, bin_upper in zip(self.bin_lowers, self.bin_uppers):
# Calculated |confidence - accuracy| in each bin
in_bin = confidences.gt(bin_lower.item()) * confidences.le(bin_upper.item())
prop_in_bin = in_bin.float().mean()
if prop_in_bin.item() > 0:
accuracy_in_bin = accuracies[in_bin].float().mean()
avg_confidence_in_bin = confidences[in_bin].mean()
ece += torch.abs(avg_confidence_in_bin - accuracy_in_bin) * prop_in_bin
return ece
class ClasswiseECELoss(nn.Module):
'''
Compute Classwise ECE
'''
def __init__(self, n_bins=15):
super(ClasswiseECELoss, self).__init__()
bin_boundaries = torch.linspace(0, 1, n_bins + 1)
self.bin_lowers = bin_boundaries[:-1]
self.bin_uppers = bin_boundaries[1:]
def forward(self, logits, labels):
num_classes = int((torch.max(labels) + 1).item())
softmaxes = F.softmax(logits, dim=1)
per_class_sce = None
for i in range(num_classes):
class_confidences = softmaxes[:, i]
class_sce = torch.zeros(1, device=logits.device)
labels_in_class = labels.eq(i) # one-hot vector of all positions where the label belongs to the class i
for bin_lower, bin_upper in zip(self.bin_lowers, self.bin_uppers):
in_bin = class_confidences.gt(bin_lower.item()) * class_confidences.le(bin_upper.item())
prop_in_bin = in_bin.float().mean()
if prop_in_bin.item() > 0:
accuracy_in_bin = labels_in_class[in_bin].float().mean()
avg_confidence_in_bin = class_confidences[in_bin].mean()
class_sce += torch.abs(avg_confidence_in_bin - accuracy_in_bin) * prop_in_bin
if (i == 0):
per_class_sce = class_sce
else:
per_class_sce = torch.cat((per_class_sce, class_sce), dim=0)
sce = torch.mean(per_class_sce)
return sce
class ThreshClasswiseECELoss(nn.Module):
'''
Compute Classwise ECE
'''
def __init__(self, n_bins=15, thresh=1e-3):
super(ThreshClasswiseECELoss, self).__init__()
bin_boundaries = torch.linspace(0, 1, n_bins + 1)
self.bin_lowers = bin_boundaries[:-1]
self.bin_uppers = bin_boundaries[1:]
self.thresh = thresh
def forward(self, logits, labels):
num_classes = int((torch.max(labels) + 1).item())
softmaxes = F.softmax(logits, dim=1)
per_class_sce = None
for i in range(num_classes):
class_confidences = softmaxes[:, i]
class_sce = torch.zeros(1, device=logits.device)
labels_in_class = labels.eq(i) # one-hot vector of all positions where the label belongs to the class i
# print (class_confidences.shape, labels_in_class.shape)
labels_in_class = labels_in_class[class_confidences > self.thresh]
class_confidences = class_confidences[class_confidences > self.thresh]
for bin_lower, bin_upper in zip(self.bin_lowers, self.bin_uppers):
in_bin = class_confidences.gt(bin_lower.item()) * class_confidences.le(bin_upper.item())
prop_in_bin = in_bin.float().mean()
if prop_in_bin.item() > 0:
accuracy_in_bin = labels_in_class[in_bin].float().mean()
avg_confidence_in_bin = class_confidences[in_bin].mean()
class_sce += torch.abs(avg_confidence_in_bin - accuracy_in_bin) * prop_in_bin
if (i == 0):
per_class_sce = class_sce
else:
per_class_sce = torch.cat((per_class_sce, class_sce), dim=0)
sce = torch.mean(per_class_sce)
return sce