{"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":16880,"databundleVersionId":858837,"sourceType":"competition"},{"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":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_kg_hide-input":true,"_kg_hide-output":true,"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T00:41:49.527166Z","iopub.execute_input":"2024-11-05T00:41:49.52765Z","iopub.status.idle":"2024-11-05T00:41:49.534671Z","shell.execute_reply.started":"2024-11-05T00:41:49.527573Z","shell.execute_reply":"2024-11-05T00:41:49.533497Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"dataset_path = '/kaggle/input/deepfake-faces/metadata.csv'","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T00:41:49.536926Z","iopub.execute_input":"2024-11-05T00:41:49.537273Z","iopub.status.idle":"2024-11-05T00:41:49.555806Z","shell.execute_reply.started":"2024-11-05T00:41:49.537211Z","shell.execute_reply":"2024-11-05T00:41:49.554653Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df = pd.read_csv(dataset_path)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T00:41:49.557769Z","iopub.execute_input":"2024-11-05T00:41:49.5582Z","iopub.status.idle":"2024-11-05T00:41:49.709168Z","shell.execute_reply.started":"2024-11-05T00:41:49.558125Z","shell.execute_reply":"2024-11-05T00:41:49.708036Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T00:41:49.712826Z","iopub.execute_input":"2024-11-05T00:41:49.713284Z","iopub.status.idle":"2024-11-05T00:41:49.732082Z","shell.execute_reply.started":"2024-11-05T00:41:49.713208Z","shell.execute_reply":"2024-11-05T00:41:49.730858Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.tail()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T00:41:49.734738Z","iopub.execute_input":"2024-11-05T00:41:49.735187Z","iopub.status.idle":"2024-11-05T00:41:49.757693Z","shell.execute_reply.started":"2024-11-05T00:41:49.735106Z","shell.execute_reply":"2024-11-05T00:41:49.756418Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T00:41:49.759548Z","iopub.execute_input":"2024-11-05T00:41:49.759996Z","iopub.status.idle":"2024-11-05T00:41:49.774286Z","shell.execute_reply.started":"2024-11-05T00:41:49.759921Z","shell.execute_reply":"2024-11-05T00:41:49.772797Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.columns","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T00:41:49.776316Z","iopub.execute_input":"2024-11-05T00:41:49.776748Z","iopub.status.idle":"2024-11-05T00:41:49.788462Z","shell.execute_reply.started":"2024-11-05T00:41:49.77668Z","shell.execute_reply":"2024-11-05T00:41:49.78739Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.duplicated().sum()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T00:41:49.790189Z","iopub.execute_input":"2024-11-05T00:41:49.790614Z","iopub.status.idle":"2024-11-05T00:41:49.859621Z","shell.execute_reply.started":"2024-11-05T00:41:49.790548Z","shell.execute_reply":"2024-11-05T00:41:49.858731Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.isnull().sum()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T00:41:49.861464Z","iopub.execute_input":"2024-11-05T00:41:49.861831Z","iopub.status.idle":"2024-11-05T00:41:49.905263Z","shell.execute_reply.started":"2024-11-05T00:41:49.861768Z","shell.execute_reply":"2024-11-05T00:41:49.903718Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.info()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T00:41:49.907178Z","iopub.execute_input":"2024-11-05T00:41:49.907575Z","iopub.status.idle":"2024-11-05T00:41:49.954096Z","shell.execute_reply.started":"2024-11-05T00:41:49.9075Z","shell.execute_reply":"2024-11-05T00:41:49.953113Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.nunique()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T00:41:49.959775Z","iopub.execute_input":"2024-11-05T00:41:49.960225Z","iopub.status.idle":"2024-11-05T00:41:50.059173Z","shell.execute_reply.started":"2024-11-05T00:41:49.960146Z","shell.execute_reply":"2024-11-05T00:41:50.057998Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"object_columns = df.select_dtypes(include=['object']).columns\nprint(\"Object type columns:\")\nprint(object_columns)\n\nnumerical_columns = df.select_dtypes(include=['int64', 'float64']).columns\nprint(\"\\nNumerical type columns:\")\nprint(numerical_columns)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T00:41:50.064203Z","iopub.execute_input":"2024-11-05T00:41:50.064664Z","iopub.status.idle":"2024-11-05T00:41:50.086724Z","shell.execute_reply.started":"2024-11-05T00:41:50.064601Z","shell.execute_reply":"2024-11-05T00:41:50.085588Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def classify_features(df):\n    categorical_features = []\n    non_categorical_features = []\n    discrete_features = []\n    continuous_features = []\n\n    for column in df.columns:\n        if df[column].dtype == 'object':\n            if df[column].nunique() < 10:\n                categorical_features.append(column)\n            else:\n                non_categorical_features.append(column)\n        elif df[column].dtype in ['int64', 'float64']:\n            if df[column].nunique() < 10:\n                discrete_features.append(column)\n            else:\n                continuous_features.append(column)\n\n    return categorical_features, non_categorical_features, discrete_features, continuous_features","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T00:41:50.088585Z","iopub.execute_input":"2024-11-05T00:41:50.088998Z","iopub.status.idle":"2024-11-05T00:41:50.100575Z","shell.execute_reply.started":"2024-11-05T00:41:50.088927Z","shell.execute_reply":"2024-11-05T00:41:50.099288Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"categorical, non_categorical, discrete, continuous = classify_features(df)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T00:41:50.102771Z","iopub.execute_input":"2024-11-05T00:41:50.103202Z","iopub.status.idle":"2024-11-05T00:41:50.168853Z","shell.execute_reply.started":"2024-11-05T00:41:50.103135Z","shell.execute_reply":"2024-11-05T00:41:50.167682Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(\"Categorical Features:\", categorical)\nprint(\"Non-Categorical Features:\", non_categorical)\nprint(\"Discrete Features:\", discrete)\nprint(\"Continuous Features:\", continuous)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T00:41:50.17046Z","iopub.execute_input":"2024-11-05T00:41:50.170822Z","iopub.status.idle":"2024-11-05T00:41:50.179013Z","shell.execute_reply.started":"2024-11-05T00:41:50.170768Z","shell.execute_reply":"2024-11-05T00:41:50.177633Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df = df.fillna(\"Not Available\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T00:41:50.180766Z","iopub.execute_input":"2024-11-05T00:41:50.181099Z","iopub.status.idle":"2024-11-05T00:41:50.235522Z","shell.execute_reply.started":"2024-11-05T00:41:50.181046Z","shell.execute_reply":"2024-11-05T00:41:50.2342Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for i in categorical:\n    print(i,':', df[i].unique())\n    print()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T00:41:50.237807Z","iopub.execute_input":"2024-11-05T00:41:50.23826Z","iopub.status.idle":"2024-11-05T00:41:50.253243Z","shell.execute_reply.started":"2024-11-05T00:41:50.23818Z","shell.execute_reply":"2024-11-05T00:41:50.251607Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for i in categorical:\n    print(df[i].value_counts())\n    print()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T00:41:50.255842Z","iopub.execute_input":"2024-11-05T00:41:50.256223Z","iopub.status.idle":"2024-11-05T00:41:50.294764Z","shell.execute_reply.started":"2024-11-05T00:41:50.256159Z","shell.execute_reply":"2024-11-05T00:41:50.293532Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np \nimport pandas as pd \nimport matplotlib.pyplot as plt\nimport seaborn as sns","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T00:41:50.296682Z","iopub.execute_input":"2024-11-05T00:41:50.297Z","iopub.status.idle":"2024-11-05T00:41:50.311137Z","shell.execute_reply.started":"2024-11-05T00:41:50.296948Z","shell.execute_reply":"2024-11-05T00:41:50.309816Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import warnings\nwarnings.filterwarnings('ignore')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T00:41:50.31305Z","iopub.execute_input":"2024-11-05T00:41:50.313521Z","iopub.status.idle":"2024-11-05T00:41:50.327841Z","shell.execute_reply.started":"2024-11-05T00:41:50.31343Z","shell.execute_reply":"2024-11-05T00:41:50.326673Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for i in categorical:\n    plt.figure(figsize=(15,6))\n    sns.countplot(x = df[i], data = df, palette = 'hls')\n    plt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T00:41:50.329675Z","iopub.execute_input":"2024-11-05T00:41:50.330104Z","iopub.status.idle":"2024-11-05T00:41:50.777682Z","shell.execute_reply.started":"2024-11-05T00:41:50.33003Z","shell.execute_reply":"2024-11-05T00:41:50.77601Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for i in categorical:\n    plt.figure(figsize=(30,20)) \n    plt.pie(df[i].value_counts(), labels=df[i].value_counts().index, \n            autopct='%1.1f%%', textprops={ 'fontsize': 20,\n                                           'color': 'black',\n                                           'weight': 'bold',\n                                           'family': 'serif' }) \n    hfont = {'fontname':'serif', 'weight': 'bold'}\n    plt.title(i, size=20, **hfont) \n    plt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T00:41:50.780434Z","iopub.execute_input":"2024-11-05T00:41:50.7813Z","iopub.status.idle":"2024-11-05T00:41:51.330705Z","shell.execute_reply.started":"2024-11-05T00:41:50.781213Z","shell.execute_reply":"2024-11-05T00:41:51.329636Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for i in numerical_columns:\n    plt.figure(figsize=(15,6))\n    sns.distplot(df[i], kde=True, bins=20)\n    plt.xticks(rotation=90)\n    plt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T00:41:51.332148Z","iopub.execute_input":"2024-11-05T00:41:51.332428Z","iopub.status.idle":"2024-11-05T00:41:52.192265Z","shell.execute_reply.started":"2024-11-05T00:41:51.332381Z","shell.execute_reply":"2024-11-05T00:41:52.190744Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for i in numerical_columns:\n    plt.figure(figsize=(15,6))\n    sns.distplot(df[i], kde = True, bins = 20)\n    plt.xticks(rotation = 90)\n    plt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T00:41:52.194853Z","iopub.execute_input":"2024-11-05T00:41:52.195576Z","iopub.status.idle":"2024-11-05T00:41:53.078374Z","shell.execute_reply.started":"2024-11-05T00:41:52.195302Z","shell.execute_reply":"2024-11-05T00:41:53.07705Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for i in numerical_columns:\n    plt.figure(figsize=(15,6))\n    sns.boxplot(x = df[i],data = df, palette = 'hls')\n    plt.xticks(rotation = 90)\n    plt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T00:41:53.080535Z","iopub.execute_input":"2024-11-05T00:41:53.08138Z","iopub.status.idle":"2024-11-05T00:41:53.707453Z","shell.execute_reply.started":"2024-11-05T00:41:53.081298Z","shell.execute_reply":"2024-11-05T00:41:53.705218Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for i in numerical_columns:\n    plt.figure(figsize=(15,6))\n    sns.violinplot(x = df[i],data = df, palette = 'hls')\n    plt.xticks(rotation = 90)\n    plt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T00:41:53.709803Z","iopub.execute_input":"2024-11-05T00:41:53.710444Z","iopub.status.idle":"2024-11-05T00:41:55.136542Z","shell.execute_reply.started":"2024-11-05T00:41:53.710376Z","shell.execute_reply":"2024-11-05T00:41:55.134992Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for i in categorical:\n    for j in numerical_columns:\n        plt.figure(figsize=(15,6))\n        sns.barplot(x = df[i], y = df[j], data = df, ci = None, palette = 'hls')\n        plt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T00:41:55.139278Z","iopub.execute_input":"2024-11-05T00:41:55.140332Z","iopub.status.idle":"2024-11-05T00:41:55.941049Z","shell.execute_reply.started":"2024-11-05T00:41:55.140239Z","shell.execute_reply":"2024-11-05T00:41:55.939099Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for i in categorical:\n    for j in numerical_columns:\n        plt.figure(figsize=(15,6))\n        sns.boxplot(x = df[i], y = df[j], data = df, palette = 'hls')\n        plt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T00:41:55.943714Z","iopub.execute_input":"2024-11-05T00:41:55.944613Z","iopub.status.idle":"2024-11-05T00:41:56.798433Z","shell.execute_reply.started":"2024-11-05T00:41:55.944208Z","shell.execute_reply":"2024-11-05T00:41:56.796867Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for i in categorical:\n    for j in numerical_columns:\n        plt.figure(figsize=(15,6))\n        sns.violinplot(x = df[i], y = df[j], data = df, palette = 'hls')\n        plt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T00:41:56.800999Z","iopub.execute_input":"2024-11-05T00:41:56.801959Z","iopub.status.idle":"2024-11-05T00:41:58.55751Z","shell.execute_reply.started":"2024-11-05T00:41:56.801861Z","shell.execute_reply":"2024-11-05T00:41:58.556041Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for i in numerical_columns:\n    for j in numerical_columns:\n        if i != j:\n            plt.figure(figsize=(15,6))\n            sns.scatterplot(x = df[j], y = df[i], data = df, palette = 'hls')\n            plt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T00:41:58.560108Z","iopub.execute_input":"2024-11-05T00:41:58.561087Z","iopub.status.idle":"2024-11-05T00:42:02.357774Z","shell.execute_reply.started":"2024-11-05T00:41:58.560994Z","shell.execute_reply":"2024-11-05T00:42:02.356182Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"real_df = df[df[\"label\"] == \"REAL\"]\nfake_df = df[df[\"label\"] == \"FAKE\"]\nsample_size = 10000\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":"2024-11-05T00:42:02.362641Z","iopub.execute_input":"2024-11-05T00:42:02.363233Z","iopub.status.idle":"2024-11-05T00:42:02.432135Z","shell.execute_reply.started":"2024-11-05T00:42:02.363151Z","shell.execute_reply":"2024-11-05T00:42:02.43102Z"}},"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":"2024-11-05T00:42:02.433765Z","iopub.execute_input":"2024-11-05T00:42:02.434091Z","iopub.status.idle":"2024-11-05T00:42:02.522838Z","shell.execute_reply.started":"2024-11-05T00:42:02.434041Z","shell.execute_reply":"2024-11-05T00:42:02.521891Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"Train_set.shape,Val_set.shape,Test_set.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T00:42:02.524503Z","iopub.execute_input":"2024-11-05T00:42:02.524867Z","iopub.status.idle":"2024-11-05T00:42:02.532002Z","shell.execute_reply.started":"2024-11-05T00:42:02.524803Z","shell.execute_reply":"2024-11-05T00:42:02.530691Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import cv2","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T00:42:02.533932Z","iopub.execute_input":"2024-11-05T00:42:02.534356Z","iopub.status.idle":"2024-11-05T00:42:02.546073Z","shell.execute_reply.started":"2024-11-05T00:42:02.534283Z","shell.execute_reply":"2024-11-05T00:42:02.544992Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"image_path = '/kaggle/input/deepfake-faces/faces_224/'\n\nimage_files = os.listdir(image_path)\n\nimage_files.sort()\n\nselected_images = image_files[:9]\n\nplt.figure(figsize=(10, 10))\n\nfor index, image_file in enumerate(selected_images):\n    image = cv2.imread(os.path.join(image_path, image_file))\n\n    plt.subplot(3, 3, index + 1)\n    plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))\n    plt.title(f'Image {index + 1}')\n    plt.axis('off')\n\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T00:42:02.547864Z","iopub.execute_input":"2024-11-05T00:42:02.548184Z","iopub.status.idle":"2024-11-05T00:42:03.753873Z","shell.execute_reply.started":"2024-11-05T00:42:02.548136Z","shell.execute_reply":"2024-11-05T00:42:03.752877Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for i, image_file in enumerate(image_files[:10]):\n    image = cv2.imread(os.path.join(image_path, image_file))\n    if image is not None:\n        height, width, _ = image.shape\n        print(f\"Resolution of image {i+1}: {width} x {height}\")\n    else:\n        print(f\"Error reading image {i+1}\")\n\nif len(image_files) < 10:\n    print(f\"Only {len(image_files)} images found in the directory.\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T00:42:03.755531Z","iopub.execute_input":"2024-11-05T00:42:03.755828Z","iopub.status.idle":"2024-11-05T00:42:03.788109Z","shell.execute_reply.started":"2024-11-05T00:42:03.755779Z","shell.execute_reply":"2024-11-05T00:42:03.786922Z"}},"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":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T00:42:03.790048Z","iopub.execute_input":"2024-11-05T00:42:03.790459Z","iopub.status.idle":"2024-11-05T00:42:05.728508Z","shell.execute_reply.started":"2024-11-05T00:42:03.790377Z","shell.execute_reply":"2024-11-05T00:42:05.727314Z"}},"outputs":[],"execution_count":null},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T00:42:05.730182Z","iopub.execute_input":"2024-11-05T00:42:05.730544Z","iopub.status.idle":"2024-11-05T00:42:05.741284Z","shell.execute_reply.started":"2024-11-05T00:42:05.73047Z","shell.execute_reply":"2024-11-05T00:42:05.740305Z"}},"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":"2024-11-05T00:42:05.743284Z","iopub.execute_input":"2024-11-05T00:42:05.743671Z","iopub.status.idle":"2024-11-05T00:43:10.319857Z","shell.execute_reply.started":"2024-11-05T00:42:05.743608Z","shell.execute_reply":"2024-11-05T00:43:10.318586Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras import layers, models\nfrom functools import partial","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T00:43:10.321803Z","iopub.execute_input":"2024-11-05T00:43:10.322231Z","iopub.status.idle":"2024-11-05T00:43:10.328631Z","shell.execute_reply.started":"2024-11-05T00:43:10.322156Z","shell.execute_reply":"2024-11-05T00:43:10.327239Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"tf.random.set_seed(42)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T00:43:10.33053Z","iopub.execute_input":"2024-11-05T00:43:10.330952Z","iopub.status.idle":"2024-11-05T00:43:10.347878Z","shell.execute_reply.started":"2024-11-05T00:43:10.330882Z","shell.execute_reply":"2024-11-05T00:43:10.346715Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"DefaultConv2D = partial(layers.Conv2D, kernel_size=3, padding=\"same\",\n                        activation=\"relu\", kernel_initializer=\"he_normal\")\n\n# Model Definition\nmodel = models.Sequential([\n    DefaultConv2D(filters=64, kernel_size=7, input_shape=[224, 224, 3]),\n    layers.MaxPooling2D(),\n    layers.BatchNormalization(),\n    DefaultConv2D(filters=128),\n    DefaultConv2D(filters=128),\n    layers.MaxPooling2D(),\n    layers.BatchNormalization(),\n    layers.Flatten(),\n    layers.Dense(units=128, activation=\"relu\",\n                 kernel_initializer=\"he_normal\"),\n    layers.BatchNormalization(),\n    layers.Dropout(0.5),\n    layers.Dense(units=64, activation=\"relu\",\n                 kernel_initializer=\"he_normal\"),\n    layers.BatchNormalization(),\n    layers.Dropout(0.5),\n    layers.Dense(units=1, activation=\"sigmoid\")\n])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T00:43:10.353222Z","iopub.execute_input":"2024-11-05T00:43:10.353684Z","iopub.status.idle":"2024-11-05T00:43:11.508046Z","shell.execute_reply.started":"2024-11-05T00:43:10.353622Z","shell.execute_reply":"2024-11-05T00:43:11.50698Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"initial_learning_rate = 0.001\nlr_schedule = tf.keras.optimizers.schedules.ExponentialDecay(\n    initial_learning_rate, decay_steps=100000, decay_rate=0.96, staircase=True\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T00:43:11.509978Z","iopub.execute_input":"2024-11-05T00:43:11.510432Z","iopub.status.idle":"2024-11-05T00:43:11.517379Z","shell.execute_reply.started":"2024-11-05T00:43:11.510346Z","shell.execute_reply":"2024-11-05T00:43:11.515733Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=lr_schedule),\n              loss=\"binary_crossentropy\", metrics=[\"accuracy\"])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T00:43:11.519229Z","iopub.execute_input":"2024-11-05T00:43:11.519586Z","iopub.status.idle":"2024-11-05T00:43:11.579355Z","shell.execute_reply.started":"2024-11-05T00:43:11.519524Z","shell.execute_reply":"2024-11-05T00:43:11.578177Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T00:43:11.580859Z","iopub.execute_input":"2024-11-05T00:43:11.581146Z","iopub.status.idle":"2024-11-05T00:43:11.591966Z","shell.execute_reply.started":"2024-11-05T00:43:11.581101Z","shell.execute_reply":"2024-11-05T00:43:11.590848Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"history = model.fit(\n    X_train, y_train,\n    epochs=10,  # Adjust as needed\n    batch_size=32,  # Adjust as needed\n    validation_data=(X_val, y_val),\n    verbose=1\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T00:43:11.593617Z","iopub.execute_input":"2024-11-05T00:43:11.593962Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"y_pred = model.predict(X_test)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score, confusion_matrix, classification_report","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"y_test_pred_binary = (y_pred > 0.5).astype(int)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"y_train_pred = model.predict(X_train)\ny_train_pred_binary = (y_train_pred > 0.5).astype(int)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_accuracy = accuracy_score(y_train, y_train_pred_binary)\nprint(f\"Training Accuracy: {train_accuracy * 100:.2f}%\")","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_accuracy = accuracy_score(y_test, y_test_pred_binary)\nprint(f\"Test Accuracy: {test_accuracy * 100:.2f}%\")","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"f1 = f1_score(y_test, y_test_pred_binary)\nprint(f\"F1 Score: {f1:.4f}\")\n\nprecision = precision_score(y_test, y_test_pred_binary)\nprint(f\"Precison: {precision:.4f}\")\n\nrecall = recall_score(y_test, y_test_pred_binary)\nprint(f\"Recall: {recall:.4f}\")","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"conf_matrix = confusion_matrix(y_test, y_test_pred_binary)\nprint(\"Confusion Matrix:\")\nprint(conf_matrix)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import scikitplot as skplt","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"skplt.metrics.plot_confusion_matrix(y_test, y_test_pred_binary, normalize=True)\nplt.show()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class_report = classification_report(y_test, y_test_pred_binary)\nprint(\"Classification Report:\")\nprint(class_report)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.figure(figsize=(12, 4))\nplt.subplot(1, 2, 1)\nplt.plot(history.history['accuracy'], label='Training Accuracy')\nplt.plot(history.history['val_accuracy'], label='Validation Accuracy')\nplt.title('Training and Validation Accuracy')\nplt.xlabel('Epoch')\nplt.ylabel('Accuracy')\nplt.legend()\nplt.show()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.plot(history.history['loss'], label='Training Loss')\nplt.plot(history.history['val_loss'], label='Validation Loss')\nplt.title('Training and Validation Loss')\nplt.xlabel('Epoch')\nplt.ylabel('Loss')\nplt.legend()\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.applications import ResNet50","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"input_shape = (224, 224, 3)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"base_model = ResNet50(weights='imagenet', include_top=False, input_shape=input_shape)","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":"model_resnet50 = models.Sequential()\nmodel_resnet50.add(base_model)\nmodel_resnet50.add(layers.GlobalAveragePooling2D())\nmodel_resnet50.add(layers.Dense(1, activation='sigmoid'))","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model_resnet50.summary()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras import optimizers","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model_resnet50.compile(optimizer=optimizers.Adam(lr=0.001), loss='binary_crossentropy', metrics=['accuracy'])","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"history = model_resnet50.fit(\n    X_train, y_train,\n    epochs=10,  \n    validation_data=(X_val, y_val),\n    verbose=1\n)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"y_pred = model_resnet50.predict(X_test)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"y_test_pred_binary = (y_pred > 0.5).astype(int)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"y_train_pred = model_resnet50.predict(X_train)\ny_train_pred_binary = (y_train_pred > 0.5).astype(int)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_accuracy = accuracy_score(y_train, y_train_pred_binary)\nprint(f\"Training Accuracy: {train_accuracy * 100:.2f}%\")","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_accuracy = accuracy_score(y_test, y_test_pred_binary)\nprint(f\"Test Accuracy: {test_accuracy * 100:.2f}%\")","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"f1 = f1_score(y_test, y_test_pred_binary)\nprint(f\"F1 Score: {f1:.4f}\")\n\nprecision = precision_score(y_test, y_test_pred_binary)\nprint(f\"Precison: {precision:.4f}\")\n\nrecall = recall_score(y_test, y_test_pred_binary)\nprint(f\"Recall: {recall:.4f}\")","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"conf_matrix = confusion_matrix(y_test, y_test_pred_binary)\nprint(\"Confusion Matrix:\")\nprint(conf_matrix)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"skplt.metrics.plot_confusion_matrix(y_test, y_test_pred_binary, normalize=True)\nplt.show()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class_report = classification_report(y_test, y_test_pred_binary)\nprint(\"Classification Report:\")\nprint(class_report)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.figure(figsize=(12, 4))\nplt.subplot(1, 2, 1)\nplt.plot(history.history['accuracy'], label='Training Accuracy')\nplt.plot(history.history['val_accuracy'], label='Validation Accuracy')\nplt.title('Training and Validation Accuracy')\nplt.xlabel('Epoch')\nplt.ylabel('Accuracy')\nplt.legend()\nplt.show()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.plot(history.history['loss'], label='Training Loss')\nplt.plot(history.history['val_loss'], label='Validation Loss')\nplt.title('Training and Validation Loss')\nplt.xlabel('Epoch')\nplt.ylabel('Loss')\nplt.legend()\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}