{"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":"gpu","dataSources":[{"sourceId":924245,"sourceType":"datasetVersion","datasetId":464091}],"dockerImageVersionId":29845,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"!pip install -U --upgrade tensorflow","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-04T04:39:01.165242Z","iopub.execute_input":"2025-02-04T04:39:01.165437Z","iopub.status.idle":"2025-02-04T04:40:21.745549Z","shell.execute_reply.started":"2025-02-04T04:39:01.165402Z","shell.execute_reply":"2025-02-04T04:40:21.744824Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import tensorflow as tf\nprint(tf.__version__)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-04T04:40:21.748102Z","iopub.execute_input":"2025-02-04T04:40:21.748379Z","iopub.status.idle":"2025-02-04T04:40:24.082379Z","shell.execute_reply.started":"2025-02-04T04:40:21.748324Z","shell.execute_reply":"2025-02-04T04:40:24.081523Z"}},"outputs":[],"execution_count":null},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-04T04:40:24.084284Z","iopub.execute_input":"2025-02-04T04:40:24.084523Z","iopub.status.idle":"2025-02-04T04:40:25.423077Z","shell.execute_reply.started":"2025-02-04T04:40:24.084472Z","shell.execute_reply":"2025-02-04T04:40:25.422328Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install plotly","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-04T04:40:25.424804Z","iopub.execute_input":"2025-02-04T04:40:25.425144Z","iopub.status.idle":"2025-02-04T04:40:30.193758Z","shell.execute_reply.started":"2025-02-04T04:40:25.425085Z","shell.execute_reply":"2025-02-04T04:40:30.193046Z"}},"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-04T04:40:30.195628Z","iopub.execute_input":"2025-02-04T04:40:30.195987Z","iopub.status.idle":"2025-02-04T04:40:30.201414Z","shell.execute_reply.started":"2025-02-04T04:40:30.195922Z","shell.execute_reply":"2025-02-04T04:40:30.200756Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\n\ndef get_data():\n    return pd.read_csv('../input/deepfake-faces/metadata.csv')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-04T04:40:30.203263Z","iopub.execute_input":"2025-02-04T04:40:30.203696Z","iopub.status.idle":"2025-02-04T04:40:30.218483Z","shell.execute_reply.started":"2025-02-04T04:40:30.203629Z","shell.execute_reply":"2025-02-04T04:40:30.217744Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"meta=get_data()\nmeta.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-04T04:40:30.219748Z","iopub.execute_input":"2025-02-04T04:40:30.219969Z","iopub.status.idle":"2025-02-04T04:40:30.402272Z","shell.execute_reply.started":"2025-02-04T04:40:30.219933Z","shell.execute_reply":"2025-02-04T04:40:30.401320Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"meta.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-04T04:40:30.403522Z","iopub.execute_input":"2025-02-04T04:40:30.403783Z","iopub.status.idle":"2025-02-04T04:40:30.408330Z","shell.execute_reply.started":"2025-02-04T04:40:30.403734Z","shell.execute_reply":"2025-02-04T04:40:30.407741Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"len(meta[meta.label=='FAKE']),len(meta[meta.label=='REAL'])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-04T04:40:30.409722Z","iopub.execute_input":"2025-02-04T04:40:30.409977Z","iopub.status.idle":"2025-02-04T04:40:30.442789Z","shell.execute_reply.started":"2025-02-04T04:40:30.409923Z","shell.execute_reply":"2025-02-04T04:40:30.441943Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"real_df = meta[meta[\"label\"] == \"REAL\"]\nfake_df = meta[meta[\"label\"] == \"FAKE\"]\nsample_size = 16293\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":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-04T04:40:30.444105Z","iopub.execute_input":"2025-02-04T04:40:30.444357Z","iopub.status.idle":"2025-02-04T04:40:30.480488Z","shell.execute_reply.started":"2025-02-04T04:40:30.444305Z","shell.execute_reply":"2025-02-04T04:40:30.479901Z"}},"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-04T04:40:30.481715Z","iopub.execute_input":"2025-02-04T04:40:30.481918Z","iopub.status.idle":"2025-02-04T04:40:31.259746Z","shell.execute_reply.started":"2025-02-04T04:40:30.481882Z","shell.execute_reply":"2025-02-04T04:40:31.258656Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"Train_set.shape,Val_set.shape,Test_set.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-04T04:40:31.261431Z","iopub.execute_input":"2025-02-04T04:40:31.261765Z","iopub.status.idle":"2025-02-04T04:40:31.279007Z","shell.execute_reply.started":"2025-02-04T04:40:31.261704Z","shell.execute_reply":"2025-02-04T04:40:31.277845Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\ny = 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":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-04T04:40:31.280597Z","iopub.execute_input":"2025-02-04T04:40:31.280979Z","iopub.status.idle":"2025-02-04T04:40:35.551284Z","shell.execute_reply.started":"2025-02-04T04:40:31.280912Z","shell.execute_reply":"2025-02-04T04:40:35.550490Z"}},"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    # Construct the image path using os.path.join to ensure correct path resolution\n    image_path = os.path.join('../input/deepfake-faces/faces_224/', Train_set.loc[i,'videoname'][:-4] + '.jpg')\n\n    # Check if the image file exists\n    if os.path.exists(image_path):\n        img = cv2.imread(image_path)\n\n        # Check if the image was loaded successfully\n        if img is not None:\n            plt.imshow(img)\n        else:\n            print(f\"Warning: Could not load image at path: {image_path}\")\n    else:\n        print(f\"Warning: Image file does not exist at path: {image_path}\")\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":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-04T04:40:35.552554Z","iopub.execute_input":"2025-02-04T04:40:35.552785Z","iopub.status.idle":"2025-02-04T04:40:37.345666Z","shell.execute_reply.started":"2025-02-04T04:40:35.552747Z","shell.execute_reply":"2025-02-04T04:40:37.344623Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\n\ndef retreive_dataset(set_name):\n    images,labels=[],[]\n    for (img, imclass) in zip(set_name['videoname'], set_name['label']):\n        # Construct the image path using os.path.join\n        image_path = os.path.join('../input/deepfake-faces/faces_224/', img[:-4] + '.jpg')\n\n        # Check if the image file exists before attempting to load it\n        if os.path.exists(image_path):\n            image = cv2.imread(image_path)\n\n            # Check if the image was loaded successfully\n            if image is not None:\n                images.append(image)\n                if(imclass=='FAKE'):\n                    labels.append(1)\n                else:\n                    labels.append(0)\n            else:\n                print(f\"Warning: Could not load image at path: {image_path}\")\n        else:\n            print(f\"Warning: Image file does not exist at path: {image_path}\")\n\n    return np.array(images),np.array(labels)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-04T04:40:37.347040Z","iopub.execute_input":"2025-02-04T04:40:37.347321Z","iopub.status.idle":"2025-02-04T04:40:37.357373Z","shell.execute_reply.started":"2025-02-04T04:40:37.347274Z","shell.execute_reply":"2025-02-04T04:40:37.356586Z"}},"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-04T04:40:37.358915Z","iopub.execute_input":"2025-02-04T04:40:37.359185Z","iopub.status.idle":"2025-02-04T04:46:13.457270Z","shell.execute_reply.started":"2025-02-04T04:40:37.359139Z","shell.execute_reply":"2025-02-04T04:46:13.456293Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(X_train.shape, y_train.shape)\nprint(X_val.shape, y_val.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-04T04:46:13.461464Z","iopub.execute_input":"2025-02-04T04:46:13.461726Z","iopub.status.idle":"2025-02-04T04:46:13.466371Z","shell.execute_reply.started":"2025-02-04T04:46:13.461672Z","shell.execute_reply":"2025-02-04T04:46:13.465467Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from functools import partial\n\ntf.random.set_seed(42)\n# Create the convolutional layer with default parameters\nDefaultConv2D = partial(tf.keras.layers.Conv2D, kernel_size=3, padding=\"same\",\n                       kernel_initializer=\"he_normal\")\n\n\nmodel = tf.keras.Sequential([\n    tf.keras.Input(shape=(224, 224, 3)),\n    DefaultConv2D(filters=32),\n    tf.keras.layers.BatchNormalization(),\n    tf.keras.layers.Activation(\"relu\"),\n    tf.keras.layers.MaxPool2D(),\n\n    DefaultConv2D(filters=64),\n    tf.keras.layers.BatchNormalization(),\n    tf.keras.layers.Activation(\"relu\"),\n    tf.keras.layers.MaxPool2D(),\n\n    DefaultConv2D(filters=128),\n    tf.keras.layers.BatchNormalization(),\n    tf.keras.layers.Activation(\"relu\"),\n    tf.keras.layers.MaxPool2D(),\n\n    DefaultConv2D(filters=256), # Increased filters\n    tf.keras.layers.BatchNormalization(),\n    tf.keras.layers.Activation(\"relu\"),\n    tf.keras.layers.MaxPool2D(),\n\n    DefaultConv2D(filters=512), # Increased filters\n    tf.keras.layers.BatchNormalization(),\n    tf.keras.layers.Activation(\"relu\"),\n\n    tf.keras.layers.GlobalAveragePooling2D(),\n    tf.keras.layers.Dense(units=256, activation=\"relu\", kernel_initializer=\"he_normal\"), # Increased units\n    tf.keras.layers.Dropout(0.5),\n    tf.keras.layers.Dense(units=128, activation=\"relu\", kernel_initializer=\"he_normal\"), # Increased units\n    tf.keras.layers.Dropout(0.5),\n    tf.keras.layers.Dense(units=1, activation=\"sigmoid\")\n])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-04T04:46:13.467659Z","iopub.execute_input":"2025-02-04T04:46:13.467882Z","iopub.status.idle":"2025-02-04T04:46:13.909361Z","shell.execute_reply.started":"2025-02-04T04:46:13.467827Z","shell.execute_reply":"2025-02-04T04:46:13.908322Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Compile the model\n\nmodel.compile(loss=\"binary_crossentropy\", \n              optimizer=tf.keras.optimizers.Adam(learning_rate=0.0001),  # Tuned learning rate\n              metrics=[\"accuracy\"])\nmodel.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-04T04:46:13.911099Z","iopub.execute_input":"2025-02-04T04:46:13.911408Z","iopub.status.idle":"2025-02-04T04:46:13.949876Z","shell.execute_reply.started":"2025-02-04T04:46:13.911350Z","shell.execute_reply":"2025-02-04T04:46:13.949018Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"early_stopping = tf.keras.callbacks.EarlyStopping(patience=5, restore_best_weights=True) # Increased patience\nlr_scheduler = tf.keras.callbacks.ReduceLROnPlateau(factor=0.5, patience=3, verbose=1) # Increased patience\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-04T04:46:13.951174Z","iopub.execute_input":"2025-02-04T04:46:13.951554Z","iopub.status.idle":"2025-02-04T04:46:13.956340Z","shell.execute_reply.started":"2025-02-04T04:46:13.951431Z","shell.execute_reply":"2025-02-04T04:46:13.955656Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\n\ndatagen = ImageDataGenerator(\n    rotation_range=20,\n    width_shift_range=0.2,\n    height_shift_range=0.2,\n    shear_range=0.2,\n    zoom_range=0.2,\n    horizontal_flip=True,\n    fill_mode='nearest'  # How to fill newly created pixels\n)\ndatagen.fit(X_train)  # Fit the augmentation on training data","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-04T04:46:13.957478Z","iopub.execute_input":"2025-02-04T04:46:13.957734Z","iopub.status.idle":"2025-02-04T04:46:30.469756Z","shell.execute_reply.started":"2025-02-04T04:46:13.957675Z","shell.execute_reply":"2025-02-04T04:46:30.469071Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\n\n# Use flow from generator in model.fit\nhistory = model.fit(datagen.flow(X_train, y_train, batch_size=32),  # Use datagen.flow\n                    epochs=10,\n                    validation_data=(X_val, y_val),\n                    callbacks=[early_stopping, lr_scheduler])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-04T04:46:30.470857Z","iopub.execute_input":"2025-02-04T04:46:30.471063Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"score = model.evaluate(X_test, y_test)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Save the model\nmodel.save('/kaggle/working/my_model1.h5')  # Saves in HDF5 format\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow import keras\n\n# Load the model\nmodel = keras.models.load_model('/kaggle/working/my_model1.h5')\n\n# Check the model summary to confirm it loaded correctly\nmodel.summary()\n","metadata":{"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')\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"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},"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":{"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":{"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":{"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":{"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":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for layer in base_model.layers:\n    layer.trainable = False","metadata":{"trusted":true},"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":{"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":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.evaluate(test_set)","metadata":{"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":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"acc = 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},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.evaluate(test_set)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.save('/kaggle/working/new_model_using_Xception.h5')","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install lime","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from lime import lime_image\n\nexplainer = lime_image.LimeImageExplainer()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"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[index] + 1) / 2)  # rescale to 0–1 for imshow()\n    if(y[index]==1):\n        classt='FAKE'\n    else:\n        classt='REAL'\n    plt.title(f\"Class: {classt}\")\n    plt.axis(\"off\")\n\nplt.show()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_data=x[2,:,:,:]\ntest_data.shape","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"explanation = explainer.explain_instance(test_data.astype('double'), model.predict,  \n                                         top_labels=3, hide_color=0, num_samples=1000","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"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":{"trusted":true},"outputs":[],"execution_count":null}]}