{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.6.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":924245,"sourceType":"datasetVersion","datasetId":464091}],"dockerImageVersionId":29844,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"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":"2025-06-07T16:18:27.060260Z","iopub.execute_input":"2025-06-07T16:18:27.060691Z","iopub.status.idle":"2025-06-07T16:18:36.734888Z","shell.execute_reply.started":"2025-06-07T16:18:27.060628Z","shell.execute_reply":"2025-06-07T16:18:36.733646Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"tf.test.is_gpu_available()\nstrategy = tf.distribute.MirroredStrategy()\nprint('DEVICES AVAILABLE: {}'.format(strategy.num_replicas_in_sync))","metadata":{"execution":{"iopub.status.busy":"2025-06-07T16:18:39.779144Z","iopub.execute_input":"2025-06-07T16:18:39.779518Z","iopub.status.idle":"2025-06-07T16:18:39.826088Z","shell.execute_reply.started":"2025-06-07T16:18:39.779453Z","shell.execute_reply":"2025-06-07T16:18:39.824846Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"tf.__version__","metadata":{"execution":{"iopub.status.busy":"2025-06-07T16:18:47.580401Z","iopub.execute_input":"2025-06-07T16:18:47.580724Z","iopub.status.idle":"2025-06-07T16:18:47.588695Z","shell.execute_reply.started":"2025-06-07T16:18:47.580679Z","shell.execute_reply":"2025-06-07T16:18:47.587491Z"},"trusted":true},"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","execution":{"iopub.status.busy":"2025-06-07T16:18:50.494336Z","iopub.execute_input":"2025-06-07T16:18:50.494682Z","iopub.status.idle":"2025-06-07T16:18:50.500710Z","shell.execute_reply.started":"2025-06-07T16:18:50.494633Z","shell.execute_reply":"2025-06-07T16:18:50.499384Z"},"trusted":true},"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","execution":{"iopub.status.busy":"2025-06-07T16:18:58.060705Z","iopub.execute_input":"2025-06-07T16:18:58.061033Z","iopub.status.idle":"2025-06-07T16:18:58.065693Z","shell.execute_reply.started":"2025-06-07T16:18:58.060985Z","shell.execute_reply":"2025-06-07T16:18:58.064533Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"meta=get_data()\nmeta.head()","metadata":{"id":"tDW7BRph9ehF","outputId":"97de18b5-0a37-4302-8804-8a16a7d2ed2f","execution":{"iopub.status.busy":"2025-06-07T16:19:06.735380Z","iopub.execute_input":"2025-06-07T16:19:06.735704Z","iopub.status.idle":"2025-06-07T16:19:06.952121Z","shell.execute_reply.started":"2025-06-07T16:19:06.735653Z","shell.execute_reply":"2025-06-07T16:19:06.951071Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"meta.shape","metadata":{"id":"n7FSdDifbZxn","outputId":"5451a127-405a-4c0b-a197-c920b796adbb","execution":{"iopub.status.busy":"2025-06-07T16:19:09.574705Z","iopub.execute_input":"2025-06-07T16:19:09.575095Z","iopub.status.idle":"2025-06-07T16:19:09.583631Z","shell.execute_reply.started":"2025-06-07T16:19:09.575026Z","shell.execute_reply":"2025-06-07T16:19:09.581754Z"},"trusted":true},"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","execution":{"iopub.status.busy":"2025-06-07T16:19:11.239534Z","iopub.execute_input":"2025-06-07T16:19:11.239903Z","iopub.status.idle":"2025-06-07T16:19:11.280068Z","shell.execute_reply.started":"2025-06-07T16:19:11.239834Z","shell.execute_reply":"2025-06-07T16:19:11.278915Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"real_df = meta[meta[\"label\"] == \"REAL\"]\nfake_df = meta[meta[\"label\"] == \"FAKE\"]\nsample_size = 42000\nfake_df = fake_df.sample(sample_size, random_state=42)\nsample_meta = pd.concat([real_df, fake_df])","metadata":{"id":"IgMfzY-PjjtH","execution":{"iopub.status.busy":"2025-06-07T16:33:39.602886Z","iopub.execute_input":"2025-06-07T16:33:39.603345Z","iopub.status.idle":"2025-06-07T16:33:39.659039Z","shell.execute_reply.started":"2025-06-07T16:33:39.603272Z","shell.execute_reply":"2025-06-07T16:33:39.657927Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"fake_df.shape, real_df.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-07T16:33:41.801646Z","iopub.execute_input":"2025-06-07T16:33:41.801966Z","iopub.status.idle":"2025-06-07T16:33:41.808641Z","shell.execute_reply.started":"2025-06-07T16:33:41.801919Z","shell.execute_reply":"2025-06-07T16:33:41.807672Z"}},"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.15,random_state=42,stratify=Train_set['label'])","metadata":{"id":"5eB86S6K-T5Z","execution":{"iopub.status.busy":"2025-06-07T16:33:43.861069Z","iopub.execute_input":"2025-06-07T16:33:43.861983Z","iopub.status.idle":"2025-06-07T16:33:44.006668Z","shell.execute_reply.started":"2025-06-07T16:33:43.861726Z","shell.execute_reply":"2025-06-07T16:33:44.005465Z"},"trusted":true},"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","execution":{"iopub.status.busy":"2025-06-07T16:33:45.461940Z","iopub.execute_input":"2025-06-07T16:33:45.462279Z","iopub.status.idle":"2025-06-07T16:33:45.469251Z","shell.execute_reply.started":"2025-06-07T16:33:45.462231Z","shell.execute_reply":"2025-06-07T16:33:45.468220Z"},"trusted":true},"outputs":[],"execution_count":null},{"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":"2025-06-07T16:22:21.099937Z","iopub.execute_input":"2025-06-07T16:22:21.100379Z","iopub.status.idle":"2025-06-07T16:22:21.451563Z","shell.execute_reply.started":"2025-06-07T16:22:21.100282Z","shell.execute_reply":"2025-06-07T16:22:21.450633Z"},"trusted":true},"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","execution":{"iopub.status.busy":"2025-06-07T16:22:36.460474Z","iopub.execute_input":"2025-06-07T16:22:36.460813Z","iopub.status.idle":"2025-06-07T16:22:37.082857Z","shell.execute_reply.started":"2025-06-07T16:22:36.460765Z","shell.execute_reply":"2025-06-07T16:22:37.081025Z"},"trusted":true},"outputs":[],"execution_count":null},{"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":"2025-01-26T10:00:02.056649Z","iopub.execute_input":"2025-01-26T10:00:02.056992Z","iopub.status.idle":"2025-01-26T10:00:02.064110Z","shell.execute_reply.started":"2025-01-26T10:00:02.056944Z","shell.execute_reply":"2025-01-26T10:00:02.062794Z"},"trusted":true},"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","execution":{"iopub.status.busy":"2025-01-26T10:00:02.807193Z","iopub.execute_input":"2025-01-26T10:00:02.807560Z"},"trusted":true},"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","execution":{"iopub.status.busy":"2024-09-18T05:22:43.964173Z","iopub.status.idle":"2024-09-18T05:22:43.964563Z","shell.execute_reply.started":"2024-09-18T05:22:43.964366Z","shell.execute_reply":"2024-09-18T05:22:43.964385Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.compile(loss=\"binary_crossentropy\", optimizer=\"nadam\",\n              metrics=[\"accuracy\"])\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2024-09-18T05:08:07.832352Z","iopub.execute_input":"2024-09-18T05:08:07.832685Z","iopub.status.idle":"2024-09-18T05:08:07.877516Z","shell.execute_reply.started":"2024-09-18T05:08:07.832625Z","shell.execute_reply":"2024-09-18T05:08:07.876713Z"},"trusted":true},"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","execution":{"iopub.status.busy":"2024-09-18T05:08:07.878902Z","iopub.execute_input":"2024-09-18T05:08:07.879401Z","iopub.status.idle":"2024-09-18T05:12:45.987251Z","shell.execute_reply.started":"2024-09-18T05:08:07.879156Z","shell.execute_reply":"2024-09-18T05:12:45.986494Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"score = model.evaluate(X_test, y_test)","metadata":{"id":"6HDDr4uehast","execution":{"iopub.status.busy":"2024-09-18T05:12:50.290015Z","iopub.execute_input":"2024-09-18T05:12:50.290336Z","iopub.status.idle":"2024-09-18T05:12:57.388635Z","shell.execute_reply.started":"2024-09-18T05:12:50.290288Z","shell.execute_reply":"2024-09-18T05:12:57.387957Z"},"trusted":true},"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":{"execution":{"iopub.status.busy":"2024-09-18T05:15:44.718367Z","iopub.execute_input":"2024-09-18T05:15:44.718688Z","iopub.status.idle":"2024-09-18T05:15:45.495327Z","shell.execute_reply.started":"2024-09-18T05:15:44.718644Z","shell.execute_reply":"2024-09-18T05:15:45.494290Z"},"trusted":true},"outputs":[],"execution_count":null},{"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-09-19T02:49:12.091630Z","iopub.execute_input":"2024-09-19T02:49:12.092029Z","iopub.status.idle":"2024-09-19T02:49:12.150153Z","shell.execute_reply.started":"2024-09-19T02:49:12.091979Z","shell.execute_reply":"2024-09-19T02:49:12.149191Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"tf.keras.backend.clear_session()  # extra code – resets layer name counter\n\nbatch_size_per_replica = 32\nbatch_size = batch_size_per_replica\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-09-19T02:49:46.700522Z","iopub.execute_input":"2024-09-19T02:49:46.700894Z","iopub.status.idle":"2024-09-19T02:49:46.965030Z","shell.execute_reply.started":"2024-09-19T02:49:46.700843Z","shell.execute_reply":"2024-09-19T02:49:46.963897Z"},"trusted":true},"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","execution":{"iopub.status.busy":"2024-09-18T09:54:00.581686Z","iopub.execute_input":"2024-09-18T09:54:00.582020Z","iopub.status.idle":"2024-09-18T09:54:02.252192Z","shell.execute_reply.started":"2024-09-18T09:54:00.581986Z","shell.execute_reply":"2024-09-18T09:54:02.251150Z"},"trusted":true},"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","execution":{"iopub.status.busy":"2024-09-18T09:54:02.253462Z","iopub.execute_input":"2024-09-18T09:54:02.253835Z","iopub.status.idle":"2024-09-18T09:54:02.278898Z","shell.execute_reply.started":"2024-09-18T09:54:02.253772Z","shell.execute_reply":"2024-09-18T09:54:02.277912Z"},"trusted":true},"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","execution":{"iopub.status.busy":"2024-09-18T09:54:02.280161Z","iopub.execute_input":"2024-09-18T09:54:02.280502Z","iopub.status.idle":"2024-09-18T09:54:05.268934Z","shell.execute_reply.started":"2024-09-18T09:54:02.280464Z","shell.execute_reply":"2024-09-18T09:54:05.268015Z"},"trusted":true},"outputs":[],"execution_count":null},{"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-09-30T17:34:48.368690Z","iopub.execute_input":"2024-09-30T17:34:48.369029Z","iopub.status.idle":"2024-09-30T17:34:48.456789Z","shell.execute_reply.started":"2024-09-30T17:34:48.368975Z","shell.execute_reply":"2024-09-30T17:34:48.455377Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for layer in base_model.layers:\n    layer.trainable = False","metadata":{"id":"KBlyG6ElpKz-","execution":{"iopub.status.busy":"2024-09-18T09:54:07.271600Z","iopub.execute_input":"2024-09-18T09:54:07.271947Z","iopub.status.idle":"2024-09-18T09:54:07.279112Z","shell.execute_reply.started":"2024-09-18T09:54:07.271914Z","shell.execute_reply":"2024-09-18T09:54:07.278242Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"optimizer = tf.keras.optimizers.SGD(learning_rate=0.1, momentum=0.9)\nwith strategy.scope():\n    model.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","execution":{"iopub.status.busy":"2024-09-18T09:54:07.280388Z","iopub.execute_input":"2024-09-18T09:54:07.280779Z","iopub.status.idle":"2024-09-18T10:02:40.782755Z","shell.execute_reply.started":"2024-09-18T09:54:07.280736Z","shell.execute_reply":"2024-09-18T10:02:40.781735Z"},"trusted":true},"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},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.evaluate(test_set)","metadata":{"execution":{"iopub.status.busy":"2024-09-18T10:02:40.785541Z","iopub.execute_input":"2024-09-18T10:02:40.785903Z","iopub.status.idle":"2024-09-18T10:04:03.911814Z","shell.execute_reply.started":"2024-09-18T10:02:40.785868Z","shell.execute_reply":"2024-09-18T10:04:03.910800Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Assuming 'dataset' is your BatchDataset object\nfor images, labels in test_set.take(4):  # Takes the first batch\n    print(\"Image batch shape:\", images.shape)\n    print(\"Label batch shape:\", labels.shape)\n    print(\"Image batch dtype:\", images.dtype)\n    print(\"Label batch dtype:\", labels.dtype)\n\n    # Optionally visualize the first image in the batch (using matplotlib)\n    import matplotlib.pyplot as plt\n\n    plt.imshow(images[0].numpy().astype(\"uint8\"))  # Convert to numpy and cast to uint8\n    plt.title(f\"Label: {labels[0].numpy()}\")\n    plt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-09-19T02:52:25.916853Z","iopub.execute_input":"2024-09-19T02:52:25.917215Z","iopub.status.idle":"2024-09-19T02:52:26.128274Z","shell.execute_reply.started":"2024-09-19T02:52:25.917162Z","shell.execute_reply":"2024-09-19T02:52:26.127104Z"},"trusted":true},"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=10)","metadata":{"id":"GEUNGlhvpKz_","outputId":"c622a91d-f634-4443-b87e-8d46defdb578","execution":{"iopub.status.busy":"2024-09-18T10:33:51.849265Z","iopub.execute_input":"2024-09-18T10:33:51.850372Z","iopub.status.idle":"2024-09-18T11:28:35.657400Z","shell.execute_reply.started":"2024-09-18T10:33:51.850315Z","shell.execute_reply":"2024-09-18T11:28:35.656268Z"},"trusted":true},"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":{"execution":{"iopub.status.busy":"2024-09-18T11:28:35.659475Z","iopub.execute_input":"2024-09-18T11:28:35.659866Z","iopub.status.idle":"2024-09-18T11:28:36.275921Z","shell.execute_reply.started":"2024-09-18T11:28:35.659821Z","shell.execute_reply":"2024-09-18T11:28:36.274967Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.evaluate(test_set)","metadata":{"execution":{"iopub.status.busy":"2024-09-18T11:28:36.277013Z","iopub.execute_input":"2024-09-18T11:28:36.277308Z","iopub.status.idle":"2024-09-18T11:29:17.321487Z","shell.execute_reply.started":"2024-09-18T11:28:36.277275Z","shell.execute_reply":"2024-09-18T11:29:17.320528Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.save('xception_deepfake_image_3o.h5')","metadata":{"execution":{"iopub.status.busy":"2024-09-18T11:29:38.875932Z","iopub.execute_input":"2024-09-18T11:29:38.876348Z","iopub.status.idle":"2024-09-18T11:29:39.463027Z","shell.execute_reply.started":"2024-09-18T11:29:38.876310Z","shell.execute_reply":"2024-09-18T11:29:39.461955Z"},"trusted":true},"outputs":[],"execution_count":null}]}