1: '''
2: Code to perform temperature scaling. Adapted from https://github.com/gpleiss/temperature_scaling
3: '''
4: import logging
5: import torch
6: import numpy as np
7: from torch import nn, optim
8: from torch.nn import functional as F
9: 
10: from calibrate.evaluation.metrics import ECELoss
11: 
12: logger = logging.getLogger(__name__)
13: 
14: 
15: class ModelWithTemperature(nn.Module):
16:     """
17:     A thin decorator, which wraps a model with temperature scaling
18:     model (nn.Module):
19:         A classification neural network
20:         NB: Output of the neural network should be the classification logits,
21:             NOT the softmax (or log softmax)!
22:     """
23:     def __init__(self, model, device="cuda:0", log=True):
24:         super(ModelWithTemperature, self).__init__()
25:         self.model = model
26:         self.temperature = 1.0
27:         self.log = log
28:         self.device = device
29: 
30:     def forward(self, input):
31:         logits = self.model(input)
32:         return self.temperature_scale(logits)
33: 
34:     def temperature_scale(self, logits):
35:         """
36:         Perform temperature scaling on logits
37:         """
38:         # Expand temperature to match the size of logits
39:         return logits / self.temperature
40: 
41:     def set_temperature_ng(self, embedding_model, x_val, y_val,
42:                            cross_validate="ece",
43:                            batch_size=128):
44:         self.model.eval()
45:         embedding_model.eval()
46:         nll_criterion = nn.CrossEntropyLoss().to(self.device)
47:         ece_criterion = ECELoss().to(self.device)
48: 
49:         # First: collect all the logits and labels for the validation set
50:         logits_list = []
51:         labels_list = []
52:         batch_size = 128
53:         with torch.no_grad():
54:             for i in range(1 + x_val.shape[0]//batch_size):
55:                 data = torch.from_numpy(
56:                     x_val[i*batch_size:min((i+1)*batch_size, x_val.shape[0])]
57:                 ).type(torch.LongTensor).to(self.device)
58:                 labels = torch.from_numpy(
59:                     np.argmax(y_val[i*batch_size:min((i+1)*batch_size, x_val.shape[0])], 1)
60:                 ).to(self.device)
61:                 emb = embedding_model(data)
62:                 logits = self.model(emb)
63:                 logits_list.append(logits)
64:                 labels_list.append(labels)
65: 
66:             logits = torch.cat(logits_list).cuda()
67:             labels = torch.cat(labels_list).cuda()
68: 
69:         # Calculate NLL and ECE before temperature scaling
70:         before_temperature_nll = nll_criterion(logits, labels).item()
71:         before_temperature_ece = ece_criterion(logits, labels).item()
72:         if self.log:
73:             logger.info(
74:                 'Before temperature - NLL: {:.4f}, ECE: {:.4f}'.format(
75:                     before_temperature_nll, before_temperature_ece
76:                 )
77:             )
78: 
79:         nll_val = 10 ** 7
80:         ece_val = 10 ** 7
81:         T_opt_nll = 1.0
82:         T_opt_ece = 1.0
83:         T = 0.1
84:         for i in range(100):
85:             self.temperature = T
86:             after_temperature_nll = nll_criterion(self.temperature_scale(logits), labels).item()
87:             after_temperature_ece = ece_criterion(self.temperature_scale(logits), labels).item()
88:             if nll_val > after_temperature_nll:
89:                 T_opt_nll = T
90:                 nll_val = after_temperature_nll
91: 
92:             if ece_val > after_temperature_ece:
93:                 T_opt_ece = T
94:                 ece_val = after_temperature_ece
95:             T += 0.1
96: 
97:         if cross_validate == 'ece':
98:             self.temperature = T_opt_ece
99:         else:
100:             self.temperature = T_opt_nll
101: 
102:         # Calculate NLL and ECE after temperature scaling
103:         after_temperature_nll = nll_criterion(self.temperature_scale(logits), labels).item()
104:         after_temperature_ece = ece_criterion(self.temperature_scale(logits), labels).item()
105:         if self.log:
106:             logger.info(
107:                 'Optimal temperature: {:.3f}'.format(self.temperature)
108:             )
109:             logger.info(
110:                 'After temperature - NLL: {:.4f}, ECE: {:.4f}'.format(
111:                     after_temperature_nll, after_temperature_ece
112:                 )
113:             )
114: 
115:     def set_temperature(self,
116:                         valid_loader,
117:                         cross_validate='ece'):
118:         """
119:         Tune the tempearature of the model (using the validation set) with cross-validation on ECE or NLL
120:         """
121:         # self.cuda()
122:         self.model.eval()
123:         nll_criterion = nn.CrossEntropyLoss().to(self.device)
124:         ece_criterion = ECELoss().to(self.device)
125: 
126:         # First: collect all the logits and labels for the validation set
127:         logits_list = []
128:         labels_list = []
129:         with torch.no_grad():
130:             for data in valid_loader:
131:                 input = data['inputs'].to(self.device)  # b,c,h,w
132:                 label = data['labels']  # b,1
133:                 input = input.to(self.device)
134:                 logits = self.model(input)
135:                 logits_list.append(logits)
136:                 labels_list.append(label)
137:             logits = torch.cat(logits_list).to(self.device)
138:             labels = torch.cat(labels_list).to(self.device)
139: 
140:         # Calculate NLL and ECE before temperature scaling
141:         before_temperature_nll = nll_criterion(logits, labels).item()
142:         before_temperature_ece = ece_criterion(logits, labels).item()
143:         if self.log:
144:             logger.info(
145:                 'Before temperature - NLL: {:.4f}, ECE: {:.4f}'.format(
146:                     before_temperature_nll, before_temperature_ece
147:                 )
148:             )
149: 
150:         nll_val = 10 ** 7
151:         ece_val = 10 ** 7
152:         T_opt_nll = 1.0
153:         T_opt_ece = 1.0
154:         T = 0.1
155:         for i in range(100):
156:             self.temperature = T
157:             after_temperature_nll = nll_criterion(self.temperature_scale(logits), labels).item()
158:             after_temperature_ece = ece_criterion(self.temperature_scale(logits), labels).item()
159:             if nll_val > after_temperature_nll:
160:                 T_opt_nll = T
161:                 nll_val = after_temperature_nll
162: 
163:             if ece_val > after_temperature_ece:
164:                 T_opt_ece = T
165:                 ece_val = after_temperature_ece
166:             T += 0.1
167: 
168:         if cross_validate == 'ece':
169:             self.temperature = T_opt_ece
170:         else:
171:             self.temperature = T_opt_nll
172: 
173:         # Calculate NLL and ECE after temperature scaling
174:         after_temperature_nll = nll_criterion(self.temperature_scale(logits), labels).item()
175:         after_temperature_ece = ece_criterion(self.temperature_scale(logits), labels).item()
176:         if self.log:
177:             logger.info(
178:                 'Optimal temperature: {:.3f}'.format(self.temperature)
179:             )
180:             logger.info(
181:                 'After temperature - NLL: {:.4f}, ECE: {:.4f}'.format(
182:                     after_temperature_nll, after_temperature_ece
183:                 )
184:             )
185: 
186: 
187:     def set_temperature_seg(self,
188:                         valid_loader,
189:                         cross_validate='nll'):
190:         """
191:         Tune the tempearature of the model (using the validation set) with cross-validation on ECE or NLL
192:         """
193:         # self.cuda()
194:         self.model.eval()
195:         nll_criterion = nn.CrossEntropyLoss().to(self.device)
196:         ece_criterion = ECELoss().to(self.device)
197: 
198:         # First: collect all the logits and labels for the validation set
199:         logits_list = []
200:         labels_list = []
201:         with torch.no_grad():
202:             for input, label in valid_loader:
203:                 input = input.to(self.device)
204:                 logits = self.model(input)
205:                 assert logits.shape[0] == label.shape[0]
206:                 n, c, x, y = logits.shape
207:                 logits = torch.einsum("ncxy->nxyc", logits)
208:                 logits = logits.reshape(n * x * y, -1)
209:                 label = label.reshape(n * x * y)
210:                 if 0 <= 255:
211:                     index = torch.nonzero(label != 255).squeeze()
212:                     logits = logits[index, :]
213:                     label = label[index]
214:                 # dismiss background
215:                 index = torch.nonzero(label != 0).squeeze()
216:                 logits = logits[index, :].to(self.device)
217:                 label = label[index].to(self.device)
218:                 logits_list.append(logits)
219:                 labels_list.append(label)
220: 
221:             logits = torch.cat(logits_list).to(self.device)
222:             labels = torch.cat(labels_list).to(self.device)
223: 
224:         # Calculate NLL and ECE before temperature scaling
225:         before_temperature_nll = nll_criterion(logits, labels).item()
226:         before_temperature_ece = ece_criterion(logits, labels).item()
227:         if self.log:
228:             logger.info(
229:                 'Before temperature - NLL: {:.4f}, ECE: {:.4f}'.format(
230:                     before_temperature_nll, before_temperature_ece
231:                 )
232:             )
233: 
234:         nll_val = 10 ** 7
235:         ece_val = 10 ** 7
236:         T_opt_nll = 1.0
237:         T_opt_ece = 1.0
238:         T = 0.1
239:         for i in range(100):
240:             self.temperature = T
241:             after_temperature_nll = nll_criterion(self.temperature_scale(logits), labels).item()
242:             after_temperature_ece = ece_criterion(self.temperature_scale(logits), labels).item()
243:             if nll_val > after_temperature_nll:
244:                 T_opt_nll = T
245:                 nll_val = after_temperature_nll
246: 
247:             if ece_val > after_temperature_ece:
248:                 T_opt_ece = T
249:                 ece_val = after_temperature_ece
250:             T += 0.1
251: 
252:         if cross_validate == 'ece':
253:             self.temperature = T_opt_ece
254:         else:
255:             self.temperature = T_opt_nll
256: 
257:         # Calculate NLL and ECE after temperature scaling
258:         after_temperature_nll = nll_criterion(self.temperature_scale(logits), labels).item()
259:         after_temperature_ece = ece_criterion(self.temperature_scale(logits), labels).item()
260:         if self.log:
261:             logger.info(
262:                 'Optimal temperature: {:.3f}'.format(self.temperature)
263:             )
264:             logger.info(
265:                 'After temperature - NLL: {:.4f}, ECE: {:.4f}'.format(
266:                     after_temperature_nll, after_temperature_ece
267:                 )
268:             )
269: 
270:     def get_temperature(self):
271:         return self.temperature