-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodel.py
216 lines (180 loc) · 7.45 KB
/
model.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
import numpy as np
import joblib
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, BatchNormalization
from keras.layers import Conv2D, MaxPooling2D
from keras.layers.advanced_activations import LeakyReLU
from keras.models import load_model
from keras.callbacks import EarlyStopping, ModelCheckpoint
from keras import backend as K
from tensorflow.keras.optimizers import Adam
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
from tensorflow.keras.utils import to_categorical
import seaborn as sns
from training_data import TrainingData
from variables import *
from filters import *
class Model:
# This class method loads a model file from disk in two parts
# 1) The raw savefile for the neural network and weights
# 2) Additional attributes for the model class (e.g. name, score)
def load():
home_dir = os.getcwd()
os.chdir(Vars.MODELS_DIR)
model = Model()
filename = Vars.MODEL_ATTR_FILENAME
attr = joblib.load(filename)
print('loaded model attributes from ' + filename)
model.calls = attr[0]
model.score = attr[1]
model.cmatrix = attr[2]
filename = Vars.MODEL_FILENAME
model.classifier = load_model(filename)
print('loaded model classifier from ' + filename)
os.chdir(home_dir)
return model
# Run evaluation script and save confusion matrix to disk
def evaluate():
model = Model.load()
tdata = TrainingData.load()
(X_train, y_train), (X_test, y_test), (X_validation, y_validation) = model.combine_and_add_targets(tdata)
X_test = model.prefilter(X_test)
X_validation = model.prefilter(X_validation)
y_test = to_categorical(y_test)
y_validation = to_categorical(y_validation)
model.score = model.classifier.evaluate(X_test, y_test, verbose=1)
print('Test loss:', model.score[0])
print('Test accuracy:', model.score[1])
X = np.concatenate((X_test, X_validation))
y = np.concatenate((y_test, y_validation))
y_pred = model.classifier.predict(X)
cmatrix = confusion_matrix(np.argmax(y, axis=1), np.argmax(y_pred, axis=1))
print(model.calls)
print(cmatrix)
ax = sns.heatmap(cmatrix, annot=True, fmt='d', xticklabels=model.calls, yticklabels=model.calls)
ax.xaxis.tick_top()
ax.xaxis.set_label_position('top')
plt.xlabel('predicted')
plt.ylabel('actual')
fig = ax.get_figure()
fig.savefig(Vars.MODELS_DIR + '/' + Vars.MODEL_CMATRIX_FILENAME)
plt.show()
def __init__(self):
self.classifier = None
self.calls = None
self.score = None
self.cmatrix = None
# Loads the training data pertaining to the call type, then creates and trains the model
def train(self):
print('gathering training data...')
tdata = TrainingData.load()
(X_train, y_train), (X_test, y_test), (X_validation, y_validation) = self.combine_and_add_targets(tdata)
X_train = self.prefilter(X_train)
X_test = self.prefilter(X_test)
X_validation = self.prefilter(X_validation)
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)
y_validation = to_categorical(y_validation)
num_classes = len(self.calls)
print('commencing training...')
input_shape = (Vars.SQUARIFY_SIZE, Vars.SQUARIFY_SIZE, 1)
model = Sequential()
model.add(Conv2D(64, kernel_size=(3,3),
padding='same',
input_shape=input_shape))
model.add(BatchNormalization(momentum=0.9))
model.add(LeakyReLU(alpha=0.1))
model.add(Conv2D(64, kernel_size=(3,3),
padding='same',
strides=2))
model.add(BatchNormalization(momentum=0.9))
model.add(LeakyReLU(alpha=0.1))
model.add(Conv2D(64, kernel_size=(3,3),
padding='same',
strides=2))
model.add(BatchNormalization(momentum=0.9))
model.add(LeakyReLU(alpha=0.1))
model.add(Conv2D(64, kernel_size=(3,3),
padding='same',
strides=2))
model.add(BatchNormalization(momentum=0.9))
model.add(LeakyReLU(alpha=0.1))
model.add(Flatten())
model.add(Dropout(0.4))
model.add(Dense(2048))
model.add(LeakyReLU(alpha=0.2))
model.add(Dropout(0.3))
model.add(Dense(512))
model.add(LeakyReLU(alpha=0.2))
model.add(Dropout(0.2))
model.add(Dense(num_classes, activation='softmax'))
model.compile(loss=keras.losses.categorical_crossentropy,
optimizer=Adam(0.0002, 0.5),
metrics=['accuracy'])
print('printed model')
temp_filepath = Vars.MODELS_DIR+'/'+Vars.MODEL_FILENAME
save_best_model = ModelCheckpoint(filepath=temp_filepath,
monitor='val_loss',
verbose=1,
save_best_only=True)
model.fit(X_train, y_train,
batch_size=Vars.TRAINING_BATCH_SIZE,
epochs=Vars.TRAINING_EPOCHS,
verbose=1,
callbacks=[save_best_model],
validation_data=(X_validation, y_validation))
self.classifier = model
print('training complete!')
# Uses the trained classifier to make a prediction on a single input
def predict_single(self, x):
if not Filters.simple_check(x):
return [0]*len(self.calls)
X = self.prefilter([x])
result = self.classifier.predict(X)[0]
return result
# Prefilter images
def prefilter(self, X):
Xp = []
for i in range(len(X)):
x = Filters.squarify(X[i])
x = Filters.rescale(x)
x = np.expand_dims(x, 2)
Xp.append(x)
Xp = np.array(Xp)
return Xp
# Combine the different call training data and add the targets (i.e. the correct labels)
def combine_and_add_targets(self, tdata):
X_train, y_train = self.get_X_y(tdata.training_data)
X_test, y_test = self.get_X_y(tdata.testing_data)
X_validation, y_validation = self.get_X_y(tdata.validation_data)
return (X_train, y_train), (X_test, y_test), (X_validation, y_validation)
# Helper function for above
def get_X_y(self, data):
calls = list(data.keys())
calls.sort()
calls.remove(Vars.NOISE_STRING)
calls.append(Vars.NOISE_STRING)
if type(self.calls) == type(None):
self.calls = calls
X = []
y = []
for i in range(len(calls)):
call_data = data[calls[i]]
X.extend(call_data)
y.extend([i]*len(call_data))
return X, y
# Save trained model to model directory in the afortmentioned two parts
def save(self, in_models_dir=False):
home_dir = os.getcwd()
if in_models_dir:
os.chdir(Vars.MODELS_DIR)
print('saving model...')
filename = Vars.MODEL_FILENAME
self.classifier.save(filename)
attr = [self.calls, self.score, self.cmatrix]
filename = Vars.MODEL_ATTR_FILENAME
joblib.dump(attr, filename)
print(' complete')
os.chdir(home_dir)