{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.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":"# DeepFake Image detection","metadata":{"id":"vGkKRV1kY8Z-"}},{"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","trusted":true,"execution":{"iopub.status.busy":"2025-10-15T17:55:53.961033Z","iopub.execute_input":"2025-10-15T17:55:53.961573Z","iopub.status.idle":"2025-10-15T17:56:08.647258Z","shell.execute_reply.started":"2025-10-15T17:55:53.961549Z","shell.execute_reply":"2025-10-15T17:56:08.646389Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"tf.test.is_gpu_available()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-15T17:56:08.648722Z","iopub.execute_input":"2025-10-15T17:56:08.649274Z","iopub.status.idle":"2025-10-15T17:56:09.643160Z","shell.execute_reply.started":"2025-10-15T17:56:08.649254Z","shell.execute_reply":"2025-10-15T17:56:09.642310Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"tf.__version__","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-15T17:56:09.643869Z","iopub.execute_input":"2025-10-15T17:56:09.644163Z","iopub.status.idle":"2025-10-15T17:56:09.687619Z","shell.execute_reply.started":"2025-10-15T17:56:09.644145Z","shell.execute_reply":"2025-10-15T17:56:09.687086Z"}},"outputs":[],"execution_count":null},{"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","trusted":true,"execution":{"iopub.status.busy":"2025-10-15T17:56:09.688548Z","iopub.execute_input":"2025-10-15T17:56:09.688789Z","iopub.status.idle":"2025-10-15T17:56:09.704053Z","shell.execute_reply.started":"2025-10-15T17:56:09.688774Z","shell.execute_reply":"2025-10-15T17:56:09.703363Z"}},"outputs":[],"execution_count":null},{"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","trusted":true,"execution":{"iopub.status.busy":"2025-10-15T17:56:09.705914Z","iopub.execute_input":"2025-10-15T17:56:09.706147Z","iopub.status.idle":"2025-10-15T17:56:09.719451Z","shell.execute_reply.started":"2025-10-15T17:56:09.706133Z","shell.execute_reply":"2025-10-15T17:56:09.718884Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"meta=get_data()\nmeta.head()","metadata":{"id":"tDW7BRph9ehF","outputId":"97de18b5-0a37-4302-8804-8a16a7d2ed2f","trusted":true,"execution":{"iopub.status.busy":"2025-10-15T17:56:09.720190Z","iopub.execute_input":"2025-10-15T17:56:09.720441Z","iopub.status.idle":"2025-10-15T17:56:09.896416Z","shell.execute_reply.started":"2025-10-15T17:56:09.720417Z","shell.execute_reply":"2025-10-15T17:56:09.895757Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"meta.shape","metadata":{"id":"n7FSdDifbZxn","outputId":"5451a127-405a-4c0b-a197-c920b796adbb","trusted":true,"execution":{"iopub.status.busy":"2025-10-15T17:56:09.897183Z","iopub.execute_input":"2025-10-15T17:56:09.897412Z","iopub.status.idle":"2025-10-15T17:56:09.902392Z","shell.execute_reply.started":"2025-10-15T17:56:09.897395Z","shell.execute_reply":"2025-10-15T17:56:09.901762Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"len(meta[meta.label=='FAKE']),len(meta[meta.label=='REAL'])","metadata":{"id":"_FJcz2IthxVG","outputId":"274c3f65-7acb-4f99-8aa9-a5b2a23bf06a","trusted":true,"execution":{"iopub.status.busy":"2025-10-15T17:56:09.903125Z","iopub.execute_input":"2025-10-15T17:56:09.903608Z","iopub.status.idle":"2025-10-15T17:56:09.939224Z","shell.execute_reply.started":"2025-10-15T17:56:09.903584Z","shell.execute_reply":"2025-10-15T17:56:09.938594Z"}},"outputs":[],"execution_count":null},{"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","trusted":true,"execution":{"iopub.status.busy":"2025-10-15T17:56:09.939896Z","iopub.execute_input":"2025-10-15T17:56:09.940164Z","iopub.status.idle":"2025-10-15T17:56:09.967719Z","shell.execute_reply.started":"2025-10-15T17:56:09.940147Z","shell.execute_reply":"2025-10-15T17:56:09.966867Z"}},"outputs":[],"execution_count":null},{"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","trusted":true,"execution":{"iopub.status.busy":"2025-10-15T17:56:09.968590Z","iopub.execute_input":"2025-10-15T17:56:09.968823Z","iopub.status.idle":"2025-10-15T17:56:10.120045Z","shell.execute_reply.started":"2025-10-15T17:56:09.968808Z","shell.execute_reply":"2025-10-15T17:56:10.119357Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"Train_set.shape,Val_set.shape,Test_set.shape","metadata":{"id":"8p-TONijb4qA","outputId":"56d0b529-9d81-4019-d8fa-618c8cdba90f","trusted":true,"execution":{"iopub.status.busy":"2025-10-15T17:56:10.120793Z","iopub.execute_input":"2025-10-15T17:56:10.121095Z","iopub.status.idle":"2025-10-15T17:56:10.126498Z","shell.execute_reply.started":"2025-10-15T17:56:10.121070Z","shell.execute_reply":"2025-10-15T17:56:10.125702Z"}},"outputs":[],"execution_count":null},{"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","trusted":true,"execution":{"iopub.status.busy":"2025-10-15T17:56:12.875852Z","iopub.execute_input":"2025-10-15T17:56:12.876343Z","iopub.status.idle":"2025-10-15T17:56:14.979243Z","shell.execute_reply.started":"2025-10-15T17:56:12.876323Z","shell.execute_reply":"2025-10-15T17:56:14.978135Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Modelling","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","trusted":true,"execution":{"iopub.status.busy":"2025-10-15T17:56:14.981892Z","iopub.execute_input":"2025-10-15T17:56:14.982134Z","iopub.status.idle":"2025-10-15T17:56:14.986984Z","shell.execute_reply.started":"2025-10-15T17:56:14.982118Z","shell.execute_reply":"2025-10-15T17:56:14.986091Z"}},"outputs":[],"execution_count":null},{"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","trusted":true,"execution":{"iopub.status.busy":"2025-10-15T17:56:14.987815Z","iopub.execute_input":"2025-10-15T17:56:14.988052Z","iopub.status.idle":"2025-10-15T17:58:38.605646Z","shell.execute_reply.started":"2025-10-15T17:56:14.988036Z","shell.execute_reply":"2025-10-15T17:58:38.604682Z"}},"outputs":[],"execution_count":null},{"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","trusted":true,"execution":{"iopub.status.busy":"2025-10-15T17:58:38.606485Z","iopub.execute_input":"2025-10-15T17:58:38.606687Z","iopub.status.idle":"2025-10-15T17:58:40.060534Z","shell.execute_reply.started":"2025-10-15T17:58:38.606672Z","shell.execute_reply":"2025-10-15T17:58:40.059966Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.compile(loss=\"binary_crossentropy\", optimizer=\"nadam\",\n              metrics=[\"accuracy\"])\nmodel.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-15T17:58:40.061409Z","iopub.execute_input":"2025-10-15T17:58:40.061702Z","iopub.status.idle":"2025-10-15T17:58:40.089792Z","shell.execute_reply.started":"2025-10-15T17:58:40.061677Z","shell.execute_reply":"2025-10-15T17:58:40.089079Z"}},"outputs":[],"execution_count":null},{"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","trusted":true,"execution":{"iopub.status.busy":"2025-10-15T17:58:40.090760Z","iopub.execute_input":"2025-10-15T17:58:40.091012Z","iopub.status.idle":"2025-10-15T18:03:07.599813Z","shell.execute_reply.started":"2025-10-15T17:58:40.090986Z","shell.execute_reply":"2025-10-15T18:03:07.598981Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"score = model.evaluate(X_test, y_test)","metadata":{"id":"6HDDr4uehast","trusted":true,"execution":{"iopub.status.busy":"2025-10-15T18:03:07.601859Z","iopub.execute_input":"2025-10-15T18:03:07.602135Z","iopub.status.idle":"2025-10-15T18:03:18.976375Z","shell.execute_reply.started":"2025-10-15T18:03:07.602115Z","shell.execute_reply":"2025-10-15T18:03:18.975565Z"}},"outputs":[],"execution_count":null},{"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\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-15T18:03:18.977576Z","iopub.execute_input":"2025-10-15T18:03:18.977980Z","iopub.status.idle":"2025-10-15T18:03:19.209676Z","shell.execute_reply.started":"2025-10-15T18:03:18.977918Z","shell.execute_reply":"2025-10-15T18:03:19.208738Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Pretrained Models for Transfer Learning","metadata":{"id":"hqxnSBJ3pKz8"}},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-15T18:03:19.210618Z","iopub.execute_input":"2025-10-15T18:03:19.210915Z","iopub.status.idle":"2025-10-15T18:03:25.136309Z","shell.execute_reply.started":"2025-10-15T18:03:19.210897Z","shell.execute_reply":"2025-10-15T18:03:25.135396Z"}},"outputs":[],"execution_count":null},{"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","trusted":true,"execution":{"iopub.status.busy":"2025-10-15T18:03:25.137300Z","iopub.execute_input":"2025-10-15T18:03:25.137587Z","iopub.status.idle":"2025-10-15T18:03:26.679186Z","shell.execute_reply.started":"2025-10-15T18:03:25.137564Z","shell.execute_reply":"2025-10-15T18:03:26.678573Z"}},"outputs":[],"execution_count":null},{"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","trusted":true,"execution":{"iopub.status.busy":"2025-10-15T18:03:26.679882Z","iopub.execute_input":"2025-10-15T18:03:26.680180Z","iopub.status.idle":"2025-10-15T18:03:28.151440Z","shell.execute_reply.started":"2025-10-15T18:03:26.680156Z","shell.execute_reply":"2025-10-15T18:03:28.150700Z"}},"outputs":[],"execution_count":null},{"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","trusted":true,"execution":{"iopub.status.busy":"2025-10-15T18:03:28.152156Z","iopub.execute_input":"2025-10-15T18:03:28.152355Z","iopub.status.idle":"2025-10-15T18:03:28.167165Z","shell.execute_reply.started":"2025-10-15T18:03:28.152341Z","shell.execute_reply":"2025-10-15T18:03:28.166352Z"}},"outputs":[],"execution_count":null},{"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","trusted":true,"execution":{"iopub.status.busy":"2025-10-15T18:03:28.167835Z","iopub.execute_input":"2025-10-15T18:03:28.168069Z","iopub.status.idle":"2025-10-15T18:03:31.002840Z","shell.execute_reply.started":"2025-10-15T18:03:28.168053Z","shell.execute_reply":"2025-10-15T18:03:31.001991Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Now let's load the pretrained model, without its top layers, and replace them with our own task","metadata":{"id":"kNL9AOsDpKz-"}},{"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","trusted":true,"execution":{"iopub.status.busy":"2025-10-15T18:03:31.003717Z","iopub.execute_input":"2025-10-15T18:03:31.003998Z","iopub.status.idle":"2025-10-15T18:03:32.767687Z","shell.execute_reply.started":"2025-10-15T18:03:31.003977Z","shell.execute_reply":"2025-10-15T18:03:32.767101Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for layer in base_model.layers:\n    layer.trainable = False","metadata":{"id":"KBlyG6ElpKz-","trusted":true,"execution":{"iopub.status.busy":"2025-10-15T18:03:32.768440Z","iopub.execute_input":"2025-10-15T18:03:32.768673Z","iopub.status.idle":"2025-10-15T18:03:32.773755Z","shell.execute_reply.started":"2025-10-15T18:03:32.768651Z","shell.execute_reply":"2025-10-15T18:03:32.772985Z"}},"outputs":[],"execution_count":null},{"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=3)","metadata":{"id":"GGxK2yPcpKz-","outputId":"6b64214a-e104-4b6c-9b7a-3388fc9aa15f","trusted":true,"execution":{"iopub.status.busy":"2025-10-15T18:03:32.774512Z","iopub.execute_input":"2025-10-15T18:03:32.774742Z","iopub.status.idle":"2025-10-15T18:07:08.767519Z","shell.execute_reply.started":"2025-10-15T18:03:32.774727Z","shell.execute_reply":"2025-10-15T18:07:08.766657Z"}},"outputs":[],"execution_count":null},{"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","trusted":true,"execution":{"iopub.status.busy":"2025-10-15T18:07:08.768523Z","iopub.execute_input":"2025-10-15T18:07:08.768782Z","iopub.status.idle":"2025-10-15T18:07:08.777676Z","shell.execute_reply.started":"2025-10-15T18:07:08.768759Z","shell.execute_reply":"2025-10-15T18:07:08.776986Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.evaluate(test_set)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-15T18:07:08.778386Z","iopub.execute_input":"2025-10-15T18:07:08.778620Z","iopub.status.idle":"2025-10-15T18:07:25.401358Z","shell.execute_reply.started":"2025-10-15T18:07:08.778605Z","shell.execute_reply":"2025-10-15T18:07:25.400695Z"}},"outputs":[],"execution_count":null},{"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=20)","metadata":{"id":"GEUNGlhvpKz_","outputId":"c622a91d-f634-4443-b87e-8d46defdb578","trusted":true,"execution":{"iopub.status.busy":"2025-10-15T18:07:25.402116Z","iopub.execute_input":"2025-10-15T18:07:25.402328Z","iopub.status.idle":"2025-10-15T18:46:25.926563Z","shell.execute_reply.started":"2025-10-15T18:07:25.402312Z","shell.execute_reply":"2025-10-15T18:46:25.925884Z"}},"outputs":[],"execution_count":null},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-15T18:46:25.927559Z","iopub.execute_input":"2025-10-15T18:46:25.927794Z","iopub.status.idle":"2025-10-15T18:46:26.336804Z","shell.execute_reply.started":"2025-10-15T18:46:25.927773Z","shell.execute_reply":"2025-10-15T18:46:26.335985Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.evaluate(test_set)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-15T18:46:26.337675Z","iopub.execute_input":"2025-10-15T18:46:26.337921Z","iopub.status.idle":"2025-10-15T18:46:42.742690Z","shell.execute_reply.started":"2025-10-15T18:46:26.337904Z","shell.execute_reply":"2025-10-15T18:46:42.742030Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.save('xception_deepfake_image.h5')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-15T18:46:42.743397Z","iopub.execute_input":"2025-10-15T18:46:42.743663Z","iopub.status.idle":"2025-10-15T18:46:43.298049Z","shell.execute_reply.started":"2025-10-15T18:46:42.743636Z","shell.execute_reply":"2025-10-15T18:46:43.297225Z"}},"outputs":[],"execution_count":null}]}