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
| def Metrics(output, labels): ''' output: <list> labels: <list> ''' test_correct = 0 test_total = 0 predicts = [] prob = [] tp, tn, fp, fn = 0, 0, 0, 0
for outputs in output: index, predicted = torch.max(outputs.data, 1) predicts.append([outputs.data, predicted, labels]) test_total += labels.size(0) test_correct += (predicted == labels.data).sum()
f1_predicts = predicted.cpu().numpy().tolist() f1_label = labels.data.cpu().numpy().tolist() for i in range(len(f1_label)): if f1_predicts[i] == 1 and f1_label[i] == 1: tp += 1 if f1_predicts[i] == 1 and f1_label[i] == 0: fp += 1 if f1_predicts[i] == 0 and f1_label[i] == 1: fn += 1 if f1_predicts[i] == 0 and f1_label[i] == 0: tn += 1
outputs = outputs.data.cpu().numpy() probability = np.exp(outputs)/np.mat(np.sum(np.exp(outputs), axis=1)).T prob = probability[:,1].T.tolist()[0] for p, label in zip(prob, labels.data.cpu().numpy().tolist()): prob.append([p, label])
F1_Score = 2*tp/(2*tp+fp+fn) test_acc = test_correct.item()/test_total
return prob, test_acc, F1_Score
def drawROC(prob): ''' prob: <list>: [probability of positive, true label] '''
neg = 0 for i in range(len(prob)): if prob[i][1] == 0: neg += 1 pos = len(prob) - neg
x = [] y = [] sample_sort = sorted(prob, key=lambda x:x[0], reverse=False) for i in range(len(sample_sort)): tp = 0 fp = 0 for j in range(i, len(sample_sort)): if sample_sort[j][1] == 1: tp += 1 if sample_sort[j][1] == 0: fp += 1 x.append(fp/neg) y.append(tp/pos) x.append(0) y.append(0)
auc = 0 for i in range(len(x)-1): auc += ((x[i]-x[i+1]) * (y[i]+y[i+1]))
plt.clf() plt.title('Small_Intestine_Classifier_ROC') plt.plot(x, y, 'b', label='AUC = %.3f ACC = %.3f' % (auc*0.5)) plt.xlabel('FPR') plt.ylabel('TPR') plt.legend(loc='lower right') plt.plot([0, 1], [0, 1], 'r--') plt.savefig("./temp/Small_Intestine_Classifier_ROC_AUC=%.3f_EfficientNet.jpg" % (auc*0.5))
return auc*0.5
|