1: '''
2: Metrics to measure calibration of a trained deep neural network.
3: 
4: References:
5: [1] C. Guo, G. Pleiss, Y. Sun, and K. Q. Weinberger. On calibration of modern neural networks.
6:     arXiv preprint arXiv:1706.04599, 2017.
7: '''
8: 
9: import math
10: import torch
11: import numpy as np
12: from torch import nn
13: from torch.nn import functional as F
14: 
15: 
16: from sklearn.metrics import accuracy_score
17: from sklearn.metrics import confusion_matrix
18: 
19: 
20: # Some keys used for the following dictionaries
21: COUNT = 'count'
22: CONF = 'conf'
23: ACC = 'acc'
24: BIN_ACC = 'bin_acc'
25: BIN_CONF = 'bin_conf'
26: 
27: 
28: def _bin_initializer(bin_dict, num_bins=10):
29:     for i in range(num_bins):
30:         bin_dict[i][COUNT] = 0
31:         bin_dict[i][CONF] = 0
32:         bin_dict[i][ACC] = 0
33:         bin_dict[i][BIN_ACC] = 0
34:         bin_dict[i][BIN_CONF] = 0
35: 
36: 
37: def _populate_bins(confs, preds, labels, num_bins=10):
38:     bin_dict = {}
39:     for i in range(num_bins):
40:         bin_dict[i] = {}
41:     _bin_initializer(bin_dict, num_bins)
42:     num_test_samples = len(confs)
43: 
44:     for i in range(0, num_test_samples):
45:         confidence = confs[i]
46:         prediction = preds[i]
47:         label = labels[i]
48:         binn = int(math.ceil(((num_bins * confidence) - 1)))
49:         bin_dict[binn][COUNT] = bin_dict[binn][COUNT] + 1
50:         bin_dict[binn][CONF] = bin_dict[binn][CONF] + confidence
51:         bin_dict[binn][ACC] = bin_dict[binn][ACC] + \
52:             (1 if (label == prediction) else 0)
53: 
54:     for binn in range(0, num_bins):
55:         if (bin_dict[binn][COUNT] == 0):
56:             bin_dict[binn][BIN_ACC] = 0
57:             bin_dict[binn][BIN_CONF] = 0
58:         else:
59:             bin_dict[binn][BIN_ACC] = float(
60:                 bin_dict[binn][ACC]) / bin_dict[binn][COUNT]
61:             bin_dict[binn][BIN_CONF] = bin_dict[binn][CONF] / \
62:                 float(bin_dict[binn][COUNT])
63:     return bin_dict
64: 
65: 
66: def expected_calibration_error(confs, preds, labels, num_bins=10):
67:     bin_dict = _populate_bins(confs, preds, labels, num_bins)
68:     num_samples = len(labels)
69:     ece = 0
70:     for i in range(num_bins):
71:         bin_accuracy = bin_dict[i][BIN_ACC]
72:         bin_confidence = bin_dict[i][BIN_CONF]
73:         bin_count = bin_dict[i][COUNT]
74:         ece += (float(bin_count) / num_samples) * \
75:             abs(bin_accuracy - bin_confidence)
76:     return ece
77: 
78: 
79: def maximum_calibration_error(confs, preds, labels, num_bins=10):
80:     bin_dict = _populate_bins(confs, preds, labels, num_bins)
81:     ce = []
82:     for i in range(num_bins):
83:         bin_accuracy = bin_dict[i][BIN_ACC]
84:         bin_confidence = bin_dict[i][BIN_CONF]
85:         ce.append(abs(bin_accuracy - bin_confidence))
86:     return max(ce)
87: 
88: 
89: def average_calibration_error(confs, preds, labels, num_bins=10):
90:     bin_dict = _populate_bins(confs, preds, labels, num_bins)
91:     non_empty_bins = 0
92:     ace = 0
93:     for i in range(num_bins):
94:         bin_accuracy = bin_dict[i][BIN_ACC]
95:         bin_confidence = bin_dict[i][BIN_CONF]
96:         bin_count = bin_dict[i][COUNT]
97:         if bin_count > 0:
98:             non_empty_bins += 1
99:         ace += abs(bin_accuracy - bin_confidence)
100:     return ace / float(non_empty_bins)
101: 
102: 
103: def l2_error(confs, preds, labels, num_bins=15):
104:     bin_dict = _populate_bins(confs, preds, labels, num_bins)
105:     num_samples = len(labels)
106:     l2_sum = 0
107:     for i in range(num_bins):
108:         bin_accuracy = bin_dict[i][BIN_ACC]
109:         bin_confidence = bin_dict[i][BIN_CONF]
110:         bin_count = bin_dict[i][COUNT]
111:         l2_sum += (float(bin_count) / num_samples) * \
112:                (bin_accuracy - bin_confidence)**2
113:         l2_error = math.sqrt(l2_sum)
114:     return l2_error
115: 
116: 
117: def test_classification_net_logits(logits, labels):
118:     '''
119:     This function reports classification accuracy and confusion matrix given logits and labels
120:     from a model.
121:     '''
122:     labels_list = []
123:     predictions_list = []
124:     confidence_vals_list = []
125: 
126:     softmax = F.softmax(logits, dim=1)
127:     confidence_vals, predictions = torch.max(softmax, dim=1)
128:     labels_list.extend(labels.cpu().numpy().tolist())
129:     predictions_list.extend(predictions.cpu().numpy().tolist())
130:     confidence_vals_list.extend(confidence_vals.cpu().numpy().tolist())
131:     accuracy = accuracy_score(labels_list, predictions_list)
132:     return confusion_matrix(labels_list, predictions_list), accuracy, labels_list,\
133:         predictions_list, confidence_vals_list
134: 
135: 
136: def test_classification_net(model, data_loader, device):
137:     '''
138:     This function reports classification accuracy and confusion matrix over a dataset.
139:     '''
140:     model.eval()
141:     labels_list = []
142:     predictions_list = []
143:     confidence_vals_list = []
144:     with torch.no_grad():
145:         for i, (data, label) in enumerate(data_loader):
146:             data = data.to(device)
147:             label = label.to(device)
148: 
149:             logits = model(data)
150:             softmax = F.softmax(logits, dim=1)
151:             confidence_vals, predictions = torch.max(softmax, dim=1)
152: 
153:             labels_list.extend(label.cpu().numpy().tolist())
154:             predictions_list.extend(predictions.cpu().numpy().tolist())
155:             confidence_vals_list.extend(confidence_vals.cpu().numpy().tolist())
156:     accuracy = accuracy_score(labels_list, predictions_list)
157: 
158:     return confusion_matrix(labels_list, predictions_list), accuracy, labels_list,\
159:         predictions_list, confidence_vals_list
160: 
161: 
162: @torch.no_grad()
163: def model_prediction(model, data_loader, device):
164:     model.eval()
165:     all_predicts, all_labels = None, None
166:     for i, (data, label) in enumerate(data_loader):
167:         data, label = data.to(device), label.to(device)
168:         logits = model(data)
169:         predicts = F.softmax(logits, dim=1)
170:         if all_predicts is None:
171:             all_predicts = predicts.cpu().numpy()
172:             all_labels = label.cpu().numpy()
173:         else:
174:             all_predicts = np.concatenate((all_predicts, predicts.cpu().numpy()), axis=0)
175:             all_labels = np.concatenate((all_labels, label.cpu().numpy()))
176:     return all_predicts, all_labels
177: 
178: 
179: # Calibration error scores in the form of loss metrics
180: class ECELoss(nn.Module):
181:     '''
182:     Compute ECE (Expected Calibration Error)
183:     '''
184:     def __init__(self, n_bins=15):
185:         super(ECELoss, self).__init__()
186:         bin_boundaries = torch.linspace(0, 1, n_bins + 1)
187:         self.bin_lowers = bin_boundaries[:-1]
188:         self.bin_uppers = bin_boundaries[1:]
189: 
190:     def forward(self, logits, labels):
191:         softmaxes = F.softmax(logits, dim=1)
192:         confidences, predictions = torch.max(softmaxes, 1)
193:         accuracies = predictions.eq(labels)
194: 
195:         ece = torch.zeros(1, device=logits.device)
196:         for i, (bin_lower, bin_upper) in enumerate(zip(self.bin_lowers, self.bin_uppers)):
197:             # Calculated |confidence - accuracy| in each bin
198:             in_bin = confidences.gt(bin_lower.item()) * confidences.le(bin_upper.item())
199:             prop_in_bin = in_bin.float().mean()
200:             if prop_in_bin.item() > 0:
201:                 accuracy_in_bin = accuracies[in_bin].float().mean()
202:                 avg_confidence_in_bin = confidences[in_bin].mean()
203:                 ece += torch.abs(avg_confidence_in_bin - accuracy_in_bin) * prop_in_bin
204:         print(ece)
205:         return ece
206: 
207: 
208: class AdaptiveECELoss(nn.Module):
209:     '''
210:     Compute Adaptive ECE
211:     '''
212:     def __init__(self, n_bins=15):
213:         super(AdaptiveECELoss, self).__init__()
214:         self.nbins = n_bins
215: 
216:     def histedges_equalN(self, x):
217:         npt = len(x)
218:         return np.interp(np.linspace(0, npt, self.nbins + 1),
219:                      np.arange(npt),
220:                      np.sort(x))
221:     def forward(self, logits, labels):
222:         softmaxes = F.softmax(logits, dim=1)
223:         confidences, predictions = torch.max(softmaxes, 1)
224:         accuracies = predictions.eq(labels)
225:         n, bin_boundaries = np.histogram(confidences.cpu().detach(), self.histedges_equalN(confidences.cpu().detach()))
226:         #print(n,confidences,bin_boundaries)
227:         self.bin_lowers = bin_boundaries[:-1]
228:         self.bin_uppers = bin_boundaries[1:]
229:         ece = torch.zeros(1, device=logits.device)
230:         for bin_lower, bin_upper in zip(self.bin_lowers, self.bin_uppers):
231:             # Calculated |confidence - accuracy| in each bin
232:             in_bin = confidences.gt(bin_lower.item()) * confidences.le(bin_upper.item())
233:             prop_in_bin = in_bin.float().mean()
234:             if prop_in_bin.item() > 0:
235:                 accuracy_in_bin = accuracies[in_bin].float().mean()
236:                 avg_confidence_in_bin = confidences[in_bin].mean()
237:                 ece += torch.abs(avg_confidence_in_bin - accuracy_in_bin) * prop_in_bin
238:         return ece
239: 
240: 
241: class ClasswiseECELoss(nn.Module):
242:     '''
243:     Compute Classwise ECE
244:     '''
245:     def __init__(self, n_bins=15):
246:         super(ClasswiseECELoss, self).__init__()
247:         bin_boundaries = torch.linspace(0, 1, n_bins + 1)
248:         self.bin_lowers = bin_boundaries[:-1]
249:         self.bin_uppers = bin_boundaries[1:]
250: 
251:     def forward(self, logits, labels):
252:         num_classes = int((torch.max(labels) + 1).item())
253:         softmaxes = F.softmax(logits, dim=1)
254:         per_class_sce = None
255: 
256:         for i in range(num_classes):
257:             class_confidences = softmaxes[:, i]
258:             class_sce = torch.zeros(1, device=logits.device)
259:             labels_in_class = labels.eq(i) # one-hot vector of all positions where the label belongs to the class i
260: 
261:             for bin_lower, bin_upper in zip(self.bin_lowers, self.bin_uppers):
262:                 in_bin = class_confidences.gt(bin_lower.item()) * class_confidences.le(bin_upper.item())
263:                 prop_in_bin = in_bin.float().mean()
264:                 if prop_in_bin.item() > 0:
265:                     accuracy_in_bin = labels_in_class[in_bin].float().mean()
266:                     avg_confidence_in_bin = class_confidences[in_bin].mean()
267:                     class_sce += torch.abs(avg_confidence_in_bin - accuracy_in_bin) * prop_in_bin
268: 
269:             if (i == 0):
270:                 per_class_sce = class_sce
271:             else:
272:                 per_class_sce = torch.cat((per_class_sce, class_sce), dim=0)
273: 
274:         sce = torch.mean(per_class_sce)
275:         return sce
276: 
277: 
278: # Calibration error scores in the form of loss metrics
279: class OELoss(nn.Module):
280:     '''
281:     Compute OE (Overconfidence Error)
282:     '''
283:     def __init__(self, n_bins=15):
284:         super(OELoss, self).__init__()
285:         bin_boundaries = torch.linspace(0, 1, n_bins + 1)
286:         self.bin_lowers = bin_boundaries[:-1]
287:         self.bin_uppers = bin_boundaries[1:]
288: 
289:     def forward(self, logits, labels):
290:         softmaxes = F.softmax(logits, dim=1)
291:         confidences, predictions = torch.max(softmaxes, 1)
292:         accuracies = predictions.eq(labels)
293: 
294:         oe = torch.zeros(1, device=logits.device)
295:         for bin_lower, bin_upper in zip(self.bin_lowers, self.bin_uppers):
296:             # Calculated |confidence - accuracy| in each bin
297:             in_bin = confidences.gt(bin_lower.item()) * confidences.le(bin_upper.item())
298:             prop_in_bin = in_bin.float().mean()
299:             if prop_in_bin.item() > 0:
300:                 accuracy_in_bin = accuracies[in_bin].float().mean()
301:                 avg_confidence_in_bin = confidences[in_bin].mean()
302:                 oe += avg_confidence_in_bin * F.relu(avg_confidence_in_bin - accuracy_in_bin) * prop_in_bin
303: 
304:         return oe
305: 
306: class UELoss(nn.Module):
307:     '''
308:     Compute UE (Underconfidence Error)
309:     '''
310:     def __init__(self, n_bins=15):
311:         super(UELoss, self).__init__()
312:         bin_boundaries = torch.linspace(0, 1, n_bins + 1)
313:         self.bin_lowers = bin_boundaries[:-1]
314:         self.bin_uppers = bin_boundaries[1:]
315: 
316:     def forward(self, logits, labels):
317:         softmaxes = F.softmax(logits, dim=1)
318:         confidences, predictions = torch.max(softmaxes, 1)
319:         accuracies = predictions.eq(labels)
320: 
321:         ue = torch.zeros(1, device=logits.device)
322:         for bin_lower, bin_upper in zip(self.bin_lowers, self.bin_uppers):
323:             # Calculated |confidence - accuracy| in each bin
324:             in_bin = confidences.gt(bin_lower.item()) * confidences.le(bin_upper.item())
325:             prop_in_bin = in_bin.float().mean()
326:             if prop_in_bin.item() > 0:
327:                 accuracy_in_bin = accuracies[in_bin].float().mean()
328:                 avg_confidence_in_bin = confidences[in_bin].mean()
329:                 ue += avg_confidence_in_bin * F.relu(accuracy_in_bin - avg_confidence_in_bin) * prop_in_bin
330: 
331:         return ue