{"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":"gpu","dataSources":[{"sourceId":87323,"databundleVersionId":9934427,"sourceType":"competition"}],"dockerImageVersionId":30822,"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\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\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","trusted":true,"execution":{"iopub.status.busy":"2025-01-10T21:27:56.704214Z","iopub.execute_input":"2025-01-10T21:27:56.704543Z","iopub.status.idle":"2025-01-10T21:27:58.974324Z","shell.execute_reply.started":"2025-01-10T21:27:56.704518Z","shell.execute_reply":"2025-01-10T21:27:58.944458Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"file_path = \"/kaggle/input/cidaut-ai-fake-scene-classification-2024/train.csv\"  \ndf = pd.read_csv(file_path)\n\ndf['label'] = df['label'].map({'real': 1, 'editada': 0})\ndf.to_csv('train_modified.csv', index=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-10T21:28:34.099350Z","iopub.execute_input":"2025-01-10T21:28:34.099678Z","iopub.status.idle":"2025-01-10T21:28:34.109558Z","shell.execute_reply.started":"2025-01-10T21:28:34.099650Z","shell.execute_reply":"2025-01-10T21:28:34.108676Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.utils import Sequence\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\nclass ImageLabelGenerator(Sequence):\n    def __init__(self, dataframe, batch_size, image_size, image_folder, shuffle=True,augmentation_params=None, **kwargs):\n        super().__init__(**kwargs)\n        self.dataframe = dataframe\n        self.batch_size = batch_size\n        self.image_size = image_size\n        self.image_folder = image_folder  # Folder where images are stored\n        self.shuffle = shuffle\n        self.indexes = np.arange(len(self.dataframe))  # Track indexes for shuffling\n\n        self.augmentation_params = augmentation_params\n        if self.augmentation_params:\n            self.datagen = ImageDataGenerator(**self.augmentation_params)\n        else:\n            self.datagen = ImageDataGenerator()  \n\n    def __len__(self):\n        return int(np.floor(len(self.dataframe) / self.batch_size))  # Number of batches per epoch\n\n    def __getitem__(self, index):\n        # Get the indexes of the images for this batch\n        batch_indexes = self.indexes[index * self.batch_size:(index + 1) * self.batch_size]\n        \n        # Get the image filenames and labels for this batch\n        batch_data = self.dataframe.iloc[batch_indexes]\n        \n        # Load images and their labels\n        images = []\n        labels = []\n        for _, row in batch_data.iterrows():\n            img_filename = row['image']  # Filename column\n            label = row['label']  # Label column\n            img_path = self.image_folder + img_filename  # Construct the full image path\n            img = image.load_img(img_path, target_size=self.image_size)\n            img = image.img_to_array(img)\n            mean = np.mean(img)\n            std = np.std(img)\n            img = (img - mean) / std\n            images.append(img)\n            labels.append(label)\n        \n        return np.array(images), np.array(labels)\n\n    def on_epoch_end(self):\n        if self.shuffle:\n            # Shuffle the indexes at the end of each epoch\n            np.random.shuffle(self.indexes)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-10T22:23:17.138530Z","iopub.execute_input":"2025-01-10T22:23:17.138880Z","iopub.status.idle":"2025-01-10T22:23:17.147682Z","shell.execute_reply.started":"2025-01-10T22:23:17.138852Z","shell.execute_reply":"2025-01-10T22:23:17.146474Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n\ntrain_df, val_df = train_test_split(df, test_size=0.3, random_state=42)\n\n\nimage_folder = '/kaggle/input/cidaut-ai-fake-scene-classification-2024/Train/' \n\nbatch_size = 32\nimage_size = (224, 224)  \n\naugmentation_params = {\n    'rotation_range': 30,\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\ntrain_generator = ImageLabelGenerator(train_df, batch_size, image_size, image_folder,shuffle=True,\n    augmentation_params=augmentation_params)\nval_generator = ImageLabelGenerator(val_df, batch_size, image_size, image_folder,shuffle=False)\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-10T22:46:06.772484Z","iopub.execute_input":"2025-01-10T22:46:06.772854Z","iopub.status.idle":"2025-01-10T22:46:06.780755Z","shell.execute_reply.started":"2025-01-10T22:46:06.772823Z","shell.execute_reply":"2025-01-10T22:46:06.779864Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import GlobalAveragePooling2D, Dense, Dropout\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.callbacks import EarlyStopping\nfrom tensorflow.keras.applications import ResNet50V2\n\nbase_model = ResNet50V2(weights='imagenet', include_top=False, input_shape=(224, 224, 3))\n\nbase_model.trainable = False\n\nx = base_model.output\nx = GlobalAveragePooling2D()(x)\n\nx = Dense(128, activation='relu')(x)\nx = Dropout(0.5)(x)\n\n\npredictions = Dense(1, activation='sigmoid')(x)\n\nmodel = Model(inputs=base_model.input, outputs=predictions)\n\nmodel.compile(optimizer=Adam(learning_rate=0.0001), loss='binary_crossentropy', metrics=['accuracy'])\n\nearly_stopping = EarlyStopping(monitor='val_loss', patience=5, restore_best_weights=True)\n\nhistory = model.fit(\n    train_generator,\n    epochs=20,\n    validation_data=val_generator,\n    callbacks=[early_stopping]\n)\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-10T22:46:14.470195Z","iopub.execute_input":"2025-01-10T22:46:14.470561Z","iopub.status.idle":"2025-01-10T22:47:10.699485Z","shell.execute_reply.started":"2025-01-10T22:46:14.470525Z","shell.execute_reply":"2025-01-10T22:47:10.698515Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport pandas as pd\nfrom tensorflow.keras.preprocessing import image\n\ndef predict_image(img_path):\n    img = image.load_img(img_path, target_size=(224, 224))  \n    img_array = image.img_to_array(img) / 255.0 \n    img_array = np.expand_dims(img_array, axis=0)  \n    prediction = model.predict(img_array) \n    return 1 if prediction[0] > 0.5 else 0\n\ntest_folder = '/kaggle/input/cidaut-ai-fake-scene-classification-2024/Test/'  # Replace with the actual path to your test folder\n\n\nimage_filenames = [f for f in os.listdir(test_folder) if f.endswith(('.jpg', '.png', '.jpeg'))]\n\nresults = []\n\nfor img_name in image_filenames:\n    img_path = os.path.join(test_folder, img_name) \n    prediction = predict_image(img_path)  \n    results.append({'image': img_name, 'label': prediction})  \n\n\nsubmission_df = pd.DataFrame(results)\n\nsubmission_csv_path = 'submission4.csv'\nsubmission_df.to_csv(submission_csv_path, index=False)\n\nprint(f\"Predictions saved to {submission_csv_path}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-10T22:42:00.727234Z","iopub.execute_input":"2025-01-10T22:42:00.727658Z","iopub.status.idle":"2025-01-10T22:42:17.931954Z","shell.execute_reply.started":"2025-01-10T22:42:00.727620Z","shell.execute_reply":"2025-01-10T22:42:17.931220Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sub_data = pd.read_csv(\"submission4.csv\")\nsub_data","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-10T22:42:21.291399Z","iopub.execute_input":"2025-01-10T22:42:21.291702Z","iopub.status.idle":"2025-01-10T22:42:21.303783Z","shell.execute_reply.started":"2025-01-10T22:42:21.291679Z","shell.execute_reply":"2025-01-10T22:42:21.303029Z"}},"outputs":[],"execution_count":null}]}