-
Notifications
You must be signed in to change notification settings - Fork 0
/
kerasTensorflowClassifier.py
169 lines (132 loc) · 5.66 KB
/
kerasTensorflowClassifier.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
#!/usr/bin/env python
"""Read the training set and train a machine.
Usage:
%s <trainingset> [--classifierfile=<classifierfile>] [--outputcsv=<outputcsv>]
%s (-h | --help)
%s --version
Options:
-h --help Show this screen.
--version Show version.
--classifierfile=<classifierfile> Classifier file [default: /tmp/atlas.model.best.hdf5].
--outputcsv=<outputcsv> Output file [default: /tmp/output.csv].
"""
import sys
__doc__ = __doc__ % (sys.argv[0], sys.argv[0], sys.argv[0])
from docopt import docopt
import os, shutil, re
from gkutils import Struct, cleanOptions
import h5py
import numpy as np
import scipy.io as sio
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Dense, Dropout, Conv2D, MaxPooling2D, Flatten
from keras.callbacks import ModelCheckpoint
from rocCurve import roc_curve
def one_percent_mdr(y_true, y_pred):
t = 0.01
fpr, tpr, thresholds = roc_curve(y_true, y_pred, step=0.001)
return fpr[np.where(1-tpr<=t)[0]][-1]
def one_percent_fpr(y_true, y_pred):
t = 0.01
fpr, tpr, thresholds = roc_curve(y_true, y_pred, step=0.001)
return 1-tpr[np.where(fpr<=t)[0]][0]
def load_data(filename):
#data = sio.loadmat(filename)
data = h5py.File(filename,'r')
X = data['X']
y_train = np.squeeze(data['y'])
ascii_train_files = data['train_files']
train_files = np.squeeze([n.decode("utf-8") for n in ascii_train_files])
m, n = X.shape
image_dim = int(np.sqrt(n))
x_train = np.zeros((m, image_dim, image_dim, 1))
for i in range(m):
x_train[i,:,:,0] += np.reshape(X[i], (image_dim, image_dim), order='F')
X = data['testX']
y_test = np.squeeze(data['testy'])
ascii_test_files = data['test_files']
test_files = np.squeeze([n.decode("utf-8") for n in ascii_test_files])
m, n = X.shape
x_test = np.zeros((m, image_dim, image_dim, 1))
for i in range(m):
x_test[i,:,:,0] += np.reshape(X[i], (image_dim, image_dim), order='F')
return (x_train, y_train, train_files), (x_test, y_test, test_files), image_dim
def create_model(num_classes, image_dim):
model = Sequential()
model.add(Conv2D(filters=16, kernel_size=2, padding='same', \
activation='relu', input_shape=(image_dim, image_dim, 1)))
model.add(MaxPooling2D(pool_size=2))
model.add(Conv2D(filters=32, kernel_size=2, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Conv2D(filters=64, kernel_size=2, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Dropout(0.3))
model.add(Flatten())
model.add(Dense(500, activation='relu'))
model.add(Dropout(0.4))
model.add(Dense(num_classes, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', \
kerasmetrics=['accuracy'])
return model
def kerasTensorflowClassifier(opts):
# Use utils.Struct to convert the dict into an object for compatibility with old optparse code.
if type(opts) is dict:
options = Struct(**opts)
else:
options = opts
filename = options.trainingset
#filename = 'andrei_20x20_skew3_signpreserve_f200000b600000.mat'
train_data, test_data, image_dim = load_data(filename)
num_classes = 2
x_train = train_data[0]
y_train = np_utils.to_categorical(train_data[1], num_classes)
m = x_train.shape[0]
split_frac = int(.75*m)
(x_train, x_valid) = x_train[:split_frac], x_train[split_frac:]
(y_train, y_valid) = y_train[:split_frac], y_train[split_frac:]
x_test = test_data[0]
#y_test = np_utils.to_categorical(test_data[1], num_classes)
y_test = test_data[1]
model = create_model(num_classes, image_dim)
"""
checkpointer = ModelCheckpoint(filepath=options.classifierfile, \
verbose=1, save_best_only=True)
model.fit(x_train, y_train, batch_size=128, epochs=20, \
validation_data=(x_valid, y_valid), \
callbacks=[checkpointer], verbose=1, shuffle=True)
"""
if not os.path.exists(options.classifierfile):
# If we don't already have a trained classifier, train a new one.
checkpointer = ModelCheckpoint(filepath=options.classifierfile, \
verbose=1, save_best_only=True)
print(checkpointer)
model.fit(x_train, y_train, batch_size=128, epochs=20, \
validation_data=(x_valid, y_valid), \
callbacks=[checkpointer], verbose=1, shuffle=True)
model.load_weights(options.classifierfile)
(y_train, y_valid) = train_data[1][:split_frac], train_data[1][split_frac:]
print('[+] Training Set Error:')
pred = model.predict(x_train, verbose=0)
print((one_percent_mdr(y_train, pred[:,1])))
print((one_percent_fpr(y_train, pred[:,1])))
print('[+] Validation Set Error:')
pred = model.predict(x_valid, verbose=0)
print((one_percent_mdr(y_valid, pred[:,1])))
print((one_percent_fpr(y_valid, pred[:,1])))
print('[+] Test Set Error:')
pred = model.predict(x_test, verbose=0)
print((one_percent_mdr(y_test, pred[:,1])))
print((one_percent_fpr(y_test, pred[:,1])))
output = open(options.outputcsv,"w")
for i in range(len(pred[:,1])):
output.write("%s,%d,%.3lf\n"%(test_data[2][i], y_test[i], pred[i,1]))
output.close()
def main():
opts = docopt(__doc__, version='0.1')
opts = cleanOptions(opts)
# Use utils.Struct to convert the dict into an object for compatibility with old optparse code.
options = Struct(**opts)
kerasTensorflowClassifier(options)
if __name__ == '__main__':
main()