Vision Transformer for DeepFake images of Faces¶
Vision Transformers are a more recent approach for detecting image forgery and DeepFakes with quite promising results. In the following you can see the implementation of a Vision Transformer Model that is trained on the classification of real and generated faces. The model could be used for analyzing DeepFake videos with a frame-by-frame approach, however since this would require a lot more time and computational power, I decided to keep it simple with images so that you can run it in a reasonable amount of time.
(Running the notebook with default parameters and the GPU of Google Colab should take less than 1h)
Outline
- Imports and Requirements
- Download the Dataset
- Preprocessing of the Dataset
- Create the Model
- Training the model
- Visualizing results
Resources:
- Paper on Vision Transformers for DeepFake Detection: Combining EfficientNet and Vision Transformers for Video DeepFake Detection
- Dataset on Kaggle: 140k real and fake faces
- Implementation and Paper on Github DeepFake Recognition
Imports and Prerequisits¶
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.utils import plot_model
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image, ImageChops, ImageEnhance
import os
import random
%matplotlib inline
import cv2
from tqdm import tqdm
import pandas as pd
Below is the cell that defines the hyperparameters. You might need to adjust the root_directory if you run it locally instead of Colab. You can also adjust the NUM_IMAGES and num_epochs depending on how much you want to train the model. If your running out of memory, then consider lowering the batch_size or the image_size. There is no need to change other parameters but if you want to change the model architecture then feel free to play around with them as well. However, keep in mind that this might mean that you may have to make some adjustments in some other cells as well.
root_directory = '/content/140k_dataset/' # specify where you downloaded and unpacked the zip file
NUM_IMAGES = 20000 # max 140k
num_epochs = 50
batch_size = 256
image_size = 72 # image is resized to this size
labels = ('real', 'fake')
learning_rate = 0.001
weight_decay = 0.0001
num_classes = 2
patch_size = 6 # Size of the patches to be extract from the input images
num_patches = (image_size // patch_size) ** 2
projection_dim = 64
num_heads = 4
transformer_units = [
projection_dim * 2,
projection_dim,
] # Size of the transformer layers
transformer_layers = 8
mlp_head_units = [2048, 1024] # Size of the dense layers of the final classifier
Preprocessing¶
Get the Data¶
Run the cell below to download the data set. The data is originally from Kaggle but since there is an account required to download the data set from there, I have uploaded the data to my own cloud so that it can be downloaded without authentication. Alternatively, you can also download the file form Kaggle using this link.
Using Jupyter Notebook:
If you are not using Colab than use this link or the Kaggle link to download the file and then unzip it. Make sure that everything is in the right directory. Once this is done, continue with "Inspect the Data".
!wget data.zip "https://filedn.com/lppbPiDsptDyWVYHwlYrvdb/140k_dataset.zip"
--2023-07-03 17:51:27-- http://data.zip/ Resolving data.zip (data.zip)... failed: No address associated with hostname. wget: unable to resolve host address ‘data.zip’ --2023-07-03 17:51:27-- https://filedn.com/lppbPiDsptDyWVYHwlYrvdb/140k_dataset.zip Resolving filedn.com (filedn.com)... 74.120.9.25 Connecting to filedn.com (filedn.com)|74.120.9.25|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 4094680370 (3.8G) [application/zip] Saving to: ‘140k_dataset.zip’ 140k_dataset.zip 5%[> ] 226.50M 56.4MB/s eta 1m 52s ^C
!unzip \140k_dataset.zip && rm 140k_dataset.zip
Inspect the Data¶
The cell below displays 5 random fake images and 5 random real images form the dataset to help getting an idea of what's in the dataset and how good the quality is.
# (Test) if the images are displayed then everything seems to have worked correctly so far
from google.colab.patches import cv2_imshow
imgs = os.listdir(root_directory + 'real_vs_fake/real-vs-fake/train/fake/')
random_images = [imgs[np.random.choice(range(len(imgs)))] for x in range(5)]
images_fake = [cv2.imread(root_directory + 'real_vs_fake/real-vs-fake/train/fake/' + img) for img in random_images]
images_fake = [cv2.cvtColor(img, cv2.COLOR_BGR2RGB) for img in images_fake]
fig = plt.figure(figsize=(12, 6))
fig.suptitle("Random Images from dataset")
# Create subplots for the upper row
for i in range(5):
ax = fig.add_subplot(2, 5, i+1)
ax.set_title('fake')
ax.imshow(images_fake[i], )
ax.axis('off')
imgs = os.listdir(root_directory + 'real_vs_fake/real-vs-fake/train/real/')
random_images = [imgs[np.random.choice(range(len(imgs)))] for x in range(5)]
images_real = [cv2.imread(root_directory + 'real_vs_fake/real-vs-fake/train/real/' + img) for img in random_images]
images_real = [cv2.cvtColor(img, cv2.COLOR_BGR2RGB) for img in images_real]
# Create subplots for the lower row
for i in range(5):
ax = fig.add_subplot(2, 5, i+6)
ax.set_title('real')
ax.imshow(images_real[i])
ax.axis('off')
plt.subplots_adjust(wspace=0.05, hspace=0.3)
plt.show()
Preprocessing¶
First of all the images need to be preprocessed. This is done by the function in the cell below. The most important steps of preprocessing are:
- getting the images from the folders
- resize them to the configured
image_size - apply Error Level Analysis (ELA)
image_size = 72
input_shape = (72,72,3)
def get_data(data_dir, max_length):
'''
This function gets the training directory and processes the max_length images form the fake and real category.
It reads the image, transforms it to a numpy array and applys ELA.
returns: images with labels as numpy array
'''
temp_filename = '/content/sample_data/temp_file_name.jpg'
ela_filename = '/content/sample_data/temp_ela.png'
data = []
for label in labels:
path = os.path.join(data_dir, label)
class_num = labels.index(label)
for img, x in zip(os.listdir(path), tqdm(range(max_length), desc = f"Loading {label} Data")):
try:
img_arr = cv2.imread(os.path.join(path, img))[..., ::-1]
resized_arr = cv2.resize(img_arr, (image_size, image_size))
image = Image.fromarray(resized_arr)
image = image.convert("RGB")
image.save(temp_filename,'JPEG', quality = 95)
temporary_image = Image.open(temp_filename)
#ELA on images
ela_image = ImageChops.difference(image, temporary_image)
extrema = ela_image.getextrema()
max_diff = max([ex[1] for ex in extrema])
if max_diff == 0:
max_diff = 1
scale = 255.0 / max_diff
ela_image = ImageEnhance.Brightness(ela_image).enhance(scale)
ela_image.save(ela_filename, 'JPEG', quality=95)
imageToDisplay = cv2.imread(ela_filename)
resized_arr = cv2.resize(imageToDisplay,(image_size,image_size))
data.append([resized_arr, class_num])
except Exception as e:
print(e)
return np.array(data, dtype='object')
train = get_data(root_directory + "real_vs_fake/real-vs-fake/train/", int(NUM_IMAGES * 0.4))
test = get_data(root_directory + "real_vs_fake/real-vs-fake/test/", int(NUM_IMAGES * 0.1))
print("\n reading done")
Loading real Data: 100%|██████████| 8000/8000 [00:43<00:00, 185.54it/s] Loading fake Data: 100%|██████████| 8000/8000 [00:44<00:00, 180.41it/s] Loading real Data: 100%|██████████| 2000/2000 [00:08<00:00, 234.07it/s] Loading fake Data: 100%|██████████| 2000/2000 [00:07<00:00, 261.02it/s]
reading done
Visualization after preprocessing¶
Below is a visualiztion of two images after the preprocessing to see what's going on.
# randomly visualizing images to see whats going on
plt.figure(figsize=(8, 6))
plt.imshow(train[1][0])
plt.title(labels[train[0][1]])
plt.show()
plt.figure(figsize=(10, 6))
plt.imshow(train[-1][0])
plt.title(labels[train[-1][1]])
plt.show()
Create Datasets¶
Now the preprocessed data is transformed into numpy arrays and then tensorflow datasets. One dataset is for the training and the other one for testing/validation.
X_train = []
X_test = []
y_train = []
y_test = []
for feature, label in train:
X_train.append(feature)
y_train.append(label)
for feature, label in test:
X_test.append(feature)
y_test.append(label)
X_train = np.array(X_train)
y_train = np.array(y_train)
X_test = np.array(X_test)
y_test = np.array(y_test)
print(X_train.shape)
print(X_test.shape)
(16000, 72, 72, 3) (4000, 72, 72, 3)
tf.random.set_seed(42)
train_dataset = tf.data.Dataset.from_tensor_slices((X_train, y_train))
train_dataset = train_dataset.shuffle(int(NUM_IMAGES *0.8)).batch(batch_size).prefetch(tf.data.AUTOTUNE)
test_dataset = tf.data.Dataset.from_tensor_slices((X_test, y_test))
test_dataset = test_dataset.shuffle(int(NUM_IMAGES * 0.2)).batch(batch_size).prefetch(tf.data.AUTOTUNE)
The Model¶
The cells below initialize functions and layers needed for the model.
# layer for data augmentation
data_augmentation = keras.Sequential(
[
layers.Normalization(),
layers.Resizing(image_size, image_size),
layers.RandomFlip("horizontal"),
layers.RandomRotation(factor=0.02),
layers.RandomZoom(
height_factor=0.2, width_factor=0.2
),
],
name="data_augmentation",
)
# Compute the mean and the variance of the training data for normalization.
data_augmentation.layers[0].adapt(X_train)
def mlp(x, hidden_units, dropout_rate):
for units in hidden_units:
x = layers.Dense(units, activation=tf.nn.gelu)(x)
x = layers.Dropout(dropout_rate)(x)
return x
class Patches(layers.Layer):
def __init__(self, patch_size):
super(Patches, self).__init__()
self.patch_size = patch_size
def call(self, images):
batch_size = tf.shape(images)[0]
patches = tf.image.extract_patches(
images=images,
sizes=[1, self.patch_size, self.patch_size, 1],
strides=[1, self.patch_size, self.patch_size, 1],
rates=[1, 1, 1, 1],
padding="VALID",
)
patch_dims = patches.shape[-1]
patches = tf.reshape(patches, [batch_size, -1, patch_dims])
return patches
Visualization of the Patches¶
The cell below shows a visualization of the Patches when applied to a single random image from the dataset. For better visualization there is a random image from the dataset before preprocessing.
imgs = os.listdir(root_directory + 'real_vs_fake/real-vs-fake/train/fake/')
random_image = imgs[np.random.choice(range(len(imgs)))]
img_arr = cv2.imread(root_directory + 'real_vs_fake/real-vs-fake/train/fake/' + random_image)
img_arr = cv2.cvtColor(img_arr, cv2.COLOR_BGR2RGB)
resized_arr = cv2.resize(img_arr, (image_size, image_size))
plt.figure(figsize=(4, 4))
image = resized_arr
plt.imshow(image.astype("uint8"))
plt.axis("off")
resized_image = tf.image.resize(
tf.convert_to_tensor([image]), size=(image_size, image_size)
)
patches = Patches(patch_size)(resized_image)
print(f"Image size: {image_size} X {image_size}")
print(f"Patch size: {patch_size} X {patch_size}")
print(f"Patches per image: {patches.shape[1]}")
print(f"Elements per patch: {patches.shape[-1]}")
n = int(np.sqrt(patches.shape[1]))
plt.figure(figsize=(4, 4))
for i, patch in enumerate(patches[0]):
ax = plt.subplot(n, n, i + 1)
patch_img = tf.reshape(patch, (patch_size, patch_size, 3))
plt.imshow(patch_img.numpy().astype("uint8"))
plt.axis("off")
Image size: 72 X 72 Patch size: 6 X 6 Patches per image: 144 Elements per patch: 108
class PatchEncoder(layers.Layer):
def __init__(self, num_patches, projection_dim):
super(PatchEncoder, self).__init__()
self.num_patches = num_patches
self.projection = layers.Dense(units=projection_dim)
self.position_embedding = layers.Embedding(
input_dim=num_patches, output_dim=projection_dim
)
def call(self, patch):
positions = tf.range(start=0, limit=self.num_patches, delta=1)
encoded = self.projection(patch) + self.position_embedding(positions)
return encoded
def create_vit_classifier():
'''
builds the model by connecting all the layers
return: tensorflow model
'''
inputs = layers.Input(shape=input_shape)
# Data Augmentation
augmented = data_augmentation(inputs)
# Create patches
patches = Patches(patch_size)(augmented)
# Encode patches
encoded_patches = PatchEncoder(num_patches, projection_dim)(patches)
# Transformer block with multiple layers
for _ in range(transformer_layers):
# Layer normalization 1
x1 = layers.LayerNormalization(epsilon=1e-6)(encoded_patches)
# Create a multi-head attention layer
attention_output = layers.MultiHeadAttention(
num_heads=num_heads, key_dim=projection_dim, dropout=0.1
)(x1, x1)
# Skip connection 1
x2 = layers.Add()([attention_output, encoded_patches])
# Layer normalization 2
x3 = layers.LayerNormalization(epsilon=1e-6)(x2)
# MLP
x3 = mlp(x3, hidden_units=transformer_units, dropout_rate=0.1)
# Skip connection 2
encoded_patches = layers.Add()([x3, x2])
# Create a [batch_size, projection_dim] tensor
representation = layers.LayerNormalization(epsilon=1e-6)(encoded_patches)
representation = layers.Flatten()(representation)
representation = layers.Dropout(0.5)(representation)
# Add MLP
features = mlp(representation, hidden_units=mlp_head_units, dropout_rate=0.5)
# Classify outputs
logits = layers.Dense(num_classes)(features)
# Create the Keras model
model = keras.Model(inputs=inputs, outputs=logits)
return model
Training¶
def run_experiment(model):
optimizer = tf.optimizers.Adam(
learning_rate=learning_rate, weight_decay=weight_decay
)
model.compile(
optimizer=optimizer,
loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=[
keras.metrics.SparseCategoricalAccuracy(name="accuracy"),
],
)
checkpoint_filepath = "/tmp/checkpoint"
checkpoint_callback = keras.callbacks.ModelCheckpoint(
checkpoint_filepath,
monitor="val_accuracy",
save_best_only=True,
save_weights_only=True,
)
# traning the model and saving the best performing one
history = model.fit(
train_dataset,
epochs=num_epochs,
validation_data = test_dataset,
callbacks=[checkpoint_callback],
)
model.load_weights(checkpoint_filepath)
_, accuracy = model.evaluate(test_dataset)
print(f"Test accuracy: {round(accuracy * 100, 2)}%")
return history
vit_classifier = create_vit_classifier()
# visulization of the model architecture
plot_model(model=vit_classifier, show_shapes=False)
history = run_experiment(vit_classifier)
Epoch 1/50 63/63 [==============================] - 67s 487ms/step - loss: 1.1651 - accuracy: 0.5440 - val_loss: 0.6723 - val_accuracy: 0.5820 Epoch 2/50 63/63 [==============================] - 25s 398ms/step - loss: 0.6737 - accuracy: 0.5837 - val_loss: 0.6674 - val_accuracy: 0.6010 Epoch 3/50 63/63 [==============================] - 26s 414ms/step - loss: 0.6606 - accuracy: 0.6069 - val_loss: 0.6473 - val_accuracy: 0.6180 Epoch 4/50 63/63 [==============================] - 24s 388ms/step - loss: 0.6524 - accuracy: 0.6223 - val_loss: 0.6477 - val_accuracy: 0.6148 Epoch 5/50 63/63 [==============================] - 65s 1s/step - loss: 0.6436 - accuracy: 0.6313 - val_loss: 0.6257 - val_accuracy: 0.6480 Epoch 6/50 63/63 [==============================] - 30s 472ms/step - loss: 0.6348 - accuracy: 0.6434 - val_loss: 0.6266 - val_accuracy: 0.6497 Epoch 7/50 63/63 [==============================] - 25s 390ms/step - loss: 0.6306 - accuracy: 0.6481 - val_loss: 0.6227 - val_accuracy: 0.6442 Epoch 8/50 63/63 [==============================] - 31s 488ms/step - loss: 0.6172 - accuracy: 0.6576 - val_loss: 0.6100 - val_accuracy: 0.6687 Epoch 9/50 63/63 [==============================] - 24s 384ms/step - loss: 0.6150 - accuracy: 0.6663 - val_loss: 0.6064 - val_accuracy: 0.6615 Epoch 10/50 63/63 [==============================] - 32s 505ms/step - loss: 0.6097 - accuracy: 0.6687 - val_loss: 0.5942 - val_accuracy: 0.6837 Epoch 11/50 63/63 [==============================] - 26s 407ms/step - loss: 0.6013 - accuracy: 0.6835 - val_loss: 0.5952 - val_accuracy: 0.6873 Epoch 12/50 63/63 [==============================] - 24s 387ms/step - loss: 0.5975 - accuracy: 0.6774 - val_loss: 0.5911 - val_accuracy: 0.6787 Epoch 13/50 63/63 [==============================] - 27s 435ms/step - loss: 0.5883 - accuracy: 0.6897 - val_loss: 0.5889 - val_accuracy: 0.6898 Epoch 14/50 63/63 [==============================] - 24s 386ms/step - loss: 0.5932 - accuracy: 0.6866 - val_loss: 0.5948 - val_accuracy: 0.6725 Epoch 15/50 63/63 [==============================] - 31s 490ms/step - loss: 0.5781 - accuracy: 0.6921 - val_loss: 0.5912 - val_accuracy: 0.7003 Epoch 16/50 63/63 [==============================] - 24s 385ms/step - loss: 0.5779 - accuracy: 0.6998 - val_loss: 0.5791 - val_accuracy: 0.6992 Epoch 17/50 63/63 [==============================] - 27s 435ms/step - loss: 0.5798 - accuracy: 0.6991 - val_loss: 0.5645 - val_accuracy: 0.7067 Epoch 18/50 63/63 [==============================] - 24s 385ms/step - loss: 0.5727 - accuracy: 0.7057 - val_loss: 0.5728 - val_accuracy: 0.7023 Epoch 19/50 63/63 [==============================] - 25s 390ms/step - loss: 0.5746 - accuracy: 0.7013 - val_loss: 0.5630 - val_accuracy: 0.7050 Epoch 20/50 63/63 [==============================] - 31s 489ms/step - loss: 0.5625 - accuracy: 0.7117 - val_loss: 0.5528 - val_accuracy: 0.7185 Epoch 21/50 63/63 [==============================] - 25s 394ms/step - loss: 0.5600 - accuracy: 0.7134 - val_loss: 0.5594 - val_accuracy: 0.7128 Epoch 22/50 63/63 [==============================] - 31s 490ms/step - loss: 0.5583 - accuracy: 0.7108 - val_loss: 0.5524 - val_accuracy: 0.7230 Epoch 23/50 63/63 [==============================] - 24s 387ms/step - loss: 0.5504 - accuracy: 0.7247 - val_loss: 0.5557 - val_accuracy: 0.7218 Epoch 24/50 63/63 [==============================] - 31s 499ms/step - loss: 0.5488 - accuracy: 0.7241 - val_loss: 0.5420 - val_accuracy: 0.7290 Epoch 25/50 63/63 [==============================] - 25s 394ms/step - loss: 0.5483 - accuracy: 0.7200 - val_loss: 0.5401 - val_accuracy: 0.7280 Epoch 26/50 63/63 [==============================] - 24s 387ms/step - loss: 0.5420 - accuracy: 0.7282 - val_loss: 0.5593 - val_accuracy: 0.7205 Epoch 27/50 63/63 [==============================] - 25s 400ms/step - loss: 0.5415 - accuracy: 0.7286 - val_loss: 0.5493 - val_accuracy: 0.7245 Epoch 28/50 63/63 [==============================] - 31s 499ms/step - loss: 0.5355 - accuracy: 0.7316 - val_loss: 0.5480 - val_accuracy: 0.7365 Epoch 29/50 63/63 [==============================] - 24s 385ms/step - loss: 0.5362 - accuracy: 0.7329 - val_loss: 0.5465 - val_accuracy: 0.7178 Epoch 30/50 63/63 [==============================] - 24s 389ms/step - loss: 0.5330 - accuracy: 0.7399 - val_loss: 0.5414 - val_accuracy: 0.7237 Epoch 31/50 63/63 [==============================] - 24s 385ms/step - loss: 0.5217 - accuracy: 0.7414 - val_loss: 0.5557 - val_accuracy: 0.7200 Epoch 32/50 63/63 [==============================] - 25s 394ms/step - loss: 0.5184 - accuracy: 0.7448 - val_loss: 0.5345 - val_accuracy: 0.7355 Epoch 33/50 63/63 [==============================] - 31s 490ms/step - loss: 0.5180 - accuracy: 0.7424 - val_loss: 0.5379 - val_accuracy: 0.7400 Epoch 34/50 63/63 [==============================] - 25s 389ms/step - loss: 0.5189 - accuracy: 0.7461 - val_loss: 0.5339 - val_accuracy: 0.7358 Epoch 35/50 63/63 [==============================] - 24s 386ms/step - loss: 0.5263 - accuracy: 0.7377 - val_loss: 0.5331 - val_accuracy: 0.7318 Epoch 36/50 63/63 [==============================] - 24s 385ms/step - loss: 0.5105 - accuracy: 0.7513 - val_loss: 0.5401 - val_accuracy: 0.7358 Epoch 37/50 63/63 [==============================] - 25s 396ms/step - loss: 0.5128 - accuracy: 0.7459 - val_loss: 0.5300 - val_accuracy: 0.7362 Epoch 38/50 63/63 [==============================] - 25s 395ms/step - loss: 0.5031 - accuracy: 0.7539 - val_loss: 0.5553 - val_accuracy: 0.7190 Epoch 39/50 63/63 [==============================] - 24s 387ms/step - loss: 0.4996 - accuracy: 0.7555 - val_loss: 0.5492 - val_accuracy: 0.7145 Epoch 40/50 63/63 [==============================] - 25s 400ms/step - loss: 0.5019 - accuracy: 0.7543 - val_loss: 0.5376 - val_accuracy: 0.7350 Epoch 41/50 63/63 [==============================] - 24s 384ms/step - loss: 0.5047 - accuracy: 0.7498 - val_loss: 0.5436 - val_accuracy: 0.7243 Epoch 42/50 63/63 [==============================] - 31s 496ms/step - loss: 0.4965 - accuracy: 0.7572 - val_loss: 0.5234 - val_accuracy: 0.7437 Epoch 43/50 63/63 [==============================] - 24s 384ms/step - loss: 0.4986 - accuracy: 0.7589 - val_loss: 0.5685 - val_accuracy: 0.7088 Epoch 44/50 63/63 [==============================] - 24s 386ms/step - loss: 0.4936 - accuracy: 0.7639 - val_loss: 0.5363 - val_accuracy: 0.7398 Epoch 45/50 63/63 [==============================] - 24s 387ms/step - loss: 0.4904 - accuracy: 0.7626 - val_loss: 0.5315 - val_accuracy: 0.7387 Epoch 46/50 63/63 [==============================] - 24s 386ms/step - loss: 0.4848 - accuracy: 0.7670 - val_loss: 0.5319 - val_accuracy: 0.7358 Epoch 47/50 63/63 [==============================] - 24s 385ms/step - loss: 0.4900 - accuracy: 0.7656 - val_loss: 0.5284 - val_accuracy: 0.7405 Epoch 48/50 63/63 [==============================] - 24s 385ms/step - loss: 0.4741 - accuracy: 0.7686 - val_loss: 0.5286 - val_accuracy: 0.7420 Epoch 49/50 63/63 [==============================] - 31s 492ms/step - loss: 0.4763 - accuracy: 0.7768 - val_loss: 0.5241 - val_accuracy: 0.7448 Epoch 50/50 63/63 [==============================] - 24s 386ms/step - loss: 0.4733 - accuracy: 0.7744 - val_loss: 0.5270 - val_accuracy: 0.7365 16/16 [==============================] - 2s 125ms/step - loss: 0.5241 - accuracy: 0.7448 Test accuracy: 74.48%
Visualization of the final results¶
from sklearn.metrics import classification_report
from sklearn import metrics
predictions = np.argmax(vit_classifier.predict(X_test), axis=-1)
# Regain the original shape to evaluate predictions
predictions = predictions.reshape(1, -1)[0]
print(classification_report(y_test, predictions, target_names=['Real(class 0)', 'Fake(class 1)']))
print("Accuracy: ", metrics.accuracy_score(y_test, predictions) * 100)
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs_range = range(num_epochs)
plt.figure(figsize=(15, 15))
plt.subplot(2, 2, 1)
plt.plot(epochs_range, acc, label='Training Accuracy')
plt.plot(epochs_range, val_acc, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')
plt.subplot(2, 2, 2)
plt.plot(epochs_range, loss, label='Training Loss')
plt.plot(epochs_range, val_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()
125/125 [==============================] - 3s 15ms/step
precision recall f1-score support
Real(class 0) 0.74 0.76 0.75 2000
Fake(class 1) 0.75 0.73 0.74 2000
accuracy 0.74 4000
macro avg 0.74 0.74 0.74 4000
weighted avg 0.74 0.74 0.74 4000
Accuracy: 74.47500000000001