-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
299 lines (235 loc) · 8.92 KB
/
utils.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
from imgaug import augmenters as iaa
import matplotlib.pyplot as plt
from itertools import cycle
from scipy import interp
import tensorflow as tf
import itertools
import numpy as np
import json
import argparse
import warnings
import os
from synth.utils import datagenerate
from sklearn.metrics import roc_curve, auc, accuracy_score
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
def rand_augment(images):
"""Random augmentation
Args:
images (4D array): data images
Returns:
[4D array] data after augmentation
"""
rand_aug = datagenerate()
images = tf.cast(images, tf.uint8)
return rand_aug(images=images.numpy())
def get_data(input_dir, fname):
"""Get data from npy file
Args:
input_dir (string): ịnput directory
fname (string): name of npy file
Returns:
[4D array] data
"""
f = os.path.join(input_dir, fname + ".npy")
return np.load(f)
def ensure_dir(directory):
"""Make sure the directory exists
Args:
directory (string): name of directory
Returns:
None
"""
if not os.path.exists(directory):
warnings.warn('''[WARNING]: Output directory not found.
The default output directory will be created.''')
os.makedirs(directory)
def get_target_names(json_label_decode):
"""Get encode of label
Args:
json_label_decode (string): path to json file
Returns:
[dict] encode of label
"""
with open(json_label_decode) as f:
label_decode = json.load(f)
return label_decode
def history_plot(FLAGS, n_class):
"""Plot traning history about: categorical_accuracy, loss and auc, accuracy
Args:
FLAGS (argument parser): input information
n_class (int): number of classes
Returns:
[None]
"""
with open(FLAGS.json_history) as f:
h = json.load(f)
history = dict()
if n_class == 2:
history['accuracy'] = list(h['binary_accuracy'].values())
history['val_accuracy'] = list(h['val_binary_accuracy'].values())
else:
history['accuracy'] = list(h['categorical_accuracy'].values())
history['val_accuracy'] = list(h['val_categorical_accuracy'].values())
history['loss'] = list(h['loss'].values())
history['val_loss'] = list(h['val_loss'].values())
history['auc'] = list(h['auc'].values())
history['val_auc'] = list(h['val_auc'].values())
x = np.arange(len(history['accuracy']))
fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(8, 4))
fig.suptitle('History training of {}'.format(FLAGS.model_name))
#plot accuracy
ax[0].plot(x, history['accuracy'], label = 'accuracy')
ax[0].plot(x, history['val_accuracy'], label = 'val_accuracy')
ax[0].plot(x, history['auc'], label = 'auc')
ax[0].plot(x, history['val_auc'], label = 'val_auc')
ax[0].set_title("accuracy/auc")
ax[0].set_xlabel('epoch')
ax[0].set_ylabel('accuracy/auc')
ax[0].legend(shadow=True, fancybox=True, loc='lower right')
#plot loss
ax[1].plot(x, history['loss'], label = 'loss')
ax[1].plot(x, history['val_loss'], label = 'val_loss')
ax[1].set_title("loss")
ax[1].set_xlabel('epoch')
ax[1].set_ylabel('loss')
ax[1].legend(shadow=True, fancybox=True, loc='upper right')
plt.savefig(os.path.join(FLAGS.output_dir, 'history_of_{}.png'.format(FLAGS.model_name)))
plt.close()
def roc_plot(FLAGS, y_test, y_score, target_names):
"""Plot Receiver Operating Characteristic curve
Args:
FLAGS (argument parser): input information
y_test (2D array): true label of test data
y_score (2D) array: prediction label of test data
target_names (1D array): array of encode label
Returns:
[datagen]
"""
n_classes = y_test.shape[1]
lw = 2
# Compute ROC curve and ROC area for each class
fpr = dict()
tpr = dict()
roc_auc = dict()
for i in range(n_classes):
fpr[i], tpr[i], _ = roc_curve(y_test[:, i], y_score[:, i])
roc_auc[i] = auc(fpr[i], tpr[i])
# First aggregate all false positive rates
all_fpr = np.unique(np.concatenate([fpr[i] for i in range(n_classes)]))
# Then interpolate all ROC curves at this points
mean_tpr = np.zeros_like(all_fpr)
for i in range(n_classes):
mean_tpr += interp(all_fpr, fpr[i], tpr[i])
# Finally average it and compute AUC
mean_tpr /= n_classes
# Plot all ROC curves
plt.figure()
# colors = cycle(['aqua', 'darkorange', 'cornflowerblue'])
for i in range(n_classes):
plt.plot(fpr[i], tpr[i], lw=lw,
label='ROC curve of class {0} (area = {1:0.2f})'
''.format(target_names[i], roc_auc[i]))
plt.plot([0, 1], [0, 1], 'k--', lw=lw)
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver Operating Characteristic - {}'.format(FLAGS.model_name))
plt.legend(loc="lower right")
plt.savefig(os.path.join(FLAGS.output_dir, 'roc_of_{}.png'.format(FLAGS.model_name)))
plt.close()
def statistics(FLAGS, y_test, target_names):
"""Statistics for the number of images per class after shuffling.
Args:
FLAGS (argument parser): input information
y_test (2D array): true label of test data
target_names (1D array): array of encode label
Returns:
[None]
"""
sta_test = np.sum(y_test, axis=0); temp = sta_test.copy()
#sum equal one
sta_test = sta_test/y_test.shape[0]
explode = np.ones(len(sta_test))*0.1
#label
target_names = [(name + ':' + str(int(item))) for name, item in zip(target_names, temp)]
#plot
plt.pie(sta_test, explode=explode, labels=target_names, shadow=True, startangle=45)
plt.axis('equal')
plt.legend(title='Statistic On Test Data')
plt.savefig(os.path.join(FLAGS.output_dir, 'label_statistics.png'))
plt.close()
def plot_confusion_matrix(FLAGS, cm, classes,
normalize=True,
title='Confusion matrix',
cmap=plt.cm.Blues):
"""This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
Args:
cm (2D array): confusion matrix
classes (1D list): list of class names
normalize (boolean): normalization or not, default true
Returns:
[None]
"""
if normalize:
cm = cm.astype('float') / cm.sum(axis=1, keepdims = True)
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
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.
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')
plt.savefig(os.path.join(FLAGS.output_dir, 'confusion_matrix_of_{}.png'.format(FLAGS.model_name)))
plt.close()
def evaluate(FLAGS, y_test, y_score, n_class):
"""Evaluate the quality of the model
Args:
FLAGS (argument parser): input information
y_test (2D array): true label of test data
y_score (2D) array: prediction label of test data
n_class (int): number of classes
Returns:
[None]
"""
if os.path.exists(FLAGS.json_label_decode):
label_decode = get_target_names(FLAGS.json_label_decode)
target_names = []
for i in label_decode:
target_names.append(label_decode[i])
else: raise ValueError('[ERROR]: {} is not found'.format(FLAGS.json_label_decode))
#statistics
print("[INFOR]: Plot Statistics\n")
statistics(FLAGS, y_test, target_names)
#plot roc
print("[INFOR]: Plot Receiver Operating Characteristic\n")
roc_plot(FLAGS, y_test, y_score, target_names)
#plot history
print("[INFOR]: Plot History.\n")
if os.path.exists(FLAGS.json_history):
history_plot(FLAGS, n_class)
else: warnings.warn('''[WARNING]: {} is not found,
plot history is ignored'''.format(FLAGS.json_history))
#convert to 1D array
y_test = np.argmax(y_test, axis=1)
y_score = np.argmax(y_score, axis=1)
print("\n\n[INFOR]: Plot confusion matrix\n")
cm = confusion_matrix(y_test, y_score)
plot_confusion_matrix(FLAGS, cm, target_names, normalize=False)
print("\n\n[INFOR]: Report test data\n")
print(classification_report(y_test, y_score,
target_names=target_names))
print("\n\n[INFOR]: Report accuracy\n")
print(accuracy_score(y_test, y_score), '\n')
print("\n\n[INFOR]: See more result in {} folder\n".format(FLAGS.output_dir))
print()