-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVisualizer.py
More file actions
205 lines (160 loc) · 5.77 KB
/
Copy pathVisualizer.py
File metadata and controls
205 lines (160 loc) · 5.77 KB
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
# import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
import numpy as np
import os
import cv2
import torch
import itertools
from matplotlib.font_manager import FontProperties
from mpl_toolkits.axes_grid1 import make_axes_locatable
from sklearn.metrics import confusion_matrix
if os.name == 'nt':
fontp = FontProperties(family='Tahoma', size=10)
else:
fontp = FontProperties(family='Tlwg Typo', size=10)
def plot_ConfuseMatrix(tp, fp, fn, tn, cm=None, labels=('positive', 'negative'), title='Confusion Matrix',
tight_layout=False, fig_size=(10, 10), save=None):
if cm is None:
cm = np.array([[1, 0], [0, 1]])
fig = plt.figure(figsize=fig_size)
plt.imshow(cm, interpolation='nearest', cmap=plt.get_cmap('summer'))
plt.title(title, fontproperties=FontProperties(None, size=14))
plt.xticks(np.arange(2), labels, rotation=45)
plt.yticks(np.arange(2), labels)
plt.xlabel('True')
plt.ylabel('Pred')
plt.colorbar()
s = [[tp, fp], [fn, tn]]
for i in range(2):
for j in range(2):
plt.text(j, i, str(s[i][j]), horizontalalignment="center",
fontproperties=FontProperties(None, size=14))
if tight_layout:
plt.tight_layout()
if save is not None:
plt.savefig(save)
plt.close()
else:
return fig
def plot_confusion_matrix(cls_true, cls_pred, cls_names=None, normalize=False,
filter_true=None, filter_pred=None, title='Confusion matrix',
cmap='viridis', fig_size=(9, 9), save=None):
if cls_names is None:
cls_names = np.unique(cls_true)
cm = confusion_matrix(y_true=cls_true, y_pred=cls_pred, labels=cls_names)
real = cm.copy()
if normalize:
div = cm.sum(axis=1)[:, np.newaxis]
div[div == 0] = 1
cm = cm.astype('float') / div
x_tick = np.arange(len(cls_names))
x_tick_label = cls_names
y_tick = np.arange(len(cls_names))
y_tick_label = cls_names
if filter_true is not None:
idx = [cls_names.index(c) for c in filter_true]
cm = cm[idx, :]
real = real[idx, :]
y_tick = np.arange(len(filter_true))
y_tick_label = filter_true
if filter_pred is not None:
idx = [cls_names.index(c) for c in filter_pred]
cm = cm[:, idx]
real = real[:, idx]
x_tick = np.arange(len(filter_pred))
x_tick_label = filter_pred
plt.figure(figsize=fig_size)
ax = plt.gca()
im = plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.xticks(x_tick, x_tick_label, rotation=45, fontproperties=fontp)
plt.yticks(y_tick, y_tick_label, fontproperties=fontp)
thresh = cm.max() / 2.
for i, j in itertools.product(range(real.shape[0]), range(real.shape[1])):
plt.text(j, i, str(real[i, j]), horizontalalignment="center",
fontproperties=FontProperties(None, size=8),
color="black" if cm[i, j] > thresh else "white")
plt.ylabel('True label')
plt.xlabel('Predicted label')
divider = make_axes_locatable(ax)
cax = divider.append_axes('right', size='5%', pad=0.05)
plt.colorbar(im, cax=cax)
plt.tight_layout()
if save is not None:
plt.savefig(save)
plt.close()
def plot_bars(x, y, title='', ylim=None, save=None):
plt.figure()
bars = plt.bar(x, y)
plt.ylim(ylim)
plt.title(title)
for b in bars:
plt.annotate('{:.4f}'.format(b.get_height()),
xy=(b.get_x(), b.get_height()))
if save is not None:
plt.savefig(save)
plt.close()
def plot_graphs(x_list, legends, title, ylabel, xlabel='epoch', xlim=None, ylim=None, save=None):
plt.figure()
for x in x_list:
plt.plot(x)
plt.legend(legends)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.title(title)
plt.xlim(xlim)
plt.ylim(ylim)
if save is not None:
plt.savefig(save)
plt.close()
def plot_x(x, title=None, fig_size=(12, 10)):
fig = plt.figure(figsize=fig_size)
x = np.squeeze(x)
if len(x.shape) == 1:
plt.plot(x)
elif len(x.shape) == 2:
plt.imshow(x, cmap='gray')
plt.axis('off')
elif len(x.shape) == 3:
if x.shape[-1] == 3:
plt.imshow(x)
plt.axis('off')
else:
fig = plot_multiImage(x.transpose(2, 0, 1), fig_size=fig_size)
elif len(x.shape) == 4:
fig = plot_multiImage(x.transpose(3, 0, 1, 2), fig_size=fig_size)
if title is not None:
fig.suptitle(title)
return fig
# images in shape (amount, h, w, c).
def plot_multiImage(images, labels=None, pred=None, title=None, fig_size=(12, 10), tight_layout=False, save=None):
n = int(np.ceil(np.sqrt(len(images))))
fig = plt.figure(figsize=fig_size)
for i in range(len(images)):
ax = fig.add_subplot(n, n, i + 1)
ax.imshow(images[i])
if labels is not None:
ax.set_xlabel(str(labels[i]), color='g', fontproperties=fontp)
if labels is not None and pred is not None:
if labels[i] == pred[i]:
clr = 'g'
else:
if len(labels[i]) == len(pred[i]):
clr = 'm'
else:
clr = 'r'
ax.set_xlabel('True: {}\nPred : {}'.format(u'' + labels[i], u'' + pred[i]),
color=clr, fontproperties=fontp)
if title is not None:
fig.suptitle(title)
if tight_layout: # This make process slow if too many images.
fig.tight_layout()
if save is not None:
plt.savefig(save)
plt.close()
else:
return fig
def get_fig_image(fig): # figure to array of image.
fig.canvas.draw()
img = np.array(fig.canvas.renderer._renderer)
return img