-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmetrics.py
60 lines (50 loc) · 2.07 KB
/
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
import numpy as np
import matplotlib.pyplot as plt
import itertools
import os
def plot_confusion_matrix(cm,
target_names,
title='Confusion matrix',
cmap=None,
normalize=True,
save_dir=None):
"""Function to plot confusion matrics.
:param cm: confusion_matrix: function in sklearn.
:param target_names: list of classes.
:param cmap: str or matplotlib Colormap: Colormap recognized by matplotlib.
:param normalize: normalizes confusion matrix over the true (rows), predicted (columns) conditions or all the population.
:param save_dir: str: directory address to save.
"""
accuracy = np.trace(cm) / float(np.sum(cm))
misclass = 1 - accuracy
if cmap is None:
cmap = plt.get_cmap('Blues')
plt.figure(figsize=(10, 8))
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
if target_names:
tick_marks = np.arange(len(target_names))
plt.xticks(tick_marks, target_names, rotation=90)
plt.yticks(tick_marks, target_names)
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
thresh = cm.max() / 1.5 if normalize else cm.max() / 2
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
if normalize:
plt.text(j, i, "{:0.2f}".format(cm[i, j]),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
else:
plt.text(j, i, "{:,}".format(cm[i, j]),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label. Metrics: accuracy={:0.2f}; misclass={:0.2f}'.format(accuracy, misclass))
try:
if os.path.exists(save_dir) is False:
os.mkdir(save_dir)
plt.savefig((save_dir + '/{}.png'.format(title)))
except IOError as e:
print(e)