-
Notifications
You must be signed in to change notification settings - Fork 6
/
get_metrics.py
316 lines (249 loc) · 12.5 KB
/
get_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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
# import libraries
import torch
import matplotlib
import numpy as np
import seaborn as sns
from itertools import cycle
import matplotlib.pyplot as plt
from sklearn.metrics import roc_curve
from sklearn.metrics import roc_auc_score
from sklearn.metrics import confusion_matrix
from sklearn.metrics import cohen_kappa_score
from sklearn.metrics import classification_report
class get_metric():
def get_accuracy_graph(epochs, train_acc, val_acc): # draw validation and train accuracy graphs
plt.plot(epochs, train_acc, color='#006BA4')
plt.plot(epochs, val_acc, color='#FF800E')
plt.grid(b=True, which='major', color='lightgray')
plt.grid(b=True, which='minor', color='lightgray')
plt.xticks(np.arange(0, 45, 5))
plt.yticks(np.arange(0.5, 1, 0.05))
plt.rcParams['figure.figsize'] = (8, 6)
plt.rcParams['figure.dpi'] = 600
plt.xlabel("Number of Epochs")
plt.ylabel("Accuracy")
plt.title("Training Accuracy vs Validation Accuracy")
plt.legend(['Training Acc.', 'Validation Acc.'], loc='lower right')
plt.show()
def get_loss_graph(epochs, train_losses, val_losses): # draw validation and train loss graphs
matplotlib.rcdefaults()
plt.plot(epochs, train_losses, color='#006BA4')
plt.plot(epochs, val_losses, color='#FF800E')
plt.grid(b=True, which='major', color='lightgray')
plt.grid(b=True, which='minor', color='lightgray')
plt.xticks(np.arange(0, 45, 5))
plt.yticks(np.arange(0, 1.2, 0.2))
plt.rcParams['figure.dpi'] = 600
plt.xlabel("Number of Epochs")
plt.ylabel("Loss")
plt.title("Training Loss vs Validation Loss")
plt.legend(['Training Loss', 'Validation Loss'], loc='lower right')
plt.show()
def test_label_predictions(model, device, test_loader): # calculate outputs on test dataset for get metrics
model.eval()
actuals = []
predictions = []
with torch.no_grad():
for data, target in test_loader:
data, target = data.to(device), target.to(device)
output = model(data)
prediction = output.argmax(dim=1, keepdim=True)
actuals.extend(target.view_as(prediction))
predictions.extend(prediction)
return [i.item() for i in actuals], [i.item() for i in predictions]
def test_label_predictions_el2(model_0,model_1,model_2,model_3, device, test_loader):
actuals = []
predictions = []
with torch.no_grad():
for data, target in test_loader:
data, target = data.to(device), target.to(device)
outputs_0 = model_0(data)
_, predicted_0 =torch.max(outputs_0.data, 1)
outputs_1 = model_1(data)
_, predicted_1 =torch.max(outputs_1.data, 1)
outputs_2 = model_2(data)
_, predicted_2 =torch.max(outputs_2.data, 1)
outputs_3 = model_3(data)
_, predicted_3 =torch.max(outputs_3.data, 1)
final_pred=predicted_1
size=final_pred.size()
for i in range(0,(size[0])):
a=0
if predicted_2[i].item()==0 and predicted_3[i].item()==0:
if predicted_1[i].item()==1:
final_pred[i]=1
if predicted_1[i].item()==0:
final_pred[i]=0
a+=1
if (predicted_0[i].item()==1 and predicted_1[i].item()==1) :
a+=1
if predicted_3[i].item()==0:
final_pred[i]=0
if predicted_3[i].item()!=0:
final_pred[i]=1
if a==0:
final_pred[i]=predicted_2[i]
actuals.extend(target.view_as(final_pred))
predictions.extend(final_pred)
return [i.item() for i in actuals], [i.item() for i in predictions]
def test_model(model ,device, test_loader):
correct = 0
total = 0
with torch.no_grad():
for data in test_loader:
images, labels = data[0].to(device), data[1].to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Correct Prediction: {:d} Total Images: {:d}'.format(correct, total))
print('Test Accuracy = {:f}'.format(correct / total))
def test_model_el2(model_0,model_1,model_2,model_3,device, test_loader):
correct = 0
total = 0
with torch.no_grad():
for data in test_loader:
images, labels = data[0].to(device), data[1].to(device)
outputs_0 = model_0(images)
_, predicted_0 =torch.max(outputs_0.data, 1)
outputs_1 = model_1(images)
_, predicted_1 =torch.max(outputs_1.data, 1)
outputs_2 = model_2(images)
_, predicted_2 =torch.max(outputs_2.data, 1)
outputs_3 = model_3(images)
_, predicted_3 =torch.max(outputs_3.data, 1)
final_pred=predicted_1
size=final_pred.size()
for i in range(0,(size[0])):
a=0
if predicted_2[i].item()==0 and predicted_3[i].item()==0:
if predicted_1[i].item()==1:
final_pred[i]=1
if predicted_1[i].item()==0:
final_pred[i]=0
a+=1
if (predicted_0[i].item()==1 and predicted_1[i].item()==1):
a+=1
if predicted_3[i].item()==0:
final_pred[i]=0
if predicted_3[i].item()!=0:
final_pred[i]=1
if a==0:
final_pred[i]=predicted_2[i]
total += labels.size(0)
correct += (final_pred == labels).sum().item()
print('Correct Prediction: {:d} Total Images: {:d}'.format(correct, total))
print('Test Accuracy = {:f}'.format(correct / total))
def get_classification_report(truth, predict): # create classification report for each class with scikit-learn library
print('Classification Report :\n', classification_report(truth, predict))
def get_confusion_matrix(actuals, predictions): # create confusion matrix for each class with scikit-learn library
matplotlib.rcdefaults()
print('Confusion matrix:\n',confusion_matrix(actuals, predictions))
cf_matrix=confusion_matrix(actuals, predictions)
sns.heatmap(cf_matrix, annot=True,fmt='g', cmap='Blues')
def get_cohen_kappa(actuals, predictions): # get cohen kapa score for determine model performance
cps = cohen_kappa_score(actuals, predictions)
print('Kappa Score of this model:\n', cps)
def test_class_probabilities(model, device, test_loader, which_class):
truths = []
probabilities = []
with torch.no_grad():
for data, target in test_loader:
data, target = data.to(device), target.to(device)
output = model(data).cuda().cpu()
prediction = output.argmax(dim=1, keepdim=True)
truths.extend(target.view_as(prediction) == which_class)
probabilities.extend(np.exp(output[:, which_class]))
return [i.item() for i in truths], [i.item() for i in probabilities]
def test_class_probabilities_el2(model_0,model_1,model_2,model_3, device, test_loader, which_class):
truths = []
probabilities = []
with torch.no_grad():
for data, target in test_loader:
data, target = data.to(device), target.to(device)
outputs_0 = model_0(data)
_, predicted_0 =torch.max(outputs_0.data, 1)
outputs_1 = model_1(data)
_, predicted_1 =torch.max(outputs_1.data, 1)
outputs_2 = model_2(data)
_, predicted_2 =torch.max(outputs_2.data, 1)
outputs_3 = model_3(data)
_, predicted_3 =torch.max(outputs_3.data, 1)
final_pred=predicted_1
out=outputs_1
size=final_pred.size()
for i in range(0,(size[0])):
a=0
if predicted_2[i].item()==0 and predicted_3[i].item()==0:
if predicted_1[i].item()==1:
#final_pred[i]=1
out[i]=outputs_1[i]
if predicted_1[i].item()==0:
final_pred[i]=0
out[i]=outputs_1[i]
a+=1
if (predicted_0[i].item()==1 and predicted_1[i].item()==1):
a+=1
if predicted_3[i].item()==0:
#final_pred[i]=0
out[i]=outputs_3[i]
if predicted_3[i].item()!=0:
#final_pred[i]=1
out[i]=outputs_3[i]
if a==0:
#final_pred[i]=predicted_2[i]
out[i]=outputs_2[i]
prediction = out.argmax(dim=1, keepdim=True)
truths.extend(target.view_as(prediction) == which_class)
probabilities.extend(np.exp(out.cuda().cpu()[:, which_class]))
return [i.item() for i in truths], [i.item() for i in probabilities]
def get_roc_curves_el2(model_0,model_1,model_2,model_3, device, data): # draw Roc curves and calculate auc score for each class
fpr = dict()
tpr = dict()
roc_auc = dict()
actuals, class_probabilities = get_metric.test_class_probabilities_el2(model_0,model_1,model_2,model_3, device, data, 0)
fpr[0], tpr[0], _ = roc_curve(actuals, class_probabilities)
roc_auc[0] = roc_auc_score(actuals, class_probabilities)
actuals, class_probabilities = get_metric.test_class_probabilities_el2(model_0,model_1,model_2,model_3, device, data, 1)
fpr[1], tpr[1], _ = roc_curve(actuals, class_probabilities)
roc_auc[1] = roc_auc_score(actuals, class_probabilities)
print("Auc Score For Each Class: ", roc_auc)
matplotlib.rcdefaults()
plt.figure()
colors = cycle(['aqua', 'darkorange', 'cornflowerblue'])
for i, color in zip(range(2), colors):
plt.plot(fpr[i], tpr[i], color=color, lw=1,
label='ROC curve of class {0} (area = {1:0.4f})'
''.format(i, roc_auc[i]))
plt.plot([0, 1], [0, 1], 'k--', lw=1)
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.legend(loc="lower right")
plt.show()
def get_roc_curves(model, device, data): # draw Roc curves and calculate auc score for each class
fpr = dict()
tpr = dict()
roc_auc = dict()
actuals, class_probabilities = get_metric.test_class_probabilities(model, device, data, 0)
fpr[0], tpr[0], _ = roc_curve(actuals, class_probabilities)
roc_auc[0] = roc_auc_score(actuals, class_probabilities)
actuals, class_probabilities = get_metric.test_class_probabilities(model, device, data, 1)
fpr[1], tpr[1], _ = roc_curve(actuals, class_probabilities)
roc_auc[1] = roc_auc_score(actuals, class_probabilities)
print("Auc Score For Each Class: ", roc_auc)
matplotlib.rcdefaults()
plt.figure()
colors = cycle(['aqua', 'darkorange', 'cornflowerblue'])
for i, color in zip(range(2), colors):
plt.plot(fpr[i], tpr[i], color=color, lw=1,
label='ROC curve of class {0} (area = {1:0.4f})'
''.format(i, roc_auc[i]))
plt.plot([0, 1], [0, 1], 'k--', lw=1)
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.legend(loc="lower right")
plt.show()