-
Notifications
You must be signed in to change notification settings - Fork 0
/
evaluation.py
138 lines (105 loc) · 5.45 KB
/
evaluation.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
from tensorflow import keras
from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
from keras.callbacks import ModelCheckpoint
import numpy as np
import pandas as pd
from sklearn.metrics import confusion_matrix,classification_report
import json
import argparse
import os
from matplotlib.image import imread
from utils import get_cifar10
import time
def evaluate_model(X_test,Y_test,model,config):
test_batch_size = config['test_batch_size']
test_scores = model.evaluate(X_test, Y_test, verbose=1, batch_size=test_batch_size)
print('Test loss:', test_scores[0])
print('Test accuracy:', test_scores[1])
pred = model.predict(X_test)
pred = np.argmax(pred, axis=1)
label = np.argmax(Y_test,axis=1)
report = classification_report(label,pred)
cm = np.array2string(confusion_matrix(label,pred))
timestr = time.strftime("%Y%m%d-%H%M%S")
f = open('results/report-{}.txt'.format(timestr), 'w')
f.write('Classification Report\n\n{}\n\nConfusion Matrix\n\n{}\n'.format(report,cm))
f.close()
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-w', '--model_path', help='path directory to model', required=True)
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-d', '--data_path', help='path directory to data folder')
group.add_argument('-a', '--data_aug', help='initialize data augmentation', action='store_true')
args = parser.parse_args()
with open('config/model.json') as f:
model_config = json.load(f)
with open('config/training.json') as f:
train_config = json.load(f)
model_path = args.model_path
model = keras.models.load_model(args.model_path)
if args.data_path:
train_path = args.data_path + '\\train'
test_path = args.data_path + '\\test'
datagen = ImageDataGenerator(rescale = 1./255)
train_batches = datagen.flow_from_directory(train_path,
target_size=model_config['0']['input_shape'][:2],
batch_size=train_config['train_batch_size'],
class_mode='categorical')
test_batches = datagen.flow_from_directory(test_path,
target_size=model_config['0']['input_shape'][:2],
batch_size=train_config['test_batch_size'],
class_mode='categorical',
shuffle=False)
X_test,Y_test = test_batches.next()
else:
X_train,Y_train,X_test,Y_test = get_cifar10(model_config['0'])
#Data Augmentation
if args.data_aug:
datagen = ImageDataGenerator(width_shift_range=0.2,
horizontal_flip=True,
height_shift_range=0.2,
rotation_range=20)
datagen.fit(X_train)
checkpointer = ModelCheckpoint(filepath='saved_models/' + model.name + '-{epoch:02d}-{val_loss:.2f}.hdf5',
monitor='val_loss',
verbose=1,
save_best_only=False,
save_weights_only=False,
mode='auto',
period=1)
model.fit_generator(datagen.flow(X_train,Y_train,batch_size=train_config['train_batch_size']),
steps_per_epoch=None,
epochs=train_config['epochs'],
validation_data=(X_test,Y_test),
callbacks=[checkpointer]
)
evaluate_model(X_test,Y_test,model,train_config)
elif args.data_path:
checkpointer = ModelCheckpoint(filepath='saved_models/' + model.name + '-{epoch:02d}-{val_loss:.2f}.hdf5',
monitor='val_loss',
verbose=1,
save_best_only=False,
save_weights_only=False,
mode='auto',
period=1)
model.fit_generator(train_batches,
steps_per_epoch=None,
epochs=train_config['epochs'],
validation_data=test_batches,
callbacks=[checkpointer]
)
evaluate_model(X_test,Y_test,model,train_config)
else:
checkpointer = ModelCheckpoint(filepath='saved_models/' + model.name + '-{epoch:02d}-{val_loss:.2f}.hdf5',
monitor='val_loss',
verbose=1,
save_best_only=False,
save_weights_only=False,
mode='auto',
period=1)
model.fit(X_train,Y_train,batch_size=train_config['train_batch_size'],
epochs=train_config['epochs'],
validation_split=train_config['train_validation_split'],
callbacks=[checkpointer]
)
evaluate_model(X_test,Y_test,model,train_config)