-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy path07.evaluate_CNN_LSTM.py
329 lines (280 loc) · 9.27 KB
/
07.evaluate_CNN_LSTM.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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
from keras.models import Model
from keras.layers import Dense, GlobalAveragePooling2D, Input
from keras.applications.resnet50 import ResNet50
from keras.layers.core import Dropout
from keras.optimizers import Nadam
from keras.applications.inception_v3 import InceptionV3
from keras.applications.inception_resnet_v2 import InceptionResNetV2
from keras.applications.xception import Xception
from keras.applications.nasnet import NASNetLarge
from keras_efficientnets import EfficientNetB0, EfficientNetB5
from keras import backend as K
import numpy as np
from sklearn.metrics import (
precision_score,
recall_score,
f1_score,
accuracy_score
)
import imageio.core.util
from facenet_pytorch import MTCNN
from PIL import Image
import pandas as pd
import cv2
from keras.layers import LSTM, Bidirectional
import time
from keras.engine import InputSpec
from keras.engine.topology import Layer
import argparse
def ignore_warnings(*args, **kwargs):
pass
def cnn_model(model_name, img_size, weights):
"""
Model definition using Xception net architecture
"""
input_size = (img_size, img_size, 3)
if model_name == "xception":
baseModel = Xception(
weights="imagenet",
include_top=False,
input_shape=(img_size, img_size, 3)
)
elif model_name == "iv3":
baseModel = InceptionV3(
weights="imagenet",
include_top=False,
input_shape=(img_size, img_size, 3)
)
elif model_name == "irv2":
baseModel = InceptionResNetV2(
weights="imagenet",
include_top=False,
input_shape=(img_size, img_size, 3)
)
elif model_name == "resnet":
baseModel = ResNet50(
weights="imagenet",
include_top=False,
input_shape=(img_size, img_size, 3)
)
elif model_name == "nasnet":
baseModel = NASNetLarge(
weights="imagenet",
include_top=False,
input_shape=(img_size, img_size, 3)
)
elif model_name == "ef0":
baseModel = EfficientNetB0(
input_size,
weights="imagenet",
include_top=False
)
elif model_name == "ef5":
baseModel = EfficientNetB5(
input_size,
weights="imagenet",
include_top=False
)
headModel = baseModel.output
headModel = GlobalAveragePooling2D()(headModel)
headModel = Dense(
512,
activation="relu",
kernel_initializer="he_uniform",
name="fc1")(
headModel
)
headModel = Dropout(0.4)(headModel)
predictions = Dense(
2,
activation="softmax",
kernel_initializer="he_uniform")(
headModel
)
model = Model(inputs=baseModel.input, outputs=predictions)
model.load_weights(weights)
print("Weights loaded...")
model_lstm = Model(
inputs=baseModel.input,
outputs=model.get_layer("fc1").output
)
for layer in baseModel.layers:
layer.trainable = True
optimizer = Nadam(
lr=0.002, beta_1=0.9, beta_2=0.999, epsilon=1e-08, schedule_decay=0.004
)
model.compile(
loss="categorical_crossentropy",
optimizer=optimizer,
metrics=["accuracy"]
)
return model_lstm
def lstm_model(shape):
# Model definition
main_input = Input(
shape=(shape[0],
shape[1]),
name="main_input"
)
# headModel = Bidirectional(LSTM(256, return_sequences=True))(main_input)
headModel = LSTM(32)(main_input)
# headModel = TemporalMaxPooling()(headModel)
# headModel = TimeDistributed(Dense(512))(headModel)
# # headModel = Bidirectional(LSTM(512, dropout=0.2))(main_input)
# headModel = LSTM(256)(headModel)
predictions = Dense(
2,
activation="softmax",
kernel_initializer="he_uniform"
)(headModel)
model = Model(inputs=main_input, outputs=predictions)
# Model compilation
# opt = SGD(lr=1e-4, momentum=0.9, decay=1e-4 / EPOCHS)
optimizer = Nadam(
lr=0.002, beta_1=0.9, beta_2=0.999, epsilon=1e-08, schedule_decay=0.004
)
model.compile(
loss="categorical_crossentropy",
optimizer=optimizer,
metrics=["accuracy"]
)
return model
class TemporalMaxPooling(Layer):
"""
This pooling layer accepts the temporal sequence output by a recurrent layer
and performs temporal pooling, looking at only the non-masked portion of the sequence.
The pooling layer converts the entire variable-length hidden vector sequence
into a single hidden vector.
Modified from https://github.com/fchollet/keras/issues/2151 so code also
works on tensorflow backend. Updated syntax to match Keras 2.0 spec.
Args:
Just put it on top of an RNN Layer (GRU/LSTM/SimpleRNN) with return_sequences=True.
The dimensions are inferred based on the output shape of the RNN.
3D tensor with shape: `(samples, steps, features)`.
input shape: (nb_samples, nb_timesteps, nb_features)
output shape: (nb_samples, nb_features)
Examples:
> x = Bidirectional(GRU(128, return_sequences=True))(x)
> x = TemporalMaxPooling()(x)
"""
def __init__(self, **kwargs):
super(TemporalMaxPooling, self).__init__(**kwargs)
self.supports_masking = True
self.input_spec = InputSpec(ndim=3)
def compute_output_shape(self, input_shape):
return (input_shape[0], input_shape[2])
def call(self, x, mask=None):
if mask is None:
mask = K.sum(K.ones_like(x), axis=-1)
# if masked, set to large negative value so we ignore it
# when taking max of the sequence
# K.switch with tensorflow backend is less useful than Theano's
if K._BACKEND == "tensorflow":
mask = K.expand_dims(mask, axis=-1)
mask = K.tile(mask, (1, 1, K.int_shape(x)[2]))
masked_data = K.tf.where(
K.equal(mask, K.zeros_like(mask)), K.ones_like(x) * -np.inf, x
) # if masked assume value is -inf
return K.max(masked_data, axis=1)
else: # theano backend
mask = mask.dimshuffle(0, 1, "x")
masked_data = K.switch(K.eq(mask, 0), -np.inf, x)
return masked_data.max(axis=1)
def compute_mask(self, input, mask):
# do not pass the mask to the next layers
return None
def main():
ap = argparse.ArgumentParser()
ap.add_argument(
"-seq",
"--seq_length",
required=True,
type=int,
help="Number of frames to be taken into consideration",
)
ap.add_argument(
"-m",
"--model_name",
type=str,
help="Imagenet model to load",
default="xception",
)
ap.add_argument(
"-w",
"--load_weights_name",
# required=True,
type=str,
help="Model wieghts name"
)
ap.add_argument(
"-im_size",
"--image_size",
required=True,
type=int,
help="Batch size",
default=224,
)
args = ap.parse_args()
# MTCNN face extraction from frames
imageio.core.util._precision_warn = ignore_warnings
# Create face detector
mtcnn = MTCNN(
margin=40,
select_largest=False,
post_process=False,
device="cuda:0"
)
test_data = pd.read_csv('test_csv/test_vids_c23.csv')
videos = test_data["vids_list"]
true_labels = test_data["label"]
# Loading model for feature extraction
model = cnn_model(
model_name=args.model_name,
img_size=args.image_size,
weights=args.load_weights_name
)
shape = (args.seq_lengths, 512)
model_lstm = lstm_model(shape)
model_lstm.load_weights("trained_wts/ef0_lstm.hdf5")
print("Weights loaded...")
y_pred = []
counter = 0
for video in videos:
cap = cv2.VideoCapture(video)
batches = []
while cap.isOpened() and len(batches) < args.seq_length:
ret, frame = cap.read()
if not ret:
break
h, w, _ = frame.shape
if h >= 720 and w >= 1080:
frame = cv2.resize(
frame,
(640, 480),
interpolation=cv2.INTER_AREA
)
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frame = Image.fromarray(frame)
face = mtcnn(frame)
try:
face = face.permute(1, 2, 0).int().numpy()
batches.append(face)
except AttributeError:
print("Image Skipping")
batches = np.asarray(batches).astype('float32')
batches /= 255
feature_vec = model.predict(batches)
feature_vec = np.expand_dims(feature_vec, axis=0)
preds = model_lstm.predict(feature_vec)
y_pred += [preds[0].argmax(0)]
cap.release()
if counter % 10 == 0:
print(counter, "Done....")
counter += 1
print("Accuracy Score:", accuracy_score(true_labels, y_pred))
print("Precision Score", precision_score(true_labels, y_pred))
print("Recall Score:", recall_score(true_labels, y_pred))
print("F1 Score:", f1_score(true_labels, y_pred))
np.save("lstm_preds.npy", y_pred)
if __name__ == '__main__':
main()