{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":16880,"databundleVersionId":858837,"sourceType":"competition"},{"sourceId":924245,"sourceType":"datasetVersion","datasetId":464091}],"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Deep Fake Detection using CNN and RNN","metadata":{"id":"Q6tasuafvT2O"}},{"cell_type":"markdown","source":"# Contriubuters - ","metadata":{}},{"cell_type":"markdown","source":"## 1. Rohan Inamdar\n## 2. Kavin Sundarr","metadata":{}},{"cell_type":"markdown","source":"## Importing Required libraries","metadata":{"id":"dFXIv9qNpKzt","tags":[]}},{"cell_type":"code","source":"!pip install -U --upgrade tensorflow","metadata":{"execution":{"iopub.status.busy":"2024-04-15T06:21:10.935140Z","iopub.execute_input":"2024-04-15T06:21:10.935440Z","iopub.status.idle":"2024-04-15T06:22:40.740304Z","shell.execute_reply.started":"2024-04-15T06:21:10.935413Z","shell.execute_reply":"2024-04-15T06:22:40.739171Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import sys\nimport sklearn\nimport tensorflow as tf\n\nimport cv2\nimport pandas as pd\nimport numpy as np\n\nimport plotly.graph_objs as go\nfrom plotly.offline import iplot\nfrom matplotlib import pyplot as plt","metadata":{"id":"TFSU3FCOpKzu","execution":{"iopub.status.busy":"2024-04-15T06:23:10.322160Z","iopub.execute_input":"2024-04-15T06:23:10.322622Z","iopub.status.idle":"2024-04-15T06:23:21.362628Z","shell.execute_reply.started":"2024-04-15T06:23:10.322579Z","shell.execute_reply":"2024-04-15T06:23:21.361826Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tf.test.is_gpu_available()","metadata":{"execution":{"iopub.status.busy":"2024-04-15T06:23:26.534401Z","iopub.execute_input":"2024-04-15T06:23:26.535322Z","iopub.status.idle":"2024-04-15T06:23:27.232939Z","shell.execute_reply.started":"2024-04-15T06:23:26.535288Z","shell.execute_reply":"2024-04-15T06:23:27.232013Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\nplt.rc('font', size=14)\nplt.rc('axes', labelsize=14, titlesize=14)\nplt.rc('legend', fontsize=14)\nplt.rc('xtick', labelsize=10)\nplt.rc('ytick', labelsize=10)","metadata":{"id":"8d4TH3NbpKzx","execution":{"iopub.status.busy":"2024-04-15T06:23:36.198052Z","iopub.execute_input":"2024-04-15T06:23:36.198786Z","iopub.status.idle":"2024-04-15T06:23:36.204339Z","shell.execute_reply.started":"2024-04-15T06:23:36.198749Z","shell.execute_reply":"2024-04-15T06:23:36.203408Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Data Visualisation","metadata":{"id":"NL3Ht4wC9b3n"}},{"cell_type":"code","source":"import os\n\ndef get_data():\n    return pd.read_csv('../input/deepfake-faces/metadata.csv')","metadata":{"id":"jfv9PxSB4tM8","execution":{"iopub.status.busy":"2024-04-15T06:23:40.641081Z","iopub.execute_input":"2024-04-15T06:23:40.641700Z","iopub.status.idle":"2024-04-15T06:23:40.645885Z","shell.execute_reply.started":"2024-04-15T06:23:40.641670Z","shell.execute_reply":"2024-04-15T06:23:40.645049Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"meta=get_data()\nmeta.head()","metadata":{"id":"tDW7BRph9ehF","outputId":"97de18b5-0a37-4302-8804-8a16a7d2ed2f","execution":{"iopub.status.busy":"2024-04-15T06:23:44.649684Z","iopub.execute_input":"2024-04-15T06:23:44.650031Z","iopub.status.idle":"2024-04-15T06:23:44.901349Z","shell.execute_reply.started":"2024-04-15T06:23:44.650003Z","shell.execute_reply":"2024-04-15T06:23:44.900128Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"meta.shape","metadata":{"id":"n7FSdDifbZxn","outputId":"5451a127-405a-4c0b-a197-c920b796adbb","execution":{"iopub.status.busy":"2024-04-15T06:23:47.923879Z","iopub.execute_input":"2024-04-15T06:23:47.924693Z","iopub.status.idle":"2024-04-15T06:23:47.930143Z","shell.execute_reply.started":"2024-04-15T06:23:47.924659Z","shell.execute_reply":"2024-04-15T06:23:47.929225Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"len(meta[meta.label=='FAKE']),len(meta[meta.label=='REAL'])","metadata":{"id":"_FJcz2IthxVG","outputId":"274c3f65-7acb-4f99-8aa9-a5b2a23bf06a","execution":{"iopub.status.busy":"2024-04-15T06:23:50.560909Z","iopub.execute_input":"2024-04-15T06:23:50.561583Z","iopub.status.idle":"2024-04-15T06:23:50.615221Z","shell.execute_reply.started":"2024-04-15T06:23:50.561550Z","shell.execute_reply":"2024-04-15T06:23:50.614205Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"real_df = meta[meta[\"label\"] == \"REAL\"]\nfake_df = meta[meta[\"label\"] == \"FAKE\"]\nsample_size = 8000\n\nreal_df = real_df.sample(sample_size, random_state=42)\nfake_df = fake_df.sample(sample_size, random_state=42)\n\nsample_meta = pd.concat([real_df, fake_df])","metadata":{"id":"IgMfzY-PjjtH","execution":{"iopub.status.busy":"2024-04-15T06:23:53.213370Z","iopub.execute_input":"2024-04-15T06:23:53.214224Z","iopub.status.idle":"2024-04-15T06:23:53.272633Z","shell.execute_reply.started":"2024-04-15T06:23:53.214181Z","shell.execute_reply":"2024-04-15T06:23:53.271686Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"As mentioned instead of using 95k images we will only use 16000 images.","metadata":{}},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n\nTrain_set, Test_set = train_test_split(sample_meta,test_size=0.2,random_state=42,stratify=sample_meta['label'])\nTrain_set, Val_set  = train_test_split(Train_set,test_size=0.3,random_state=42,stratify=Train_set['label'])","metadata":{"id":"5eB86S6K-T5Z","execution":{"iopub.status.busy":"2024-04-15T06:24:14.628567Z","iopub.execute_input":"2024-04-15T06:24:14.629187Z","iopub.status.idle":"2024-04-15T06:24:14.882422Z","shell.execute_reply.started":"2024-04-15T06:24:14.629131Z","shell.execute_reply":"2024-04-15T06:24:14.881616Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Train_set.shape,Val_set.shape,Test_set.shape","metadata":{"id":"8p-TONijb4qA","outputId":"56d0b529-9d81-4019-d8fa-618c8cdba90f","execution":{"iopub.status.busy":"2024-04-15T06:24:19.131783Z","iopub.execute_input":"2024-04-15T06:24:19.132146Z","iopub.status.idle":"2024-04-15T06:24:19.138695Z","shell.execute_reply.started":"2024-04-15T06:24:19.132101Z","shell.execute_reply":"2024-04-15T06:24:19.137810Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y = dict()\n\ny[0] = []\ny[1] = []\n\nfor set_name in (np.array(Train_set['label']), np.array(Val_set['label']), np.array(Test_set['label'])):\n    y[0].append(np.sum(set_name == 'REAL'))\n    y[1].append(np.sum(set_name == 'FAKE'))\n\ntrace0 = go.Bar(\n    x=['Train Set', 'Validation Set', 'Test Set'],\n    y=y[0],\n    name='REAL',\n    marker=dict(color='#33cc33'),\n    opacity=0.7\n)\ntrace1 = go.Bar(\n    x=['Train Set', 'Validation Set', 'Test Set'],\n    y=y[1],\n    name='FAKE',\n    marker=dict(color='#ff3300'),\n    opacity=0.7\n)\n\ndata = [trace0, trace1]\nlayout = go.Layout(\n    title='Count of classes in each set',\n    xaxis={'title': 'Set'},\n    yaxis={'title': 'Count'}\n)\n\nfig = go.Figure(data, layout)\niplot(fig)","metadata":{"id":"hzNGtCWd-mTk","outputId":"5178c3ed-cbba-4f99-99d0-26bde11a5dab","execution":{"iopub.status.busy":"2024-04-15T06:24:28.950250Z","iopub.execute_input":"2024-04-15T06:24:28.950593Z","iopub.status.idle":"2024-04-15T06:24:31.187029Z","shell.execute_reply.started":"2024-04-15T06:24:28.950568Z","shell.execute_reply":"2024-04-15T06:24:31.186110Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"The original image dataset were biased with more fake images than real since we are taking a sample of it its better to take equal proportion of real and fake images.","metadata":{}},{"cell_type":"code","source":"plt.figure(figsize=(15,15))\nfor cur,i in enumerate(Train_set.index[25:50]):\n    plt.subplot(5,5,cur+1)\n    plt.xticks([])\n    plt.yticks([])\n    plt.grid(False)\n    \n    plt.imshow(cv2.imread('../input/deepfake-faces/faces_224/'+Train_set.loc[i,'videoname'][:-4]+'.jpg'))\n    \n    if(Train_set.loc[i,'label']=='FAKE'):\n        plt.xlabel('FAKE Image')\n    else:\n        plt.xlabel('REAL Image')\n        \nplt.show()","metadata":{"id":"VR7Uly2fcUYi","outputId":"c1f47a82-ef4f-4bcd-b51c-d4738142fc0f","execution":{"iopub.status.busy":"2024-04-15T06:24:40.249598Z","iopub.execute_input":"2024-04-15T06:24:40.250353Z","iopub.status.idle":"2024-04-15T06:24:42.489730Z","shell.execute_reply.started":"2024-04-15T06:24:40.250319Z","shell.execute_reply":"2024-04-15T06:24:42.488444Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Base Model","metadata":{"id":"dOvN_divkl-N"}},{"cell_type":"markdown","source":"### Custom CNN Architecture","metadata":{"id":"oid44Xx-pKz6"}},{"cell_type":"code","source":"def retreive_dataset(set_name):\n    images,labels=[],[]\n    for (img, imclass) in zip(set_name['videoname'], set_name['label']):\n        images.append(cv2.imread('../input/deepfake-faces/faces_224/'+img[:-4]+'.jpg'))\n        if(imclass=='FAKE'):\n            labels.append(1)\n        else:\n            labels.append(0)\n    \n    return np.array(images),np.array(labels)","metadata":{"id":"Hz0ZdQ_fgHhG","execution":{"iopub.status.busy":"2024-04-15T06:24:59.371519Z","iopub.execute_input":"2024-04-15T06:24:59.371870Z","iopub.status.idle":"2024-04-15T06:24:59.378071Z","shell.execute_reply.started":"2024-04-15T06:24:59.371842Z","shell.execute_reply":"2024-04-15T06:24:59.377202Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train,y_train=retreive_dataset(Train_set)\nX_val,y_val=retreive_dataset(Val_set)\nX_test,y_test=retreive_dataset(Test_set)","metadata":{"id":"zeAGRcAbguKU","execution":{"iopub.status.busy":"2024-04-15T06:27:23.218301Z","iopub.execute_input":"2024-04-15T06:27:23.219034Z","iopub.status.idle":"2024-04-15T06:28:11.946110Z","shell.execute_reply.started":"2024-04-15T06:27:23.219004Z","shell.execute_reply":"2024-04-15T06:28:11.945209Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from functools import partial\n\ntf.random.set_seed(42) \nDefaultConv2D = partial(tf.keras.layers.Conv2D, kernel_size=3, padding=\"same\",\n                        activation=\"relu\", kernel_initializer=\"he_normal\")\n\nmodel = tf.keras.Sequential([\n    DefaultConv2D(filters=64, kernel_size=7, input_shape=[224, 224, 3]),\n    tf.keras.layers.MaxPool2D(),\n    DefaultConv2D(filters=128),\n    DefaultConv2D(filters=128),\n    tf.keras.layers.MaxPool2D(),\n    tf.keras.layers.Flatten(),\n    tf.keras.layers.Dense(units=128, activation=\"relu\",\n                          kernel_initializer=\"he_normal\"),\n    tf.keras.layers.Dropout(0.5),\n    tf.keras.layers.Dense(units=64, activation=\"relu\",\n                          kernel_initializer=\"he_normal\"),\n    tf.keras.layers.Dropout(0.5),\n    tf.keras.layers.Dense(units=1, activation=\"sigmoid\")\n])","metadata":{"id":"34upiak4pKz6","execution":{"iopub.status.busy":"2024-04-15T06:28:25.852123Z","iopub.execute_input":"2024-04-15T06:28:25.853019Z","iopub.status.idle":"2024-04-15T06:28:25.934232Z","shell.execute_reply.started":"2024-04-15T06:28:25.852985Z","shell.execute_reply":"2024-04-15T06:28:25.933438Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(loss=\"binary_crossentropy\", optimizer=\"nadam\",\n              metrics=[\"accuracy\"])\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2024-04-15T06:28:39.237981Z","iopub.execute_input":"2024-04-15T06:28:39.238586Z","iopub.status.idle":"2024-04-15T06:28:39.275260Z","shell.execute_reply.started":"2024-04-15T06:28:39.238551Z","shell.execute_reply":"2024-04-15T06:28:39.274374Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit(X_train, y_train, epochs=5,batch_size=64,\n                    validation_data=(X_val, y_val))","metadata":{"id":"KZbWeIBYpKz6","outputId":"deb6f56a-7b93-4241-a1bd-b210c0f2d426","execution":{"iopub.status.busy":"2024-04-15T06:28:46.892749Z","iopub.execute_input":"2024-04-15T06:28:46.893097Z","iopub.status.idle":"2024-04-15T06:32:36.815370Z","shell.execute_reply.started":"2024-04-15T06:28:46.893070Z","shell.execute_reply":"2024-04-15T06:32:36.814475Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"score = model.evaluate(X_test, y_test)","metadata":{"id":"6HDDr4uehast","execution":{"iopub.status.busy":"2024-04-15T06:32:48.436418Z","iopub.execute_input":"2024-04-15T06:32:48.439091Z","iopub.status.idle":"2024-04-15T06:33:00.102215Z","shell.execute_reply.started":"2024-04-15T06:32:48.439051Z","shell.execute_reply":"2024-04-15T06:33:00.101296Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# plot model performance\nacc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\nepochs_range = range(1, len(history.epoch) + 1)\n\nplt.figure(figsize=(15,5))\n\nplt.subplot(1, 2, 1)\nplt.plot(epochs_range, acc, label='Train Set')\nplt.plot(epochs_range, val_acc, label='Val Set')\nplt.legend(loc=\"best\")\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.title('Model Accuracy')\n\nplt.subplot(1, 2, 2)\nplt.plot(epochs_range, loss, label='Train Set')\nplt.plot(epochs_range, val_loss, label='Val Set')\nplt.legend(loc=\"best\")\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.title('Model Loss')\n\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-04-15T06:33:08.533710Z","iopub.execute_input":"2024-04-15T06:33:08.534375Z","iopub.status.idle":"2024-04-15T06:33:09.064341Z","shell.execute_reply.started":"2024-04-15T06:33:08.534342Z","shell.execute_reply":"2024-04-15T06:33:09.063431Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**A baseline score is set here around ~51%**","metadata":{}},{"cell_type":"markdown","source":"# Pretrained Models for Transfer Learning","metadata":{"id":"hqxnSBJ3pKz8"}},{"cell_type":"markdown","source":"using Xception model for fine-tuning ","metadata":{}},{"cell_type":"code","source":"train_set_raw=tf.data.Dataset.from_tensor_slices((X_train,y_train))\nvalid_set_raw=tf.data.Dataset.from_tensor_slices((X_val,y_val))\ntest_set_raw=tf.data.Dataset.from_tensor_slices((X_test,y_test))","metadata":{"execution":{"iopub.status.busy":"2024-04-15T06:33:34.723291Z","iopub.execute_input":"2024-04-15T06:33:34.723691Z","iopub.status.idle":"2024-04-15T06:33:40.069138Z","shell.execute_reply.started":"2024-04-15T06:33:34.723661Z","shell.execute_reply":"2024-04-15T06:33:40.067720Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tf.keras.backend.clear_session()  # extra code – resets layer name counter\n\nbatch_size = 32\npreprocess = tf.keras.applications.xception.preprocess_input\ntrain_set = train_set_raw.map(lambda X, y: (preprocess(tf.cast(X, tf.float32)), y))\ntrain_set = train_set.shuffle(1000, seed=42).batch(batch_size).prefetch(1)\nvalid_set = valid_set_raw.map(lambda X, y: (preprocess(tf.cast(X, tf.float32)), y)).batch(batch_size)\ntest_set = test_set_raw.map(lambda X, y: (preprocess(tf.cast(X, tf.float32)), y)).batch(batch_size)","metadata":{"id":"Bnz0n9XApKz9","execution":{"iopub.status.busy":"2024-04-15T06:33:45.670260Z","iopub.execute_input":"2024-04-15T06:33:45.670630Z","iopub.status.idle":"2024-04-15T06:33:47.385303Z","shell.execute_reply.started":"2024-04-15T06:33:45.670602Z","shell.execute_reply":"2024-04-15T06:33:47.384298Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# extra code – displays the first 9 images in the first batch of valid_set\n\nplt.figure(figsize=(12, 12))\nfor X_batch, y_batch in valid_set.take(1):\n    for index in range(9):\n        plt.subplot(3, 3, index + 1)\n        plt.imshow((X_batch[index] + 1) / 2)  # rescale to 0–1 for imshow()\n        if(y_batch[index]==1):\n            classt='FAKE'\n        else:\n            classt='REAL'\n        plt.title(f\"Class: {classt}\")\n        plt.axis(\"off\")\n\nplt.show()","metadata":{"id":"ZL3c3i4opKz9","outputId":"38847d8d-8822-41a3-cfb2-27479aa5debe","execution":{"iopub.status.busy":"2024-04-15T06:34:00.785911Z","iopub.execute_input":"2024-04-15T06:34:00.786386Z","iopub.status.idle":"2024-04-15T06:34:02.712921Z","shell.execute_reply.started":"2024-04-15T06:34:00.786355Z","shell.execute_reply":"2024-04-15T06:34:02.711951Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_augmentation = tf.keras.Sequential([\n    tf.keras.layers.RandomFlip(mode=\"horizontal\", seed=42),\n    tf.keras.layers.RandomRotation(factor=0.05, seed=42),\n    tf.keras.layers.RandomContrast(factor=0.2, seed=42)\n])","metadata":{"id":"Ib0cA8Y1pKz9","execution":{"iopub.status.busy":"2024-04-15T06:34:10.725875Z","iopub.execute_input":"2024-04-15T06:34:10.726750Z","iopub.status.idle":"2024-04-15T06:34:10.741944Z","shell.execute_reply.started":"2024-04-15T06:34:10.726715Z","shell.execute_reply":"2024-04-15T06:34:10.740993Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# extra code – displays the same first 9 images, after augmentation\n\nplt.figure(figsize=(12, 12))\nfor X_batch, y_batch in valid_set.take(1):\n    X_batch_augmented = data_augmentation(X_batch, training=True)\n    for index in range(9):\n        plt.subplot(3, 3, index + 1)\n        # We must rescale the images to the 0-1 range for imshow(), and also\n        # clip the result to that range, because data augmentation may\n        # make some values go out of bounds (e.g., RandomContrast in this case).\n        plt.imshow(np.clip((X_batch_augmented[index] + 1) / 2, 0, 1))\n        if(y_batch[index]==1):\n            classt='FAKE'\n        else:\n            classt='REAL'\n        plt.title(f\"Class: {classt}\")\n        plt.axis(\"off\")\n\nplt.show()","metadata":{"id":"w6GH5_vupKz-","outputId":"eeb2c924-2f4f-4aa1-bea9-951bebef4bf0","execution":{"iopub.status.busy":"2024-04-15T06:34:13.802515Z","iopub.execute_input":"2024-04-15T06:34:13.802877Z","iopub.status.idle":"2024-04-15T06:34:17.336212Z","shell.execute_reply.started":"2024-04-15T06:34:13.802850Z","shell.execute_reply":"2024-04-15T06:34:17.335112Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tf.random.set_seed(42)  # extra code – ensures reproducibility\nbase_model = tf.keras.applications.xception.Xception(weights=\"imagenet\",\n                                                     include_top=False)\navg = tf.keras.layers.GlobalAveragePooling2D()(base_model.output)\noutput = tf.keras.layers.Dense(1, activation=\"sigmoid\")(avg)\nmodel = tf.keras.Model(inputs=base_model.input, outputs=output)","metadata":{"id":"lRyCgvaKpKz-","outputId":"a825e173-8b1d-4217-a1c4-5491b49c3e82","execution":{"iopub.status.busy":"2024-04-15T06:34:36.278925Z","iopub.execute_input":"2024-04-15T06:34:36.279754Z","iopub.status.idle":"2024-04-15T06:34:38.386330Z","shell.execute_reply.started":"2024-04-15T06:34:36.279720Z","shell.execute_reply":"2024-04-15T06:34:38.385520Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for layer in base_model.layers:\n    layer.trainable = False","metadata":{"id":"KBlyG6ElpKz-","execution":{"iopub.status.busy":"2024-04-15T06:34:45.301109Z","iopub.execute_input":"2024-04-15T06:34:45.301476Z","iopub.status.idle":"2024-04-15T06:34:45.311071Z","shell.execute_reply.started":"2024-04-15T06:34:45.301448Z","shell.execute_reply":"2024-04-15T06:34:45.310168Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"optimizer = tf.keras.optimizers.SGD(learning_rate=0.1, momentum=0.9)\nmodel.compile(loss=\"binary_crossentropy\", optimizer=optimizer,\n              metrics=[\"accuracy\"])\nhistory = model.fit(train_set, validation_data=valid_set, epochs=5)","metadata":{"id":"GGxK2yPcpKz-","outputId":"6b64214a-e104-4b6c-9b7a-3388fc9aa15f","execution":{"iopub.status.busy":"2024-04-15T06:37:54.809344Z","iopub.execute_input":"2024-04-15T06:37:54.809949Z","iopub.status.idle":"2024-04-15T06:41:54.590812Z","shell.execute_reply.started":"2024-04-15T06:37:54.809916Z","shell.execute_reply":"2024-04-15T06:41:54.590006Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for indices in zip(range(33), range(33, 66), range(66, 99), range(99, 132)):\n    for idx in indices:\n        print(f\"{idx:3}: {base_model.layers[idx].name:22}\", end=\"\")\n    print()","metadata":{"id":"GvGMiJMLpKz-","outputId":"91f2c96c-c058-45e0-e428-66fa6076ad56","execution":{"iopub.status.busy":"2024-04-15T06:42:06.141623Z","iopub.execute_input":"2024-04-15T06:42:06.141979Z","iopub.status.idle":"2024-04-15T06:42:06.160358Z","shell.execute_reply.started":"2024-04-15T06:42:06.141951Z","shell.execute_reply":"2024-04-15T06:42:06.159453Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.evaluate(test_set)","metadata":{"execution":{"iopub.status.busy":"2024-04-15T06:42:35.655243Z","iopub.execute_input":"2024-04-15T06:42:35.655600Z","iopub.status.idle":"2024-04-15T06:42:47.204039Z","shell.execute_reply.started":"2024-04-15T06:42:35.655573Z","shell.execute_reply":"2024-04-15T06:42:47.203199Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**After Fine tuning The accuracy comes about ~64%**","metadata":{}},{"cell_type":"markdown","source":"Now that the weights of our new top layers are not too bad, we can make the top part of the base model trainable again, and continue training, but with a lower learning rate:","metadata":{"id":"L_bEwL8KpKz_"}},{"cell_type":"code","source":"for layer in base_model.layers[56:]:\n    layer.trainable = True\n\noptimizer = tf.keras.optimizers.SGD(learning_rate=0.01, momentum=0.9)\nmodel.compile(loss=\"binary_crossentropy\", optimizer=optimizer,\n              metrics=[\"accuracy\"])\nhistory = model.fit(train_set, validation_data=valid_set, epochs=10)","metadata":{"id":"GEUNGlhvpKz_","outputId":"c622a91d-f634-4443-b87e-8d46defdb578","execution":{"iopub.status.busy":"2024-04-15T06:43:17.801728Z","iopub.execute_input":"2024-04-15T06:43:17.802557Z","iopub.status.idle":"2024-04-15T06:57:43.045886Z","shell.execute_reply.started":"2024-04-15T06:43:17.802519Z","shell.execute_reply":"2024-04-15T06:57:43.044890Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# plot model performance\nacc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\nepochs_range = range(1, len(history.epoch) + 1)\n\nplt.figure(figsize=(15,5))\n\nplt.subplot(1, 2, 1)\nplt.plot(epochs_range, acc, label='Train Set')\nplt.plot(epochs_range, val_acc, label='Val Set')\nplt.legend(loc=\"best\")\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.title('Model Accuracy')\n\nplt.subplot(1, 2, 2)\nplt.plot(epochs_range, loss, label='Train Set')\nplt.plot(epochs_range, val_loss, label='Val Set')\nplt.legend(loc=\"best\")\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.title('Model Loss')\n\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-04-15T06:57:51.850225Z","iopub.execute_input":"2024-04-15T06:57:51.850599Z","iopub.status.idle":"2024-04-15T06:57:52.503021Z","shell.execute_reply.started":"2024-04-15T06:57:51.850569Z","shell.execute_reply":"2024-04-15T06:57:52.502037Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.evaluate(test_set)","metadata":{"execution":{"iopub.status.busy":"2024-04-15T06:58:13.977695Z","iopub.execute_input":"2024-04-15T06:58:13.978388Z","iopub.status.idle":"2024-04-15T06:58:25.217082Z","shell.execute_reply.started":"2024-04-15T06:58:13.978349Z","shell.execute_reply":"2024-04-15T06:58:25.216203Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**The model accuracy finally reaches to 81.9%**","metadata":{}},{"cell_type":"code","source":"model.save('xception_deepfake_model.h5')","metadata":{"execution":{"iopub.status.busy":"2024-04-15T06:59:34.574671Z","iopub.execute_input":"2024-04-15T06:59:34.575530Z","iopub.status.idle":"2024-04-15T06:59:35.087761Z","shell.execute_reply.started":"2024-04-15T06:59:34.575493Z","shell.execute_reply":"2024-04-15T06:59:35.086734Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Adding Explainability to the model","metadata":{}},{"cell_type":"code","source":"!pip install lime","metadata":{"execution":{"iopub.status.busy":"2024-04-15T06:59:48.922199Z","iopub.execute_input":"2024-04-15T06:59:48.922846Z","iopub.status.idle":"2024-04-15T07:00:01.307936Z","shell.execute_reply.started":"2024-04-15T06:59:48.922812Z","shell.execute_reply":"2024-04-15T07:00:01.306640Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from lime import lime_image\n\nexplainer = lime_image.LimeImageExplainer()","metadata":{"execution":{"iopub.status.busy":"2024-04-15T07:00:05.399447Z","iopub.execute_input":"2024-04-15T07:00:05.399872Z","iopub.status.idle":"2024-04-15T07:00:06.136580Z","shell.execute_reply.started":"2024-04-15T07:00:05.399833Z","shell.execute_reply":"2024-04-15T07:00:06.135788Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(12, 12))\n\nfor index in range(9):\n    plt.subplot(3, 3, index + 1)\n    plt.imshow((X_batch[index] + 1) / 2)  # rescale to 0–1 for imshow()\n    if(y_batch[index]==1):\n        classt='FAKE'\n    else:\n        classt='REAL'\n    plt.title(f\"Class: {classt}\")\n    plt.axis(\"off\")\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-04-15T07:11:36.193088Z","iopub.execute_input":"2024-04-15T07:11:36.193948Z","iopub.status.idle":"2024-04-15T07:11:37.398576Z","shell.execute_reply.started":"2024-04-15T07:11:36.193914Z","shell.execute_reply":"2024-04-15T07:11:37.397584Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_data=X_batch[2,:,:,:]\ntest_data.shape","metadata":{"execution":{"iopub.status.busy":"2024-04-15T07:12:04.867937Z","iopub.execute_input":"2024-04-15T07:12:04.868768Z","iopub.status.idle":"2024-04-15T07:12:04.880020Z","shell.execute_reply.started":"2024-04-15T07:12:04.868725Z","shell.execute_reply":"2024-04-15T07:12:04.878976Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"explanation = explainer.explain_instance(test_data.numpy().astype('double'), model.predict,  \n                                         top_labels=3, hide_color=0, num_samples=1000)\n","metadata":{"execution":{"iopub.status.busy":"2024-04-15T07:15:25.938878Z","iopub.execute_input":"2024-04-15T07:15:25.939648Z","iopub.status.idle":"2024-04-15T07:15:44.853417Z","shell.execute_reply.started":"2024-04-15T07:15:25.939613Z","shell.execute_reply":"2024-04-15T07:15:44.852103Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from skimage.segmentation import mark_boundaries\n\ntemp_1, mask_1 = explanation.get_image_and_mask(explanation.top_labels[0], positive_only=True, num_features=5, hide_rest=True)\ntemp_2, mask_2 = explanation.get_image_and_mask(explanation.top_labels[0], positive_only=False, num_features=10, hide_rest=False)\n\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15,15))\nax1.imshow(mark_boundaries(temp_1, mask_1))\nax2.imshow(mark_boundaries(temp_2, mask_2))\nax1.axis('off')\nax2.axis('off')","metadata":{"execution":{"iopub.status.busy":"2024-04-15T07:15:52.598855Z","iopub.execute_input":"2024-04-15T07:15:52.599517Z","iopub.status.idle":"2024-04-15T07:15:52.906271Z","shell.execute_reply.started":"2024-04-15T07:15:52.599481Z","shell.execute_reply":"2024-04-15T07:15:52.905169Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Deep Fake Video Classification","metadata":{}},{"cell_type":"markdown","source":"## Importing required libraries","metadata":{}},{"cell_type":"code","source":"!pip install -U --upgrade tensorflow","metadata":{"execution":{"iopub.status.busy":"2024-04-15T07:19:36.350262Z","iopub.execute_input":"2024-04-15T07:19:36.350645Z","iopub.status.idle":"2024-04-15T07:19:49.005359Z","shell.execute_reply.started":"2024-04-15T07:19:36.350614Z","shell.execute_reply":"2024-04-15T07:19:49.004133Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install tensorflow-docs","metadata":{"execution":{"iopub.status.busy":"2024-04-15T07:20:50.728572Z","iopub.execute_input":"2024-04-15T07:20:50.729339Z","iopub.status.idle":"2024-04-15T07:21:03.950835Z","shell.execute_reply.started":"2024-04-15T07:20:50.729306Z","shell.execute_reply":"2024-04-15T07:21:03.949607Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow_docs.vis import embed\nfrom tensorflow import keras\n\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport pandas as pd\nimport numpy as np\nimport imageio\nimport cv2\nimport os","metadata":{"execution":{"iopub.status.busy":"2024-04-15T07:21:19.654244Z","iopub.execute_input":"2024-04-15T07:21:19.654569Z","iopub.status.idle":"2024-04-15T07:21:19.659628Z","shell.execute_reply.started":"2024-04-15T07:21:19.654545Z","shell.execute_reply":"2024-04-15T07:21:19.658723Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Data Visualisation","metadata":{}},{"cell_type":"code","source":"DATA_FOLDER = '../input/deepfake-detection-challenge'\nTRAIN_SAMPLE_FOLDER = 'train_sample_videos'\nTEST_FOLDER = 'test_videos'\n\nprint(f\"Train samples: {len(os.listdir(os.path.join(DATA_FOLDER, TRAIN_SAMPLE_FOLDER)))}\")\nprint(f\"Test samples: {len(os.listdir(os.path.join(DATA_FOLDER, TEST_FOLDER)))}\")","metadata":{"execution":{"iopub.status.busy":"2024-04-15T07:21:26.274199Z","iopub.execute_input":"2024-04-15T07:21:26.274556Z","iopub.status.idle":"2024-04-15T07:21:26.615239Z","shell.execute_reply.started":"2024-04-15T07:21:26.274527Z","shell.execute_reply":"2024-04-15T07:21:26.614309Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_sample_metadata = pd.read_json('../input/deepfake-detection-challenge/train_sample_videos/metadata.json').T\ntrain_sample_metadata.head()","metadata":{"execution":{"iopub.status.busy":"2024-04-15T07:21:35.077224Z","iopub.execute_input":"2024-04-15T07:21:35.077602Z","iopub.status.idle":"2024-04-15T07:21:35.209802Z","shell.execute_reply.started":"2024-04-15T07:21:35.077572Z","shell.execute_reply":"2024-04-15T07:21:35.208920Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_sample_metadata.groupby('label')['label'].count().plot(figsize=(15, 5), kind='bar', title='Distribution of Labels in the Training Set')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-04-15T07:21:49.325660Z","iopub.execute_input":"2024-04-15T07:21:49.326031Z","iopub.status.idle":"2024-04-15T07:21:49.642775Z","shell.execute_reply.started":"2024-04-15T07:21:49.326004Z","shell.execute_reply":"2024-04-15T07:21:49.641852Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_sample_metadata.shape","metadata":{"execution":{"iopub.status.busy":"2024-04-15T07:21:54.298783Z","iopub.execute_input":"2024-04-15T07:21:54.299475Z","iopub.status.idle":"2024-04-15T07:21:54.305450Z","shell.execute_reply.started":"2024-04-15T07:21:54.299441Z","shell.execute_reply":"2024-04-15T07:21:54.304337Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Fake videos","metadata":{}},{"cell_type":"code","source":"fake_train_sample_video = list(train_sample_metadata.loc[train_sample_metadata.label=='FAKE'].sample(3).index)\nfake_train_sample_video","metadata":{"execution":{"iopub.status.busy":"2024-04-15T07:22:00.997022Z","iopub.execute_input":"2024-04-15T07:22:00.997954Z","iopub.status.idle":"2024-04-15T07:22:01.006659Z","shell.execute_reply.started":"2024-04-15T07:22:00.997918Z","shell.execute_reply":"2024-04-15T07:22:01.005651Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def display_image_from_video(video_path):\n    capture_image = cv2.VideoCapture(video_path) \n    ret, frame = capture_image.read()\n    fig = plt.figure(figsize=(10,10))\n    ax = fig.add_subplot(111)\n    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n    ax.imshow(frame)","metadata":{"execution":{"iopub.status.busy":"2024-04-15T07:22:11.521445Z","iopub.execute_input":"2024-04-15T07:22:11.521798Z","iopub.status.idle":"2024-04-15T07:22:11.527258Z","shell.execute_reply.started":"2024-04-15T07:22:11.521768Z","shell.execute_reply":"2024-04-15T07:22:11.526280Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for video_file in fake_train_sample_video:\n    display_image_from_video(os.path.join(DATA_FOLDER, TRAIN_SAMPLE_FOLDER, video_file))","metadata":{"execution":{"iopub.status.busy":"2024-04-15T07:22:16.076132Z","iopub.execute_input":"2024-04-15T07:22:16.076514Z","iopub.status.idle":"2024-04-15T07:22:18.777410Z","shell.execute_reply.started":"2024-04-15T07:22:16.076484Z","shell.execute_reply":"2024-04-15T07:22:18.776516Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Real Videos","metadata":{}},{"cell_type":"code","source":"real_train_sample_video = list(train_sample_metadata.loc[train_sample_metadata.label=='REAL'].sample(3).index)\nreal_train_sample_video","metadata":{"execution":{"iopub.status.busy":"2024-04-15T07:23:02.977232Z","iopub.execute_input":"2024-04-15T07:23:02.977633Z","iopub.status.idle":"2024-04-15T07:23:02.986361Z","shell.execute_reply.started":"2024-04-15T07:23:02.977603Z","shell.execute_reply":"2024-04-15T07:23:02.985220Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for video_file in real_train_sample_video:\n    display_image_from_video(os.path.join(DATA_FOLDER, TRAIN_SAMPLE_FOLDER, video_file))","metadata":{"execution":{"iopub.status.busy":"2024-04-15T07:23:17.322245Z","iopub.execute_input":"2024-04-15T07:23:17.322623Z","iopub.status.idle":"2024-04-15T07:23:20.042630Z","shell.execute_reply.started":"2024-04-15T07:23:17.322594Z","shell.execute_reply":"2024-04-15T07:23:20.041770Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Videos with same original","metadata":{}},{"cell_type":"code","source":"train_sample_metadata['original'].value_counts()[0:5]","metadata":{"execution":{"iopub.status.busy":"2024-04-15T07:23:59.141038Z","iopub.execute_input":"2024-04-15T07:23:59.141940Z","iopub.status.idle":"2024-04-15T07:23:59.153421Z","shell.execute_reply.started":"2024-04-15T07:23:59.141904Z","shell.execute_reply":"2024-04-15T07:23:59.152446Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def display_image_from_video_list(video_path_list, video_folder=TRAIN_SAMPLE_FOLDER):\n    plt.figure()\n    fig, ax = plt.subplots(2,3,figsize=(16,8))\n    # images extracted from the first 6 videos\n    for i, video_file in enumerate(video_path_list[0:6]):\n        video_path = os.path.join(DATA_FOLDER, video_folder,video_file)\n        capture_image = cv2.VideoCapture(video_path) \n        ret, frame = capture_image.read()\n        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n        ax[i//3, i%3].imshow(frame)\n        ax[i//3, i%3].set_title(f\"Video: {video_file}\")\n        ax[i//3, i%3].axis('on')\n","metadata":{"execution":{"iopub.status.busy":"2024-04-15T07:25:51.508758Z","iopub.execute_input":"2024-04-15T07:25:51.509483Z","iopub.status.idle":"2024-04-15T07:25:51.516314Z","shell.execute_reply.started":"2024-04-15T07:25:51.509449Z","shell.execute_reply":"2024-04-15T07:25:51.515408Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"same_original_fake_train_sample_video = list(train_sample_metadata.loc[train_sample_metadata.original=='atvmxvwyns.mp4'].index)\ndisplay_image_from_video_list(same_original_fake_train_sample_video)","metadata":{"execution":{"iopub.status.busy":"2024-04-15T07:25:55.282027Z","iopub.execute_input":"2024-04-15T07:25:55.282956Z","iopub.status.idle":"2024-04-15T07:25:59.012021Z","shell.execute_reply.started":"2024-04-15T07:25:55.282917Z","shell.execute_reply":"2024-04-15T07:25:59.011162Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Test video files","metadata":{}},{"cell_type":"code","source":"test_videos = pd.DataFrame(list(os.listdir(os.path.join(DATA_FOLDER, TEST_FOLDER))), columns=['video'])","metadata":{"execution":{"iopub.status.busy":"2024-04-15T07:26:20.817073Z","iopub.execute_input":"2024-04-15T07:26:20.817787Z","iopub.status.idle":"2024-04-15T07:26:20.824774Z","shell.execute_reply.started":"2024-04-15T07:26:20.817751Z","shell.execute_reply":"2024-04-15T07:26:20.823965Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_videos.head()","metadata":{"execution":{"iopub.status.busy":"2024-04-15T07:26:23.367802Z","iopub.execute_input":"2024-04-15T07:26:23.368537Z","iopub.status.idle":"2024-04-15T07:26:23.378328Z","shell.execute_reply.started":"2024-04-15T07:26:23.368497Z","shell.execute_reply":"2024-04-15T07:26:23.377207Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"display_image_from_video(os.path.join(DATA_FOLDER, TEST_FOLDER, test_videos.iloc[2].video))","metadata":{"execution":{"iopub.status.busy":"2024-04-15T07:26:33.551800Z","iopub.execute_input":"2024-04-15T07:26:33.552561Z","iopub.status.idle":"2024-04-15T07:26:34.494081Z","shell.execute_reply.started":"2024-04-15T07:26:33.552514Z","shell.execute_reply":"2024-04-15T07:26:34.493198Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Play video files","metadata":{}},{"cell_type":"code","source":"fake_videos = list(train_sample_metadata.loc[train_sample_metadata.label=='FAKE'].index)","metadata":{"execution":{"iopub.status.busy":"2024-04-15T07:26:49.643933Z","iopub.execute_input":"2024-04-15T07:26:49.644675Z","iopub.status.idle":"2024-04-15T07:26:49.649967Z","shell.execute_reply.started":"2024-04-15T07:26:49.644630Z","shell.execute_reply":"2024-04-15T07:26:49.649053Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from IPython.display import HTML\nfrom base64 import b64encode\n\ndef play_video(video_file, subset=TRAIN_SAMPLE_FOLDER):\n    video_url = open(os.path.join(DATA_FOLDER, subset,video_file),'rb').read()\n    data_url = \"data:video/mp4;base64,\" + b64encode(video_url).decode()\n    return HTML(\"\"\"<video width=500 controls><source src=\"%s\" type=\"video/mp4\"></video>\"\"\" % data_url)\n\nplay_video(fake_videos[10])","metadata":{"execution":{"iopub.status.busy":"2024-04-15T07:27:34.284262Z","iopub.execute_input":"2024-04-15T07:27:34.284699Z","iopub.status.idle":"2024-04-15T07:27:34.664985Z","shell.execute_reply.started":"2024-04-15T07:27:34.284659Z","shell.execute_reply":"2024-04-15T07:27:34.663361Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Modelling","metadata":{}},{"cell_type":"markdown","source":"### A CNN-RNN Architecture","metadata":{}},{"cell_type":"code","source":"IMG_SIZE = 224\nBATCH_SIZE = 64\nEPOCHS = 10\n\nMAX_SEQ_LENGTH = 20\nNUM_FEATURES = 2048","metadata":{"execution":{"iopub.status.busy":"2024-04-15T07:28:18.482172Z","iopub.execute_input":"2024-04-15T07:28:18.482541Z","iopub.status.idle":"2024-04-15T07:28:18.487495Z","shell.execute_reply.started":"2024-04-15T07:28:18.482513Z","shell.execute_reply":"2024-04-15T07:28:18.486515Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def crop_center_square(frame):\n    y, x = frame.shape[0:2]\n    min_dim = min(y, x)\n    start_x = (x // 2) - (min_dim // 2)\n    start_y = (y // 2) - (min_dim // 2)\n    return frame[start_y : start_y + min_dim, start_x : start_x + min_dim]\n\n\ndef load_video(path, max_frames=0, resize=(IMG_SIZE, IMG_SIZE)):\n    cap = cv2.VideoCapture(path)\n    frames = []\n    try:\n        while True:\n            ret, frame = cap.read()\n            if not ret:\n                break\n            frame = crop_center_square(frame)\n            frame = cv2.resize(frame, resize)\n            frame = frame[:, :, [2, 1, 0]]\n            frames.append(frame)\n\n            if len(frames) == max_frames:\n                break\n    finally:\n        cap.release()\n    return np.array(frames)","metadata":{"execution":{"iopub.status.busy":"2024-04-15T07:28:21.536332Z","iopub.execute_input":"2024-04-15T07:28:21.536719Z","iopub.status.idle":"2024-04-15T07:28:21.545765Z","shell.execute_reply.started":"2024-04-15T07:28:21.536688Z","shell.execute_reply":"2024-04-15T07:28:21.544600Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"using the InceptionV3 model to extract meaningful features from the extracted frames.","metadata":{}},{"cell_type":"code","source":"def build_feature_extractor():\n    feature_extractor = keras.applications.InceptionV3(\n        weights=\"imagenet\",\n        include_top=False,\n        pooling=\"avg\",\n        input_shape=(IMG_SIZE, IMG_SIZE, 3),\n    )\n    preprocess_input = keras.applications.inception_v3.preprocess_input\n\n    inputs = keras.Input((IMG_SIZE, IMG_SIZE, 3))\n    preprocessed = preprocess_input(inputs)\n\n    outputs = feature_extractor(preprocessed)\n    return keras.Model(inputs, outputs, name=\"feature_extractor\")\n\n\nfeature_extractor = build_feature_extractor()","metadata":{"execution":{"iopub.status.busy":"2024-04-15T07:28:27.664438Z","iopub.execute_input":"2024-04-15T07:28:27.665066Z","iopub.status.idle":"2024-04-15T07:28:30.433007Z","shell.execute_reply.started":"2024-04-15T07:28:27.665036Z","shell.execute_reply":"2024-04-15T07:28:30.432206Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def prepare_all_videos(df, root_dir):\n    num_samples = len(df)\n    video_paths = list(df.index)\n    labels = df[\"label\"].values\n    labels = np.array(labels=='FAKE').astype(int)\n\n    # `frame_masks` and `frame_features` are what we will feed to our sequence model.\n    # `frame_masks` will contain a bunch of booleans denoting if a timestep is\n    # masked with padding or not.\n    frame_masks = np.zeros(shape=(num_samples, MAX_SEQ_LENGTH), dtype=\"bool\")\n    frame_features = np.zeros(\n        shape=(num_samples, MAX_SEQ_LENGTH, NUM_FEATURES), dtype=\"float32\"\n    )\n\n    # For each video.\n    for idx, path in enumerate(video_paths):\n        # Gather all its frames and add a batch dimension.\n        frames = load_video(os.path.join(root_dir, path))\n        frames = frames[None, ...]\n\n        # Initialize placeholders to store the masks and features of the current video.\n        temp_frame_mask = np.zeros(shape=(1, MAX_SEQ_LENGTH,), dtype=\"bool\")\n        temp_frame_features = np.zeros(\n            shape=(1, MAX_SEQ_LENGTH, NUM_FEATURES), dtype=\"float32\"\n        )\n\n        # Extract features from the frames of the current video.\n        for i, batch in enumerate(frames):\n            video_length = batch.shape[0]\n            length = min(MAX_SEQ_LENGTH, video_length)\n            for j in range(length):\n                temp_frame_features[i, j, :] = feature_extractor.predict(\n                    batch[None, j, :]\n                )\n            temp_frame_mask[i, :length] = 1  # 1 = not masked, 0 = masked\n\n        frame_features[idx,] = temp_frame_features.squeeze()\n        frame_masks[idx,] = temp_frame_mask.squeeze()\n\n    return (frame_features, frame_masks), labels","metadata":{"execution":{"iopub.status.busy":"2024-04-15T07:31:44.013313Z","iopub.execute_input":"2024-04-15T07:31:44.013681Z","iopub.status.idle":"2024-04-15T07:31:44.024452Z","shell.execute_reply.started":"2024-04-15T07:31:44.013650Z","shell.execute_reply":"2024-04-15T07:31:44.023345Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n\nTrain_set, Test_set = train_test_split(train_sample_metadata,test_size=0.1,random_state=42,stratify=train_sample_metadata['label'])\n\nprint(Train_set.shape, Test_set.shape )","metadata":{"execution":{"iopub.status.busy":"2024-04-15T07:31:46.542810Z","iopub.execute_input":"2024-04-15T07:31:46.543777Z","iopub.status.idle":"2024-04-15T07:31:46.552729Z","shell.execute_reply.started":"2024-04-15T07:31:46.543741Z","shell.execute_reply":"2024-04-15T07:31:46.551585Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data, train_labels = prepare_all_videos(Train_set, \"train\")\ntest_data, test_labels = prepare_all_videos(Test_set, \"test\")\n\nprint(f\"Frame features in train set: {train_data[0].shape}\")\nprint(f\"Frame masks in train set: {train_data[1].shape}\")","metadata":{"execution":{"iopub.status.busy":"2024-04-15T07:31:49.599015Z","iopub.execute_input":"2024-04-15T07:31:49.599904Z","iopub.status.idle":"2024-04-15T07:31:49.660930Z","shell.execute_reply.started":"2024-04-15T07:31:49.599869Z","shell.execute_reply":"2024-04-15T07:31:49.659951Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## The sequence model","metadata":{}},{"cell_type":"code","source":"frame_features_input = keras.Input((MAX_SEQ_LENGTH, NUM_FEATURES))\nmask_input = keras.Input((MAX_SEQ_LENGTH,), dtype=\"bool\")\n\n#can use LSTM as well\nx = keras.layers.GRU(16, return_sequences=True)(\n    frame_features_input, mask=mask_input\n)\nx = keras.layers.GRU(8)(x)\nx = keras.layers.Dropout(0.4)(x)\nx = keras.layers.Dense(8, activation=\"relu\")(x)\noutput = keras.layers.Dense(1, activation=\"sigmoid\")(x)\n\nmodel = keras.Model([frame_features_input, mask_input], output)\n\nmodel.compile(loss=\"binary_crossentropy\", optimizer=\"adam\", metrics=[\"accuracy\"])\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2024-04-15T07:31:59.817118Z","iopub.execute_input":"2024-04-15T07:31:59.817882Z","iopub.status.idle":"2024-04-15T07:32:00.036182Z","shell.execute_reply.started":"2024-04-15T07:31:59.817844Z","shell.execute_reply":"2024-04-15T07:32:00.035167Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"checkpoint = keras.callbacks.ModelCheckpoint('./model.weights.h5', save_weights_only=True, save_best_only=True)\n\nhistory = model.fit(\n        [train_data[0], train_data[1]],\n        train_labels,\n        validation_data=([test_data[0], test_data[1]],test_labels),\n        callbacks=[checkpoint],\n        epochs=EPOCHS,\n        batch_size=8\n    )","metadata":{"execution":{"iopub.status.busy":"2024-04-15T07:33:06.603138Z","iopub.execute_input":"2024-04-15T07:33:06.603901Z","iopub.status.idle":"2024-04-15T07:33:23.973198Z","shell.execute_reply.started":"2024-04-15T07:33:06.603867Z","shell.execute_reply":"2024-04-15T07:33:23.972318Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n# Extracting training history\nhistory_dict = history.history\n\n# Extracting accuracy and loss values\naccuracy = history_dict['accuracy']\nval_accuracy = history_dict['val_accuracy']\nloss = history_dict['loss']\nval_loss = history_dict['val_loss']\n\n# Plotting accuracy\nepochs = range(1, len(accuracy) + 1)\nplt.plot(epochs, accuracy, 'bo', label='Training accuracy')\nplt.plot(epochs, val_accuracy, 'b', label='Validation accuracy')\nplt.title('Training and validation accuracy')\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.legend()\nplt.show()\n\n# Plotting loss\nplt.plot(epochs, loss, 'bo', label='Training loss')\nplt.plot(epochs, val_loss, 'b', label='Validation loss')\nplt.title('Training and validation loss')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.legend()\nplt.show()\n\n# Calculate final accuracy\nfinal_accuracy = accuracy[-1]\nprint(f'Final accuracy: {final_accuracy}')\n\n# Alternatively, you can use the following line to directly get the final accuracy\n# final_accuracy = model.evaluate(test_data, test_labels)[1]\n","metadata":{"execution":{"iopub.status.busy":"2024-04-15T07:37:38.225073Z","iopub.execute_input":"2024-04-15T07:37:38.225978Z","iopub.status.idle":"2024-04-15T07:37:38.805348Z","shell.execute_reply.started":"2024-04-15T07:37:38.225942Z","shell.execute_reply":"2024-04-15T07:37:38.804433Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Inference","metadata":{}},{"cell_type":"code","source":"def prepare_single_video(frames):\n    frames = frames[None, ...]\n    frame_mask = np.zeros(shape=(1, MAX_SEQ_LENGTH,), dtype=\"bool\")\n    frame_features = np.zeros(shape=(1, MAX_SEQ_LENGTH, NUM_FEATURES), dtype=\"float32\")\n\n    for i, batch in enumerate(frames):\n        video_length = batch.shape[0]\n        length = min(MAX_SEQ_LENGTH, video_length)\n        for j in range(length):\n            frame_features[i, j, :] = feature_extractor.predict(batch[None, j, :])\n        frame_mask[i, :length] = 1  # 1 = not masked, 0 = masked\n\n    return frame_features, frame_mask\n\ndef sequence_prediction(path):\n    frames = load_video(os.path.join(DATA_FOLDER, TEST_FOLDER,path))\n    frame_features, frame_mask = prepare_single_video(frames)\n    return model.predict([frame_features, frame_mask])[0]\n    \n# This utility is for visualization.\n# Referenced from:\n# https://www.tensorflow.org/hub/tutorials/action_recognition_with_tf_hub\ndef to_gif(images):\n    converted_images = images.astype(np.uint8)\n    imageio.mimsave(\"animation.gif\", converted_images, fps=10)\n    return embed.embed_file(\"animation.gif\")\n\n\ntest_video = np.random.choice(test_videos[\"video\"].values.tolist())\nprint(f\"Test video path: {test_video}\")\n\nif(sequence_prediction(test_video)>=0.5):\n    print(f'The video is FAKE')\nelse:\n    print(f'The video is REAL')\n\nplay_video(test_video,TEST_FOLDER)","metadata":{"execution":{"iopub.status.busy":"2024-04-15T07:34:34.477975Z","iopub.execute_input":"2024-04-15T07:34:34.478772Z","iopub.status.idle":"2024-04-15T07:34:37.345023Z","shell.execute_reply.started":"2024-04-15T07:34:34.478735Z","shell.execute_reply":"2024-04-15T07:34:37.344085Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Conclusion","metadata":{}},{"cell_type":"markdown","source":"**The deep fake image classifier and deep fake video classifier model gave a generalisation error of around ~82%**","metadata":{}},{"cell_type":"markdown","source":"# Reference","metadata":{}},{"cell_type":"markdown","source":"https://keras.io/examples/vision/video_classification/\n\nhttps://www.kaggle.com/code/gpreda/deepfake-starter-kit\n\nhttps://www.kaggle.com/code/robikscube/kaggle-deepfake-detection-introduction\n\nhttps://www.kaggle.com/code/humananalog/binary-image-classifier-training-demo\n\nhttps://www.kaggle.com/datasets/dagnelies/deepfake-faces\n\nhttps://www.kaggle.com/code/gautam20bce1227/fake-detection-on-images","metadata":{}}]}