-
Notifications
You must be signed in to change notification settings - Fork 2
/
real_and_fake_face_detection.py
381 lines (282 loc) · 10.5 KB
/
real_and_fake_face_detection.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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
import itertools
import os
import random
from keras.models import Sequential
import cv2
import keras
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from IPython.display import Image, display
from keras.layers import Activation
from keras.layers.convolutional import Conv2D
from keras.layers.core import Dense, Flatten
from keras.metrics import categorical_crossentropy
from keras.models import Sequential
from keras.preprocessing.image import ImageDataGenerator
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split
from tensorflow.keras.layers import (Activation, BatchNormalization, Conv2D,
Dense, Dropout, Flatten, MaxPooling2D,
SeparableConv2D)
from tensorflow.keras.models import Sequential
from tensorflow.keras.optimizers import Adam
from habana_frameworks.tensorflow import load_habana_module
tf.compact.v1.disable_eager_execution()
load_habana_module()
real = "Dataset/real_and_fake_face/training_fake"
fake = "Dataset/real_and_fake_face/training_fake"
datadir = "Dataset/real_and_fake_face"
real_path = os.listdir(real)
fake_path = os.listdir(fake)
def load_img(path):
image = cv2.imread(path)
image = cv2.resize(image, (224, 224))
return image[...,::-1]
categories = ["training_real" , "training_fake"]
for category in categories:
path = os.path.join(datadir, category)
for img in os.listdir(path):
img_array = cv2.imread(os.path.join(path,img), cv2.IMREAD_GRAYSCALE)
break
break
training_data = []
IMG_SIZE = 224
categories = ["training_real" , "training_fake"] # 0 -> Real and 1 -> Fake
def create_training_data():
for category in categories:
path = os.path.join(datadir, category)
class_num = categories.index(category)
for img in os.listdir(path):
try:
img_array = cv2.imread(os.path.join(path,img), cv2.IMREAD_UNCHANGED)
new_array = cv2.resize(img_array,(IMG_SIZE,IMG_SIZE))
training_data.append([new_array,class_num])
except: pass
create_training_data()
training_data = np.array(training_data)
np.random.shuffle(training_data)
for sample in training_data[:10]:
print(sample[1])
X = []
y = []
for features,label in training_data:
X.append(features)
y.append(label)
X = np.array(X).reshape(-1, IMG_SIZE, IMG_SIZE, 3)
y = np.array(y)
print(X.shape)
print(y.shape)
print(np.unique(y, return_counts = True))
print(y[1:10]) # Expected -> (array([0, 1]), array([1081, 960]))
# Normalization
X = X/255.0
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
print("Shape of test_x: ",X_train.shape)
print("Shape of train_y: ",y_train.shape)
print("Shape of test_x: ",X_test.shape)
print("Shape of test_y: ",y_test.shape)
print(y_test[1:10])
print(np.unique(y_train, return_counts = True))
print(np.unique(y_test, return_counts = True))
train_x = tf.keras.utils.normalize(X_train,axis=1)
test_x = tf.keras.utils.normalize(X_test, axis=1)
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(64,(3,3),activation = 'relu',
input_shape= X.shape[1:]),
tf.keras.layers.Conv2D(64,(3,3),activation = 'relu'),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Conv2D(64,(3,3),activation = 'relu'),
tf.keras.layers.Conv2D(64,(3,3),activation = 'relu'),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Dropout(0.25),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation=tf.nn.relu),
tf.keras.layers.Dense(2, activation=tf.nn.softmax)
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
hist = model.fit(X_train,y_train, batch_size=20, epochs = 5, validation_split=0.1)
epochs = 5
train_loss = hist.history['loss']
val_loss = hist.history['val_loss']
train_acc = hist.history['accuracy']
val_acc = hist.history['val_accuracy']
xc = range(epochs)
# plt.figure(1,figsize=(7,5))
# plt.plot(xc,train_loss)
# plt.plot(xc,val_loss)
# plt.xlabel('num of Epochs')
# plt.ylabel('loss')
# plt.title('train_loss vs val_loss')
# plt.grid(True)
# plt.legend(['train','val'])
# print plt.style.available # use bmh, classic,ggplot for big pictures
# plt.style.use(['classic'])
# plt.figure(2,figsize=(7,5))
# plt.plot(xc,train_acc)
# plt.plot(xc,val_acc)
# plt.xlabel('num of Epochs')
# plt.ylabel('accuracy')
# plt.title('train_acc vs val_acc')
# plt.grid(True)
# plt.legend(['train','val'],loc=4)
# print plt.style.available # use bmh, classic,ggplot for big pictures
# plt.style.use(['classic'])
# val_loss, val_acc = model.evaluate(X_test, y_test)
# print(val_loss)
# print(val_acc)
predictions = model.predict(X_test)
predictions
rounded_predictions=model.predict(x = X_test, batch_size=10, verbose=0)
classes_x=np.argmax(rounded_predictions,axis=1)
for i in rounded_predictions[:10]: print(i)
# %matplotlib inline
# cm = confusion_matrix(y_test,rounded_predictions)
def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print("Normalized confusion matrix")
else: print('Confusion matrix, without normalization')
print(cm)
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, cm[i, j],
horizontalalignment="center",
color="black" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
cm_plot_labels = ['Real', 'Fake']
plot_confusion_matrix(cm=cm, classes=cm_plot_labels, title='Confusion Matrix')
"""- This means our model predicted every single time and got the 54% accuracy.
## VGG 16
- Checkout [this](https://neurohive.io/en/popular-networks/vgg16/) article for better Explanation.
"""
# %matplotlib inline
## I don't know why but without running this cell the below code is showing errors.
## Running all these imports again solved it.
## Will figure out soon.
vgg16_model = keras.applications.vgg16.VGG16()
vgg16_model.summary()
print('VGG16 done')
"""- **predictions (Dense) (None, 1000) 4097000**
- Vgg-16 is trained for classification of 1000 different classes, but we do not need that.
- So we will remove that last layer and add one of our own.
"""
# type(vgg16_model)
## This is not a sequential model.
"""### Customizing our model"""
model = Sequential()
for layer in vgg16_model.layers[:-1]: model.add(layer)
# Now, we have replicated the entire vgg16_model
# (excluding the output layer) to a new Sequential model, which we've just given the name model
for layer in model.layers: layer.trainable = False
# Next, we’ll iterate over each of the layers in our new Sequential model and set them to
# be non-trainable. This freezes the weights and other trainable parameters
# in each layer so that they will not be updated when we pass in our images of fake and real faces.
model.add(Dense(2, activation='softmax'))
model.summary()
model.save('final_model')
print('Model saved')
"""**Model is Ready, time to Compile it**
"""
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
hist = model.fit(X_train,y_train, batch_size=20, epochs = 2, validation_split=0.1) # isme originally 50 epoch the
epochs = 2 # 50
train_loss = hist.history['loss']
val_loss = hist.history['val_loss']
train_acc = hist.history['accuracy']
val_acc = hist.history['val_accuracy']
xc = range(epochs)
plt.figure(1,figsize=(7,5))
plt.plot(xc,train_loss)
plt.plot(xc,val_loss)
plt.xlabel('num of Epochs')
plt.ylabel('loss')
plt.title('train_loss vs val_loss')
plt.grid(True)
plt.legend(['train','val'])
plt.style.use(['classic'])
plt.figure(2,figsize=(7,5))
plt.plot(xc,train_acc)
plt.plot(xc,val_acc)
plt.xlabel('num of Epochs')
plt.ylabel('accuracy')
plt.title('train_acc vs val_acc')
plt.grid(True)
plt.legend(['train','val'],loc=4)
#print plt.style.available # use bmh, classic,ggplot for big pictures
plt.style.use(['classic'])
val_loss, val_acc = model.evaluate(X_test, y_test)
print(val_loss)
print(val_acc)
predictions = model.predict(X_test)
rounded_predictions=model.predict(x = X_test, batch_size=10, verbose=0)
classes_x=np.argmax(rounded_predictions,axis=1)
for i in rounded_predictions[:10]: print(i)
print(y_test[1:10])
print(np.unique(y_test, return_counts = True))
rounded_prediction = np.array(rounded_prediction)
print(np.unique(rounded_prediction, return_counts = True))
"""### Performance Analysis:
- **Actual Test Data**: Real Faces[209], Fake Faces[200]
- **Predicted Data** : Real Faces[263], Fake Faces[146]
"""
cm = confusion_matrix(y_test,rounded_prediction)
cm_plot_labels = ['Real', 'Fake']
plot_confusion_matrix(cm=cm, classes=cm_plot_labels, title='Confusion Matrix')
"""## Explanation of Matrix:
**True Positive**
- Correct Real Faces Predictions: 157
**False Positive**
- Incorrect Real Faces Predictions: 106
**True Negative**
- Correct Fake Faces Predictions: 94
**False Negative**
- Incorrect Fake Faces Predictions: 52
## Predictions vs Actual.
"""
## For Image Display.
def load_img(path):
image = cv2.resize(path, (224, 224))
return image[...,::-1]
## For Predicting result.
def prepare(image):
IMG_SIZE = 224
new_array = cv2.resize(image, (IMG_SIZE, IMG_SIZE))
return new_array.reshape(-1, IMG_SIZE,IMG_SIZE,3)
print("It's over!")
"""## 0 is Real Face
## 1 is Fake Face
"""
from keras.models import load_model
model = load_model('/content/gdrive/MyDrive/complete_model.h5')
# Change the value of n for other images. I have chosen these images randomly.
# Test 1
n = 171
prediction = model.predict(prepare(X_test[n]))
print("Probabilities: ",prediction)
x = ["Real-Face" if y_test[n]== 0 else "Fake-Face"]
print("Actual: ",x[0])
rounded_prediction=model.predict(x = prepare(X_test[n]), batch_size=10, verbose=0)
classes_x=np.argmax(rounded_prediction,axis=1)
plt.imshow(load_img(X_test[n]), cmap='gray')
plt.show()
model.save('complete_model.h5')