-
Notifications
You must be signed in to change notification settings - Fork 6
/
utils.py
281 lines (241 loc) · 9.47 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
import numpy as np
import os
import cv2 as cv
# import tensorflow as tf
# tf.compat.v1.disable_eager_execution()
import tensorflow.keras as keras
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import BatchNormalization
from tensorflow.keras.layers import Conv2D
from tensorflow.keras.layers import MaxPooling2D
from tensorflow.keras.layers import Activation
from tensorflow.keras.layers import Dropout
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers import Flatten
from tensorflow.keras.layers import Input
from tensorflow.keras.models import Model
from tensorflow.keras.callbacks import ModelCheckpoint
from tensorflow.keras.models import load_model
from tensorflow.keras.metrics import AUC
import sklearn.metrics as metrics
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import Callback
# Given the paths to real and fake cropped signs (positivly detected by an object classifier), create a training set and test set.
# The data is split chronologically (by filename) to avoid having the same signs in the test set (since we extracted from videos).
# Return: the FILEPATHS to the npy images for the train and test set. We load the images later during training to reduce memory consumption.
def split_data(base_path_r,base_path_f,split=0.8):
X_r = []
files = os.listdir(base_path_r); files.sort()
X_r += [os.path.join(base_path_r,file) for file in files]
Y_r = np.zeros((len(X_r),2))
Y_r[:,0] = 1 # 0:real, 1:fake
X_f = []
files = os.listdir(base_path_f); files.sort()
X_f += [os.path.join(base_path_f,file) for file in files]
Y_f = np.zeros((len(X_f),2))
Y_f[:,1] = 1 # 0:real, 1:fake
# Real : train test
split_indx = int(len(X_r)*split)
Xtrain_r = X_r[:split_indx]
Ytrain_r = Y_r[:split_indx,:]
Xtest_r = X_r[split_indx:]
Ytest_r = Y_r[split_indx:,:]
# Fake : train test
split_indx = int(len(X_f)*split)
Xtrain_f = X_f[:split_indx]
Ytrain_f = Y_f[:split_indx,:]
Xtest_f = X_f[split_indx:]
Ytest_f = Y_f[split_indx:,:]
# Train test
Xtrain = np.array(Xtrain_r + Xtrain_f)
Ytrain = np.vstack((Ytrain_r,Ytrain_f))
Xtest = np.array(Xtest_r + Xtest_f)
Ytest = np.vstack((Ytest_r,Ytest_f))
return Xtrain,Ytrain,Xtest,Ytest
# Used by the Keras model to dynamically load the images during training and prepair their features
# if dynamic_loading, then images are loaded from disk during training to save memory
class DataLoader(keras.utils.Sequence):
def __init__(self, X, Y, batch_size=32, shuffle=True,dynamic_loading=False):
#'Initialization'
self.batch_size = batch_size
self.Y = Y
self.X = X
self.filenames = [x.split('/')[-1] for x in X] #take the filname, not the full path
self.shuffle = shuffle
self.dynamic_loading=dynamic_loading
if not self.dynamic_loading: #load all data to RAM
self.load_all()
self.on_epoch_end()
def __len__(self):
#'Denotes the number of batches per epoch'
return int(np.floor(len(self.X) / self.batch_size))
def load_all(self):
print('Loading files from disk:',self.X[0],'...')
Xd=[]
for x in self.X:
x_img=np.load(x)
Xd.append(x_img)
self.X = np.array(Xd)
def __getitem__(self, index):
#'Generate one batch of data'
# Generate indexes of the batch
indexes = self.indexes[index*self.batch_size:(index+1)*self.batch_size]
if not self.dynamic_loading:
return self.X[indexes,], self.Y[indexes,]
else:
Xd = []
for x in self.X[indexes]:
x_img=np.load(x)
Xd.append(x_img)
return np.array(Xd), self.Y[indexes,:]
def on_epoch_end(self):
#'Updates indexes after each epoch'
self.indexes = np.arange(len(self.X))
if self.shuffle == True:
np.random.shuffle(self.indexes)
# Used by the Keras Model to report for us the AUC at each epoch and save the best model to disk.
class auc_Callback(keras.callbacks.Callback):
def __init__(self,validation_generator,model_save_path,data=None,byTPRatFPR0=False):
self.validation_generator=validation_generator
self.max_v=-1
self.path = model_save_path
self.data = data
self.byTPRatFPR0 = byTPRatFPR0
def on_epoch_end(self, epoch, logs=None):
if self.validation_generator is not None:
Ytest=[]
Ypred=[]
for x,y in self.validation_generator:
Ytest.append(y)
Ypred.append(self.model.predict(x))
Ytest=np.vstack(Ytest)#.astype(int)
Ypred=np.vstack(Ypred)
else:
Ytest = self.data[1]
Ypred = self.model.predict(self.data[0])
fpr, tpr, threshold = metrics.roc_curve(Ytest[:,0], Ypred[:,0])
roc_auc = metrics.auc(fpr, tpr)
tpr_fpr0=tpr[np.where(fpr==0)[0][-1]]
print('')
print('AUC:',roc_auc,"TPR@FPR0:",tpr_fpr0)
if self.byTPRatFPR0:
v = tpr_fpr0
else:
v = roc_auc
if v > self.max_v:
self.max_v = v
self.model.save(self.path)
# Evalaute model with a given validation generator (made with train_expert) OR prediction and their groundtruth labels
def eval_model(model, validation_generator=None, predictions=None, labels=None):
from matplotlib import pyplot as plt
Ytest=[]
Ypred=[]
if validation_generator is not None:
for x,y in validation_generator:
Ytest.append(y)
Ypred.append(model.predict(x))
Ytest=np.vstack(Ytest)#.astype(int)
Ypred=np.vstack(Ypred)
elif predictions is not None:
Ytest=predictions
Ypred=labels
else:
raise Exception('you must provide a generator or the predicitons+labels')
# calculate the fpr and tpr for all thresholds of the classification
fpr, tpr, threshold = metrics.roc_curve(Ytest[:,0], Ypred[:,0])
roc_auc = metrics.auc(fpr, tpr)
# method I: plt
import matplotlib.pyplot as plt
plt.title('ROCR')
plt.plot(fpr, tpr, 'b', label = 'AUC = %0.2f' % roc_auc)
plt.legend(loc = 'lower right')
plt.plot([0, 1], [0, 1],'r--')
plt.xlim([0, 1])
plt.ylim([0, 1])
plt.ylabel('True Positive Rate')
plt.xlabel('False Positive Rate')
plt.show()
print("TPR at FPR=0:",tpr[np.where(fpr==0)[0][-1]],"with threshold:",threshold[np.where(fpr==0)[0][-1]])
thr=0.5
with_signs = Ypred[Ytest[:,1]==1,0]
acc_xr = np.sum(with_signs>thr)/len(with_signs) #errors on real signs
withf_signs = Ypred[Ytest[:,1]==0,0]
acc_wfs = np.sum(withf_signs>thr)/len(withf_signs) #succ detecting fake signs
print("errors on real signs:",acc_xr)
print("succ detecting fake signs:",acc_wfs)
from sklearn.metrics import classification_report, confusion_matrix
print('Confusion Matrix')
print(confusion_matrix(np.argmax(Ytest, axis=1), np.argmax(Ypred, axis=1)))
return Ytest, Ypred
# used to create experts in train_expert()
def create_cnn(width, height, depth, regress=False, filters=(16, 32, 64)):
# initialize the input shape and channel dimension, assuming
# TensorFlow/channels-last ordering
inputShape = (height, width, depth)
chanDim = -1
# define the model input
inputs = Input(shape=inputShape)
# loop over the number of filters
for (i, f) in enumerate(filters):
# if this is the first CONV layer then set the input
# appropriately
if i == 0:
x = inputs
# CONV => RELU => BN => POOL
x = Conv2D(f, (3, 3), padding="same")(x)
x = Activation("relu")(x)
x = BatchNormalization(axis=chanDim)(x)
x = MaxPooling2D(pool_size=(2, 2))(x)
# flatten the volume, then FC => RELU => BN => DROPOUT
x = Flatten()(x)
x = Dense(16)(x)
x = Activation("relu",name="embed")(x)
x = BatchNormalization(axis=chanDim)(x)
x = Dropout(0.5)(x)
# apply another FC layer, this one to match the number of nodes
# coming out of the MLP
x = Dense(4)(x)
x = Activation("relu")(x)
if regress:
x = Dense(1, activation="linear")(x)
else:
x = Dense(2, activation="softmax")(x)
# construct the CNN
model = Model(inputs, x)
# return the CNN
return model
# used to train the combined (meta) model
def create_dnn(input_dim):
# initialize the input shape and channel dimension, assuming
# TensorFlow/channels-last ordering
inputShape = (input_dim,)
# define the model input
inputs = Input(shape=inputShape)
# flatten the volume, then FC => RELU => BN => DROPOUT
x = Dense(32)(inputs)
x = Activation("relu")(x)
x = BatchNormalization(axis=-1)(x)
x = Dropout(0.5)(x)
x = Dense(16)(x)
x = Activation("relu")(x)
x = BatchNormalization(axis=-1)(x)
x = Dropout(0.5)(x)
# apply another FC layer, this one to match the number of nodes
# coming out of the MLP
x = Dense(4)(x)
x = Activation("relu")(x)
x = Dense(2, activation="softmax")(x)
# construct the CNN
model = Model(inputs, x)
# return the CNN
return model
def get_embeddings(model,generator):
if generator.dynamic_loading:
Y=[]
emeddings=[]
for x,y in generator:
Y.append(y)
emeddings.append(model.predict(x))
return np.vstack(emeddings), np.vstack(Y)
else:
return model.predict(generator.X), np.array(generator.Y)