{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","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},{"sourceId":9119397,"sourceType":"datasetVersion","datasetId":5504901}],"dockerImageVersionId":30627,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"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","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-08-06T15:44:00.806478Z","iopub.execute_input":"2024-08-06T15:44:00.807519Z","iopub.status.idle":"2024-08-06T15:44:01.756629Z","shell.execute_reply.started":"2024-08-06T15:44:00.807470Z","shell.execute_reply":"2024-08-06T15:44:01.755785Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dataset_path = '/kaggle/input/deepfake-faces/metadata.csv'","metadata":{"execution":{"iopub.status.busy":"2024-08-06T15:44:01.758869Z","iopub.execute_input":"2024-08-06T15:44:01.759394Z","iopub.status.idle":"2024-08-06T15:44:01.763780Z","shell.execute_reply.started":"2024-08-06T15:44:01.759355Z","shell.execute_reply":"2024-08-06T15:44:01.762806Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = pd.read_csv(dataset_path)","metadata":{"execution":{"iopub.status.busy":"2024-08-06T15:44:01.764932Z","iopub.execute_input":"2024-08-06T15:44:01.765297Z","iopub.status.idle":"2024-08-06T15:44:01.944272Z","shell.execute_reply.started":"2024-08-06T15:44:01.765254Z","shell.execute_reply":"2024-08-06T15:44:01.943312Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.head()","metadata":{"execution":{"iopub.status.busy":"2024-08-06T15:44:01.945599Z","iopub.execute_input":"2024-08-06T15:44:01.945970Z","iopub.status.idle":"2024-08-06T15:44:01.964853Z","shell.execute_reply.started":"2024-08-06T15:44:01.945935Z","shell.execute_reply":"2024-08-06T15:44:01.963934Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.tail()","metadata":{"execution":{"iopub.status.busy":"2024-08-06T15:44:01.968035Z","iopub.execute_input":"2024-08-06T15:44:01.968629Z","iopub.status.idle":"2024-08-06T15:44:01.978051Z","shell.execute_reply.started":"2024-08-06T15:44:01.968602Z","shell.execute_reply":"2024-08-06T15:44:01.977108Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.shape","metadata":{"execution":{"iopub.status.busy":"2024-08-06T15:44:01.979256Z","iopub.execute_input":"2024-08-06T15:44:01.979581Z","iopub.status.idle":"2024-08-06T15:44:01.990392Z","shell.execute_reply.started":"2024-08-06T15:44:01.979554Z","shell.execute_reply":"2024-08-06T15:44:01.989524Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.columns","metadata":{"execution":{"iopub.status.busy":"2024-08-06T15:44:01.992051Z","iopub.execute_input":"2024-08-06T15:44:01.992688Z","iopub.status.idle":"2024-08-06T15:44:02.000090Z","shell.execute_reply.started":"2024-08-06T15:44:01.992662Z","shell.execute_reply":"2024-08-06T15:44:01.999070Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.duplicated().sum()","metadata":{"execution":{"iopub.status.busy":"2024-08-06T15:44:02.001285Z","iopub.execute_input":"2024-08-06T15:44:02.001851Z","iopub.status.idle":"2024-08-06T15:44:02.058381Z","shell.execute_reply.started":"2024-08-06T15:44:02.001819Z","shell.execute_reply":"2024-08-06T15:44:02.057517Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.isnull().sum()","metadata":{"execution":{"iopub.status.busy":"2024-08-06T15:44:02.059506Z","iopub.execute_input":"2024-08-06T15:44:02.059777Z","iopub.status.idle":"2024-08-06T15:44:02.091788Z","shell.execute_reply.started":"2024-08-06T15:44:02.059753Z","shell.execute_reply":"2024-08-06T15:44:02.090808Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.info()","metadata":{"execution":{"iopub.status.busy":"2024-08-06T15:44:02.092920Z","iopub.execute_input":"2024-08-06T15:44:02.093214Z","iopub.status.idle":"2024-08-06T15:44:02.134419Z","shell.execute_reply.started":"2024-08-06T15:44:02.093190Z","shell.execute_reply":"2024-08-06T15:44:02.133526Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.nunique()","metadata":{"execution":{"iopub.status.busy":"2024-08-06T15:44:02.135791Z","iopub.execute_input":"2024-08-06T15:44:02.136481Z","iopub.status.idle":"2024-08-06T15:44:02.183284Z","shell.execute_reply.started":"2024-08-06T15:44:02.136424Z","shell.execute_reply":"2024-08-06T15:44:02.182383Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-08-06T15:44:02.184288Z","iopub.execute_input":"2024-08-06T15:44:02.184559Z","iopub.status.idle":"2024-08-06T15:44:02.193668Z","shell.execute_reply.started":"2024-08-06T15:44:02.184535Z","shell.execute_reply":"2024-08-06T15:44:02.192800Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-08-06T15:44:02.194882Z","iopub.execute_input":"2024-08-06T15:44:02.195141Z","iopub.status.idle":"2024-08-06T15:44:02.202540Z","shell.execute_reply.started":"2024-08-06T15:44:02.195118Z","shell.execute_reply":"2024-08-06T15:44:02.201607Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"categorical, non_categorical, discrete, continuous = classify_features(df)","metadata":{"execution":{"iopub.status.busy":"2024-08-06T15:44:02.207745Z","iopub.execute_input":"2024-08-06T15:44:02.208021Z","iopub.status.idle":"2024-08-06T15:44:02.251814Z","shell.execute_reply.started":"2024-08-06T15:44:02.207998Z","shell.execute_reply":"2024-08-06T15:44:02.251030Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Categorical Features:\", categorical)\nprint(\"Non-Categorical Features:\", non_categorical)\nprint(\"Discrete Features:\", discrete)\nprint(\"Continuous Features:\", continuous)","metadata":{"execution":{"iopub.status.busy":"2024-08-06T15:44:02.252778Z","iopub.execute_input":"2024-08-06T15:44:02.253026Z","iopub.status.idle":"2024-08-06T15:44:02.258535Z","shell.execute_reply.started":"2024-08-06T15:44:02.253004Z","shell.execute_reply":"2024-08-06T15:44:02.257521Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = df.fillna(\"Not Available\")","metadata":{"execution":{"iopub.status.busy":"2024-08-06T15:44:02.259838Z","iopub.execute_input":"2024-08-06T15:44:02.260136Z","iopub.status.idle":"2024-08-06T15:44:02.299312Z","shell.execute_reply.started":"2024-08-06T15:44:02.260103Z","shell.execute_reply":"2024-08-06T15:44:02.298615Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for i in categorical:\n    print(i,':', df[i].unique())\n    print()","metadata":{"execution":{"iopub.status.busy":"2024-08-06T15:44:02.300273Z","iopub.execute_input":"2024-08-06T15:44:02.300561Z","iopub.status.idle":"2024-08-06T15:44:02.311961Z","shell.execute_reply.started":"2024-08-06T15:44:02.300537Z","shell.execute_reply":"2024-08-06T15:44:02.310956Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for i in categorical:\n    print(df[i].value_counts())\n    print()","metadata":{"execution":{"iopub.status.busy":"2024-08-06T15:44:02.313212Z","iopub.execute_input":"2024-08-06T15:44:02.313532Z","iopub.status.idle":"2024-08-06T15:44:02.329749Z","shell.execute_reply.started":"2024-08-06T15:44:02.313499Z","shell.execute_reply":"2024-08-06T15:44:02.328862Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np \nimport pandas as pd \nimport matplotlib.pyplot as plt\nimport seaborn as sns","metadata":{"execution":{"iopub.status.busy":"2024-08-06T15:44:02.330955Z","iopub.execute_input":"2024-08-06T15:44:02.331247Z","iopub.status.idle":"2024-08-06T15:44:03.191174Z","shell.execute_reply.started":"2024-08-06T15:44:02.331222Z","shell.execute_reply":"2024-08-06T15:44:03.190381Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import warnings\nwarnings.filterwarnings('ignore')","metadata":{"execution":{"iopub.status.busy":"2024-08-06T15:44:03.192209Z","iopub.execute_input":"2024-08-06T15:44:03.192484Z","iopub.status.idle":"2024-08-06T15:44:03.196908Z","shell.execute_reply.started":"2024-08-06T15:44:03.192435Z","shell.execute_reply":"2024-08-06T15:44:03.195907Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-08-06T15:44:03.198163Z","iopub.execute_input":"2024-08-06T15:44:03.198430Z","iopub.status.idle":"2024-08-06T15:44:03.569851Z","shell.execute_reply.started":"2024-08-06T15:44:03.198406Z","shell.execute_reply":"2024-08-06T15:44:03.568907Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-08-06T15:44:03.571271Z","iopub.execute_input":"2024-08-06T15:44:03.571664Z","iopub.status.idle":"2024-08-06T15:44:03.625538Z","shell.execute_reply.started":"2024-08-06T15:44:03.571627Z","shell.execute_reply":"2024-08-06T15:44:03.624621Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n\nTrain_set, Test_set = train_test_split(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":{"execution":{"iopub.status.busy":"2024-08-06T15:44:03.626849Z","iopub.execute_input":"2024-08-06T15:44:03.627201Z","iopub.status.idle":"2024-08-06T15:44:03.953032Z","shell.execute_reply.started":"2024-08-06T15:44:03.627167Z","shell.execute_reply":"2024-08-06T15:44:03.952040Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Train_set.shape,Val_set.shape,Test_set.shape","metadata":{"execution":{"iopub.status.busy":"2024-08-06T15:44:03.954255Z","iopub.execute_input":"2024-08-06T15:44:03.954594Z","iopub.status.idle":"2024-08-06T15:44:03.961721Z","shell.execute_reply.started":"2024-08-06T15:44:03.954566Z","shell.execute_reply":"2024-08-06T15:44:03.960676Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import cv2","metadata":{"execution":{"iopub.status.busy":"2024-08-06T15:44:03.963053Z","iopub.execute_input":"2024-08-06T15:44:03.964211Z","iopub.status.idle":"2024-08-06T15:44:04.146592Z","shell.execute_reply.started":"2024-08-06T15:44:03.964175Z","shell.execute_reply":"2024-08-06T15:44:04.145772Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-08-06T15:44:04.147606Z","iopub.execute_input":"2024-08-06T15:44:04.147865Z","iopub.status.idle":"2024-08-06T15:44:05.860134Z","shell.execute_reply.started":"2024-08-06T15:44:04.147843Z","shell.execute_reply":"2024-08-06T15:44:05.859152Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-08-06T15:44:05.861480Z","iopub.execute_input":"2024-08-06T15:44:05.861926Z","iopub.status.idle":"2024-08-06T15:44:05.892159Z","shell.execute_reply.started":"2024-08-06T15:44:05.861877Z","shell.execute_reply":"2024-08-06T15:44:05.891230Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-08-06T15:44:05.893341Z","iopub.execute_input":"2024-08-06T15:44:05.893713Z","iopub.status.idle":"2024-08-06T15:44:07.984044Z","shell.execute_reply.started":"2024-08-06T15:44:05.893686Z","shell.execute_reply":"2024-08-06T15:44:07.983048Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-08-06T15:44:07.985411Z","iopub.execute_input":"2024-08-06T15:44:07.985782Z","iopub.status.idle":"2024-08-06T15:44:07.992335Z","shell.execute_reply.started":"2024-08-06T15:44:07.985735Z","shell.execute_reply":"2024-08-06T15:44:07.991223Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train,y_train=retreive_dataset(Train_set)\nX_val,y_val=retreive_dataset(Val_set)\nX_test,y_test=retreive_dataset(Test_set)","metadata":{"execution":{"iopub.status.busy":"2024-08-06T15:44:07.993749Z","iopub.execute_input":"2024-08-06T15:44:07.994091Z","iopub.status.idle":"2024-08-06T15:46:05.430409Z","shell.execute_reply.started":"2024-08-06T15:44:07.994058Z","shell.execute_reply":"2024-08-06T15:46:05.429518Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras import layers, models\nfrom functools import partial","metadata":{"execution":{"iopub.status.busy":"2024-08-06T15:46:05.432058Z","iopub.execute_input":"2024-08-06T15:46:05.432337Z","iopub.status.idle":"2024-08-06T15:46:12.774186Z","shell.execute_reply.started":"2024-08-06T15:46:05.432313Z","shell.execute_reply":"2024-08-06T15:46:12.773308Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tf.random.set_seed(42)","metadata":{"execution":{"iopub.status.busy":"2024-08-06T15:46:12.775355Z","iopub.execute_input":"2024-08-06T15:46:12.775991Z","iopub.status.idle":"2024-08-06T15:46:12.781406Z","shell.execute_reply.started":"2024-08-06T15:46:12.775959Z","shell.execute_reply":"2024-08-06T15:46:12.780499Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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'\n)\n\n# Fit the generator to your data\ndatagen.fit(X_train)\n","metadata":{"execution":{"iopub.status.busy":"2024-08-06T15:46:12.782756Z","iopub.execute_input":"2024-08-06T15:46:12.783038Z","iopub.status.idle":"2024-08-06T15:46:16.681140Z","shell.execute_reply.started":"2024-08-06T15:46:12.783014Z","shell.execute_reply":"2024-08-06T15:46:16.680268Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"DefaultConv2D = partial(\n    layers.Conv2D,\n    kernel_size=3,\n    padding=\"same\",\n    activation=None,  # Remove activation from Conv2D\n    kernel_initializer=\"he_normal\"\n)\n\nmodel = models.Sequential([\n    DefaultConv2D(filters=32, kernel_size=7, input_shape=[224, 224, 3]),\n    layers.BatchNormalization(),\n    layers.Activation(\"relu\"),\n    layers.MaxPooling2D(),\n    \n    DefaultConv2D(filters=64),\n    layers.BatchNormalization(),\n    layers.Activation(\"relu\"),\n    layers.MaxPooling2D(),\n    \n    DefaultConv2D(filters=128),\n    layers.BatchNormalization(),\n    layers.Activation(\"relu\"),\n    layers.MaxPooling2D(),\n    \n    layers.GlobalAveragePooling2D(),\n    layers.Dense(units=128, activation=\"relu\", kernel_initializer=\"he_normal\"),\n    layers.Dropout(0.5),\n    layers.Dense(units=64, activation=\"relu\", kernel_initializer=\"he_normal\"),\n    layers.Dropout(0.5),\n    layers.Dense(units=1, activation=\"sigmoid\")\n])\n","metadata":{"execution":{"iopub.status.busy":"2024-08-06T15:46:16.682239Z","iopub.execute_input":"2024-08-06T15:46:16.682532Z","iopub.status.idle":"2024-08-06T15:46:17.671280Z","shell.execute_reply.started":"2024-08-06T15:46:16.682508Z","shell.execute_reply":"2024-08-06T15:46:17.670508Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2024-08-06T15:46:17.672373Z","iopub.execute_input":"2024-08-06T15:46:17.672649Z","iopub.status.idle":"2024-08-06T15:46:17.723226Z","shell.execute_reply.started":"2024-08-06T15:46:17.672626Z","shell.execute_reply":"2024-08-06T15:46:17.720321Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"initial_learning_rate = 0.001\nlr_schedule = tf.keras.optimizers.schedules.ExponentialDecay(\n    initial_learning_rate, decay_steps=500, decay_rate=0.9, staircase=True\n)\n\n# Compile model\nmodel.compile(\n    optimizer=tf.keras.optimizers.Adam(learning_rate=lr_schedule),\n    loss=\"binary_crossentropy\",\n    metrics=[\"accuracy\"]\n)","metadata":{"execution":{"iopub.status.busy":"2024-08-06T15:49:51.325689Z","iopub.execute_input":"2024-08-06T15:49:51.326093Z","iopub.status.idle":"2024-08-06T15:49:51.361605Z","shell.execute_reply.started":"2024-08-06T15:49:51.326062Z","shell.execute_reply":"2024-08-06T15:49:51.360811Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Callbacks\nearly_stopping = EarlyStopping(monitor='val_loss', patience=10, restore_best_weights=True, mode='min')\nmodel_checkpoint = ModelCheckpoint('/kaggle/working/best_model.h5', save_best_only=True, monitor='val_loss', mode='min')\n\n# Data Augmentation\nfrom 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'\n)\n\ndatagen.fit(X_train)","metadata":{"execution":{"iopub.status.busy":"2024-08-06T15:50:53.513237Z","iopub.execute_input":"2024-08-06T15:50:53.513770Z","iopub.status.idle":"2024-08-06T15:50:57.409199Z","shell.execute_reply.started":"2024-08-06T15:50:53.513737Z","shell.execute_reply":"2024-08-06T15:50:57.408287Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit(\n    datagen.flow(X_train, y_train, batch_size=32),\n    epochs=15,\n    validation_data=(X_val, y_val),\n    callbacks=[early_stopping, model_checkpoint]\n)","metadata":{"execution":{"iopub.status.busy":"2024-08-06T15:51:26.490625Z","iopub.execute_input":"2024-08-06T15:51:26.491016Z","iopub.status.idle":"2024-08-06T16:20:33.726953Z","shell.execute_reply.started":"2024-08-06T15:51:26.490984Z","shell.execute_reply":"2024-08-06T16:20:33.725929Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_pred = model.predict(X_test)","metadata":{"execution":{"iopub.status.busy":"2024-08-06T16:22:39.660670Z","iopub.execute_input":"2024-08-06T16:22:39.661727Z","iopub.status.idle":"2024-08-06T16:22:44.180803Z","shell.execute_reply.started":"2024-08-06T16:22:39.661678Z","shell.execute_reply":"2024-08-06T16:22:44.179869Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_pred","metadata":{"execution":{"iopub.status.busy":"2024-08-06T16:22:58.108203Z","iopub.execute_input":"2024-08-06T16:22:58.108594Z","iopub.status.idle":"2024-08-06T16:22:58.115787Z","shell.execute_reply.started":"2024-08-06T16:22:58.108566Z","shell.execute_reply":"2024-08-06T16:22:58.114493Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score, confusion_matrix, classification_report","metadata":{"execution":{"iopub.status.busy":"2024-08-06T16:23:02.753364Z","iopub.execute_input":"2024-08-06T16:23:02.753784Z","iopub.status.idle":"2024-08-06T16:23:02.758656Z","shell.execute_reply.started":"2024-08-06T16:23:02.753750Z","shell.execute_reply":"2024-08-06T16:23:02.757611Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_test_pred_binary = (y_pred > 0.5).astype(int)","metadata":{"execution":{"iopub.status.busy":"2024-08-06T16:23:03.741247Z","iopub.execute_input":"2024-08-06T16:23:03.741972Z","iopub.status.idle":"2024-08-06T16:23:03.746642Z","shell.execute_reply.started":"2024-08-06T16:23:03.741935Z","shell.execute_reply":"2024-08-06T16:23:03.745522Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_train_pred = model.predict(X_train)\ny_train_pred_binary = (y_train_pred > 0.5).astype(int)","metadata":{"execution":{"iopub.status.busy":"2024-08-06T16:23:05.709399Z","iopub.execute_input":"2024-08-06T16:23:05.709823Z","iopub.status.idle":"2024-08-06T16:23:17.594563Z","shell.execute_reply.started":"2024-08-06T16:23:05.709788Z","shell.execute_reply":"2024-08-06T16:23:17.593440Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_accuracy = accuracy_score(y_train, y_train_pred_binary)\nprint(f\"Training Accuracy: {train_accuracy * 100:.2f}%\")","metadata":{"execution":{"iopub.status.busy":"2024-08-06T16:23:17.596544Z","iopub.execute_input":"2024-08-06T16:23:17.596858Z","iopub.status.idle":"2024-08-06T16:23:17.605525Z","shell.execute_reply.started":"2024-08-06T16:23:17.596831Z","shell.execute_reply":"2024-08-06T16:23:17.604422Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_accuracy = accuracy_score(y_test, y_test_pred_binary)\nprint(f\"Test Accuracy: {test_accuracy * 100:.2f}%\")","metadata":{"execution":{"iopub.status.busy":"2024-08-06T16:23:17.607415Z","iopub.execute_input":"2024-08-06T16:23:17.607849Z","iopub.status.idle":"2024-08-06T16:23:17.615039Z","shell.execute_reply.started":"2024-08-06T16:23:17.607811Z","shell.execute_reply":"2024-08-06T16:23:17.614045Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-08-06T16:25:10.273561Z","iopub.execute_input":"2024-08-06T16:25:10.273993Z","iopub.status.idle":"2024-08-06T16:25:10.293497Z","shell.execute_reply.started":"2024-08-06T16:25:10.273963Z","shell.execute_reply":"2024-08-06T16:25:10.292532Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"conf_matrix = confusion_matrix(y_test, y_test_pred_binary)\nprint(\"Confusion Matrix:\")\nprint(conf_matrix)","metadata":{"execution":{"iopub.status.busy":"2024-08-06T16:25:12.436047Z","iopub.execute_input":"2024-08-06T16:25:12.436446Z","iopub.status.idle":"2024-08-06T16:25:12.446654Z","shell.execute_reply.started":"2024-08-06T16:25:12.436416Z","shell.execute_reply":"2024-08-06T16:25:12.445516Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import scikitplot as skplt","metadata":{"execution":{"iopub.status.busy":"2024-08-06T16:25:13.900271Z","iopub.execute_input":"2024-08-06T16:25:13.900656Z","iopub.status.idle":"2024-08-06T16:25:13.997592Z","shell.execute_reply.started":"2024-08-06T16:25:13.900623Z","shell.execute_reply":"2024-08-06T16:25:13.996779Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"skplt.metrics.plot_confusion_matrix(y_test, y_test_pred_binary, normalize=True)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-08-06T16:25:15.772158Z","iopub.execute_input":"2024-08-06T16:25:15.772864Z","iopub.status.idle":"2024-08-06T16:25:16.145617Z","shell.execute_reply.started":"2024-08-06T16:25:15.772830Z","shell.execute_reply":"2024-08-06T16:25:16.144586Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class_report = classification_report(y_test, y_test_pred_binary)\nprint(\"Classification Report:\")\nprint(class_report)","metadata":{"execution":{"iopub.status.busy":"2024-08-06T16:25:22.389635Z","iopub.execute_input":"2024-08-06T16:25:22.390630Z","iopub.status.idle":"2024-08-06T16:25:22.410766Z","shell.execute_reply.started":"2024-08-06T16:25:22.390593Z","shell.execute_reply":"2024-08-06T16:25:22.409813Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-08-06T16:25:24.404513Z","iopub.execute_input":"2024-08-06T16:25:24.405478Z","iopub.status.idle":"2024-08-06T16:25:24.710637Z","shell.execute_reply.started":"2024-08-06T16:25:24.405417Z","shell.execute_reply":"2024-08-06T16:25:24.709520Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-08-06T16:25:27.224209Z","iopub.execute_input":"2024-08-06T16:25:27.224911Z","iopub.status.idle":"2024-08-06T16:25:27.638036Z","shell.execute_reply.started":"2024-08-06T16:25:27.224876Z","shell.execute_reply":"2024-08-06T16:25:27.637038Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\nimport os\nfrom PIL import Image\nfrom tensorflow.keras.preprocessing import image\n\ndef preprocess_image(img_path, target_size=(224, 224)):\n    \"\"\"\n    Preprocesses an image for model input.\n    \n    Parameters:\n    - img_path: Path to the image file.\n    - target_size: Desired size to resize the image to.\n    \n    Returns:\n    - img_array: Preprocessed image as a numpy array.\n    \"\"\"\n    img = image.load_img(img_path, target_size=target_size)\n    img_array = image.img_to_array(img)\n    img_array = np.expand_dims(img_array, axis=0)\n    img_array /= 255.0\n    return img_array\n\ndef predict_image(model, img_path):\n    \"\"\"\n    Predicts whether an image is FAKE or REAL using the given model.\n    \n    Parameters:\n    - model: The trained Keras model.\n    - img_path: Path to the image file.\n    \n    Returns:\n    - prediction: The predicted label ('FAKE' or 'REAL').\n    \"\"\"\n    img_array = preprocess_image(img_path)\n    prediction = model.predict(img_array)\n    return \"FAKE\" if prediction < 0.5 else \"REAL\"\n\ndef get_real_label(folder_name):\n    \"\"\"\n    Returns the label based on the folder name.\n    \n    Parameters:\n    - folder_name: The name of the folder.\n    \n    Returns:\n    - Label ('FAKE' or 'REAL').\n    \"\"\"\n    if 'fake' in folder_name.lower():\n        return 'FAKE'\n    else:\n        return 'REAL'\n\ndef test_real_time_predictions(model, real_folder, fake_folder, num_images=75):\n    \"\"\"\n    Tests the model on a set of real and fake images and prints the results.\n    \n    Parameters:\n    - model: The trained Keras model.\n    - real_folder: Path to the folder containing REAL images.\n    - fake_folder: Path to the folder containing FAKE images.\n    - num_images: Total number of images to test from both folders.\n    \"\"\"\n    # Get list of images in each folder\n    real_images = os.listdir(real_folder)\n    fake_images = os.listdir(fake_folder)\n\n    # Check if there are enough images in each folder\n    if len(real_images) < num_images // 2 or len(fake_images) < (num_images // 2) + 1:\n        raise ValueError(f\"Not enough images in one of the folders. Found {len(real_images)} real images and {len(fake_images)} fake images.\")\n\n    # Select a subset of images from each folder\n    selected_real_images = real_images[:num_images // 2]\n    selected_fake_images = fake_images[:(num_images - (num_images // 2))]\n\n    # Combine the selected images and their folders\n    selected_images = selected_real_images + selected_fake_images\n    folders = [real_folder] * (num_images // 2) + [fake_folder] * (num_images - (num_images // 2))\n\n    correct_predictions = 0\n    total_images = len(selected_images)\n\n    plt.figure(figsize=(20, 20), dpi=100)  # Adjusted figure size for 75 images\n\n    for index, img_file in enumerate(selected_images):\n        img_path = os.path.join(folders[index], img_file)\n        prediction = predict_image(model, img_path)\n        real_label = get_real_label(folders[index])\n        \n        if prediction == real_label:\n            correct_predictions += 1\n        \n        # Use PIL to load the image and improve quality\n        img = Image.open(img_path)\n        plt.subplot(8, 10, index + 1)  # Adjusted subplot grid for 75 images\n        plt.imshow(img)\n        plt.title(f'Pred: {prediction}\\nReal: {real_label}')\n        plt.axis('off')\n\n    plt.show()\n\n    # Calculate and print accuracy\n    if total_images > 0:\n        accuracy = (correct_predictions / total_images) * 100\n        print(f'Accuracy: {accuracy:.2f}%')\n    else:\n        print(\"No images selected for testing.\")\n\n# Example usage\n# Make sure to replace 'your_model' with your actual model variable\noriginal_model = model  # Replace with your original model variable\nreal_folder = '/kaggle/input/animal/test/REAL'\nfake_folder = '/kaggle/input/animal/test/FAKE'\n\n# Test real-time predictions\ntest_real_time_predictions(original_model, real_folder, fake_folder, num_images=75)\n","metadata":{"execution":{"iopub.status.busy":"2024-08-06T17:53:32.088188Z","iopub.execute_input":"2024-08-06T17:53:32.088636Z","iopub.status.idle":"2024-08-06T17:53:42.418906Z","shell.execute_reply.started":"2024-08-06T17:53:32.088602Z","shell.execute_reply":"2024-08-06T17:53:42.417931Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.applications import ResNet50","metadata":{"execution":{"iopub.status.busy":"2024-08-06T16:25:31.582351Z","iopub.execute_input":"2024-08-06T16:25:31.583080Z","iopub.status.idle":"2024-08-06T16:25:31.588306Z","shell.execute_reply.started":"2024-08-06T16:25:31.583044Z","shell.execute_reply":"2024-08-06T16:25:31.587298Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"input_shape = (224, 224, 3)","metadata":{"execution":{"iopub.status.busy":"2024-08-06T16:25:32.876129Z","iopub.execute_input":"2024-08-06T16:25:32.876521Z","iopub.status.idle":"2024-08-06T16:25:32.881075Z","shell.execute_reply.started":"2024-08-06T16:25:32.876489Z","shell.execute_reply":"2024-08-06T16:25:32.880127Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"base_model = ResNet50(weights='imagenet', include_top=False, input_shape=input_shape)","metadata":{"execution":{"iopub.status.busy":"2024-08-06T16:25:33.252847Z","iopub.execute_input":"2024-08-06T16:25:33.253241Z","iopub.status.idle":"2024-08-06T16:25:35.670741Z","shell.execute_reply.started":"2024-08-06T16:25:33.253210Z","shell.execute_reply":"2024-08-06T16:25:35.669626Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for layer in base_model.layers:\n    layer.trainable = False","metadata":{"execution":{"iopub.status.busy":"2024-08-06T16:25:35.672878Z","iopub.execute_input":"2024-08-06T16:25:35.673572Z","iopub.status.idle":"2024-08-06T16:25:35.684847Z","shell.execute_reply.started":"2024-08-06T16:25:35.673534Z","shell.execute_reply":"2024-08-06T16:25:35.683868Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.applications import ResNet50\nfrom tensorflow.keras import layers, models\n\n# Load the pre-trained ResNet50 model without the top layers\nbase_model = ResNet50(weights='imagenet', include_top=False, input_shape=(224,224, 3))\n\n# Freeze the base model\nbase_model.trainable = False\n\n# Define a new model with additional layers\nmodel_resnet50 = models.Sequential([\n    base_model,\n    layers.GlobalAveragePooling2D(),\n    layers.Dense(512, activation='relu'),  # Adding a dense layer with 512 units\n    layers.Dropout(0.5),  # Dropout layer to reduce overfitting\n    layers.Dense(256, activation='relu'),  # Adding another dense layer with 256 units\n    layers.Dropout(0.5),  # Another dropout layer\n    layers.Dense(1, activation='sigmoid')  # Output layer for binary classification\n])\n\n# Compile the model\nmodel_resnet50.compile(\n    optimizer='adam',\n    loss='binary_crossentropy',\n    metrics=['accuracy']\n)\n","metadata":{"execution":{"iopub.status.busy":"2024-08-06T16:25:35.685968Z","iopub.execute_input":"2024-08-06T16:25:35.686254Z","iopub.status.idle":"2024-08-06T16:25:38.014623Z","shell.execute_reply.started":"2024-08-06T16:25:35.686219Z","shell.execute_reply":"2024-08-06T16:25:38.013819Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_resnet50.summary()","metadata":{"execution":{"iopub.status.busy":"2024-08-06T16:25:38.016729Z","iopub.execute_input":"2024-08-06T16:25:38.017031Z","iopub.status.idle":"2024-08-06T16:25:38.062268Z","shell.execute_reply.started":"2024-08-06T16:25:38.017005Z","shell.execute_reply":"2024-08-06T16:25:38.061313Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras import optimizers","metadata":{"execution":{"iopub.status.busy":"2024-08-06T16:25:38.063585Z","iopub.execute_input":"2024-08-06T16:25:38.063939Z","iopub.status.idle":"2024-08-06T16:25:38.068416Z","shell.execute_reply.started":"2024-08-06T16:25:38.063906Z","shell.execute_reply":"2024-08-06T16:25:38.067519Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_resnet50.compile(optimizer=optimizers.Adam(lr=0.001), loss='binary_crossentropy', metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2024-08-06T16:25:38.069927Z","iopub.execute_input":"2024-08-06T16:25:38.070595Z","iopub.status.idle":"2024-08-06T16:25:38.087530Z","shell.execute_reply.started":"2024-08-06T16:25:38.070562Z","shell.execute_reply":"2024-08-06T16:25:38.086805Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-08-06T16:25:38.088565Z","iopub.execute_input":"2024-08-06T16:25:38.088835Z","iopub.status.idle":"2024-08-06T16:34:16.483349Z","shell.execute_reply.started":"2024-08-06T16:25:38.088812Z","shell.execute_reply":"2024-08-06T16:34:16.482283Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_pred = model_resnet50.predict(X_test)","metadata":{"execution":{"iopub.status.busy":"2024-08-06T16:34:16.485113Z","iopub.execute_input":"2024-08-06T16:34:16.486004Z","iopub.status.idle":"2024-08-06T16:34:31.389758Z","shell.execute_reply.started":"2024-08-06T16:34:16.485968Z","shell.execute_reply":"2024-08-06T16:34:31.388710Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_test_pred_binary = (y_pred > 0.5).astype(int)","metadata":{"execution":{"iopub.status.busy":"2024-08-06T16:34:31.391199Z","iopub.execute_input":"2024-08-06T16:34:31.391535Z","iopub.status.idle":"2024-08-06T16:34:31.396802Z","shell.execute_reply.started":"2024-08-06T16:34:31.391507Z","shell.execute_reply":"2024-08-06T16:34:31.395774Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_train_pred = model_resnet50.predict(X_train)\ny_train_pred_binary = (y_train_pred > 0.5).astype(int)","metadata":{"execution":{"iopub.status.busy":"2024-08-06T16:34:31.401307Z","iopub.execute_input":"2024-08-06T16:34:31.401663Z","iopub.status.idle":"2024-08-06T16:35:10.535765Z","shell.execute_reply.started":"2024-08-06T16:34:31.401635Z","shell.execute_reply":"2024-08-06T16:35:10.534816Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_accuracy = accuracy_score(y_train, y_train_pred_binary)\nprint(f\"Training Accuracy: {train_accuracy * 100:.2f}%\")","metadata":{"execution":{"iopub.status.busy":"2024-08-06T16:35:10.537084Z","iopub.execute_input":"2024-08-06T16:35:10.537407Z","iopub.status.idle":"2024-08-06T16:35:10.545663Z","shell.execute_reply.started":"2024-08-06T16:35:10.537380Z","shell.execute_reply":"2024-08-06T16:35:10.544510Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_accuracy = accuracy_score(y_test, y_test_pred_binary)\nprint(f\"Test Accuracy: {test_accuracy * 100:.2f}%\")","metadata":{"execution":{"iopub.status.busy":"2024-08-06T16:35:10.547022Z","iopub.execute_input":"2024-08-06T16:35:10.547878Z","iopub.status.idle":"2024-08-06T16:35:10.555670Z","shell.execute_reply.started":"2024-08-06T16:35:10.547838Z","shell.execute_reply":"2024-08-06T16:35:10.554628Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-08-06T16:35:10.557120Z","iopub.execute_input":"2024-08-06T16:35:10.557435Z","iopub.status.idle":"2024-08-06T16:35:10.574768Z","shell.execute_reply.started":"2024-08-06T16:35:10.557408Z","shell.execute_reply":"2024-08-06T16:35:10.573838Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"conf_matrix = confusion_matrix(y_test, y_test_pred_binary)\nprint(\"Confusion Matrix:\")\nprint(conf_matrix)","metadata":{"execution":{"iopub.status.busy":"2024-08-06T16:35:10.576063Z","iopub.execute_input":"2024-08-06T16:35:10.576726Z","iopub.status.idle":"2024-08-06T16:35:10.584720Z","shell.execute_reply.started":"2024-08-06T16:35:10.576683Z","shell.execute_reply":"2024-08-06T16:35:10.583685Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"skplt.metrics.plot_confusion_matrix(y_test, y_test_pred_binary, normalize=True)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-08-06T16:35:10.585638Z","iopub.execute_input":"2024-08-06T16:35:10.586142Z","iopub.status.idle":"2024-08-06T16:35:10.882978Z","shell.execute_reply.started":"2024-08-06T16:35:10.586116Z","shell.execute_reply":"2024-08-06T16:35:10.881957Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class_report = classification_report(y_test, y_test_pred_binary)\nprint(\"Classification Report:\")\nprint(class_report)","metadata":{"execution":{"iopub.status.busy":"2024-08-06T16:35:10.884161Z","iopub.execute_input":"2024-08-06T16:35:10.884435Z","iopub.status.idle":"2024-08-06T16:35:10.904211Z","shell.execute_reply.started":"2024-08-06T16:35:10.884411Z","shell.execute_reply":"2024-08-06T16:35:10.903153Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-08-06T16:35:10.905555Z","iopub.execute_input":"2024-08-06T16:35:10.905940Z","iopub.status.idle":"2024-08-06T16:35:11.210291Z","shell.execute_reply.started":"2024-08-06T16:35:10.905904Z","shell.execute_reply":"2024-08-06T16:35:11.209503Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-08-06T16:35:11.211697Z","iopub.execute_input":"2024-08-06T16:35:11.212075Z","iopub.status.idle":"2024-08-06T16:35:11.605290Z","shell.execute_reply.started":"2024-08-06T16:35:11.212038Z","shell.execute_reply":"2024-08-06T16:35:11.604373Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\nimport os\nimport cv2\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.applications import ResNet50\nfrom tensorflow.keras import layers, models\n\n# Define the preprocessing function for ResNet50 model\ndef preprocess_image(img_path, target_size=(224, 224)):\n    \"\"\"\n    Preprocesses an image for ResNet50 model input.\n    \n    Parameters:\n    - img_path: Path to the image file.\n    - target_size: Desired size to resize the image to.\n    \n    Returns:\n    - img_array: Preprocessed image as a numpy array.\n    \"\"\"\n    img = image.load_img(img_path, target_size=target_size)\n    img_array = image.img_to_array(img)\n    img_array = np.expand_dims(img_array, axis=0)  # Add batch dimension\n    img_array /= 255.0  # Normalize to [0, 1] range\n    return img_array\n\n# Define the prediction function\ndef predict_image(model, img_path):\n    \"\"\"\n    Predicts whether an image is FAKE or REAL using the given model.\n    \n    Parameters:\n    - model: The trained Keras model.\n    - img_path: Path to the image file.\n    \n    Returns:\n    - prediction: The predicted label ('FAKE' or 'REAL').\n    \"\"\"\n    img_array = preprocess_image(img_path)\n    prediction = model.predict(img_array)\n    return \"FAKE\" if prediction < 0.5 else \"REAL\"\n\n# Test real-time predictions\ndef test_real_time_predictions(real_folder, fake_folder, num_images=75):\n    \"\"\"\n    Tests the model on a set of real and fake images and prints the results.\n    \n    Parameters:\n    - real_folder: Path to the folder containing REAL images.\n    - fake_folder: Path to the folder containing FAKE images.\n    - num_images: Total number of images to test from both folders.\n    \"\"\"\n    # Get list of images in each folder\n    real_images = os.listdir(real_folder)\n    fake_images = os.listdir(fake_folder)\n\n    # Check if there are enough images in each folder\n    if len(real_images) < num_images // 2 or len(fake_images) < (num_images // 2) + 1:\n        raise ValueError(f\"Not enough images in one of the folders. Found {len(real_images)} real images and {len(fake_images)} fake images.\")\n\n    # Select a subset of images from each folder\n    selected_real_images = real_images[:num_images // 2]\n    selected_fake_images = fake_images[:(num_images // 2) + 1]\n\n    # Combine the selected images and their folders\n    selected_images = selected_real_images + selected_fake_images\n    folders = [real_folder] * (num_images // 2) + [fake_folder] * ((num_images // 2) + 1)\n\n    correct_predictions = 0\n    total_images = len(selected_images)\n\n    plt.figure(figsize=(20, 20))  # Adjusted figure size for 75 images\n\n    for index, img_file in enumerate(selected_images):\n        img_path = os.path.join(folders[index], img_file)\n        prediction = predict_image(model_resnet50, img_path)\n        real_label = 'FAKE' if 'FAKE' in folders[index].upper() else 'REAL'\n        \n        if prediction == real_label:\n            correct_predictions += 1\n        \n        plt.subplot(8, 10, index + 1)  # Adjusted subplot grid for 75 images\n        img = cv2.imread(img_path)\n        plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))\n        plt.title(f'Pred: {prediction}\\nReal: {real_label}')\n        plt.axis('off')\n\n    plt.show()\n\n    # Calculate and print accuracy\n    if total_images > 0:\n        accuracy = (correct_predictions / total_images) * 100\n        print(f'Accuracy: {accuracy:.2f}%')\n    else:\n        print(\"No images selected for testing.\")\n\n# Example paths (update these with your actual paths)\nreal_folder = '/kaggle/input/animal/test/REAL'\nfake_folder = '/kaggle/input/animal/test/FAKE'\n\n# Test real-time predictions\ntest_real_time_predictions(real_folder, fake_folder, num_images=75)\n","metadata":{"execution":{"iopub.status.busy":"2024-08-06T17:48:37.223565Z","iopub.execute_input":"2024-08-06T17:48:37.223986Z","iopub.status.idle":"2024-08-06T17:48:47.204228Z","shell.execute_reply.started":"2024-08-06T17:48:37.223956Z","shell.execute_reply":"2024-08-06T17:48:47.203332Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Save the entire model\nmodel_resnet50.save('/kaggle/working/resnet50_model.h5')  # or use .keras extension\n","metadata":{"execution":{"iopub.status.busy":"2024-08-06T16:35:11.606591Z","iopub.execute_input":"2024-08-06T16:35:11.607322Z","iopub.status.idle":"2024-08-06T16:35:12.064840Z","shell.execute_reply.started":"2024-08-06T16:35:11.607284Z","shell.execute_reply":"2024-08-06T16:35:12.063986Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}