forked from fastmachinelearning/hls4ml-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 1
/
plotting.py
89 lines (70 loc) · 2.69 KB
/
plotting.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
import itertools
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.metrics import auc, roc_curve
# confusion matrix code from Maurizio
# /eos/user/m/mpierini/DeepLearning/ML4FPGA/jupyter/HbbTagger_Conv1D.ipynb
def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
plt.imshow(cm, interpolation='nearest', cmap=cmap)
# plt.title(title)
cbar = plt.colorbar()
plt.clim(0, 1)
cbar.set_label(title)
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
fmt = '.2f' if normalize else 'd'
thresh = cm.max() / 2.0
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, format(cm[i, j], fmt), horizontalalignment="center", color="white" if cm[i, j] > thresh else "black")
# plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
def plotRoc(fpr, tpr, auc, labels, linestyle, legend=True):
for _i, label in enumerate(labels):
plt.plot(
tpr[label],
fpr[label],
label='{} tagger, AUC = {:.1f}%'.format(label.replace('j_', ''), auc[label] * 100.0),
linestyle=linestyle,
)
plt.semilogy()
plt.xlabel("Signal Efficiency")
plt.ylabel("Background Efficiency")
plt.ylim(0.001, 1)
plt.grid(True)
if legend:
plt.legend(loc='upper left')
plt.figtext(0.25, 0.90, 'hls4ml', fontweight='bold', wrap=True, horizontalalignment='right', fontsize=14)
def rocData(y, predict_test, labels):
df = pd.DataFrame()
fpr = {}
tpr = {}
auc1 = {}
for i, label in enumerate(labels):
df[label] = y[:, i]
df[label + '_pred'] = predict_test[:, i]
fpr[label], tpr[label], threshold = roc_curve(df[label], df[label + '_pred'])
auc1[label] = auc(fpr[label], tpr[label])
return fpr, tpr, auc1
def makeRoc(y, predict_test, labels, linestyle='-', legend=True):
if 'j_index' in labels:
labels.remove('j_index')
fpr, tpr, auc1 = rocData(y, predict_test, labels)
plotRoc(fpr, tpr, auc1, labels, linestyle, legend=legend)
return predict_test
def print_dict(d, indent=0):
for key, value in d.items():
print(' ' * indent + str(key), end='')
if isinstance(value, dict):
print()
print_dict(value, indent + 1)
else:
print(':' + ' ' * (20 - len(key) - 2 * indent) + str(value))