{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.11","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":87323,"databundleVersionId":9934427,"sourceType":"competition"}],"dockerImageVersionId":31012,"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\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-04-12T17:54:34.481297Z","iopub.execute_input":"2025-04-12T17:54:34.481573Z","iopub.status.idle":"2025-04-12T17:54:38.177614Z","shell.execute_reply.started":"2025-04-12T17:54:34.481544Z","shell.execute_reply":"2025-04-12T17:54:38.176565Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Import necessary libraries\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.utils import Sequence\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout, BatchNormalization\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.callbacks import EarlyStopping\nfrom sklearn.model_selection import train_test_split\nimport os\n\n# Load CSV and encode labels\nfile_path = \"/kaggle/input/cidaut-ai-fake-scene-classification-2024/train.csv\"\ndf = pd.read_csv(file_path)\ndf['label'] = df['label'].map({'real': 1, 'editada': 0})\ndf.to_csv('train_modified.csv', index=False)\n\n# Custom Data Generator Class\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\n        self.shuffle = shuffle\n        self.indexes = np.arange(len(self.dataframe))\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))\n\n    def __getitem__(self, index):\n        batch_indexes = self.indexes[index * self.batch_size:(index + 1) * self.batch_size]\n        batch_data = self.dataframe.iloc[batch_indexes]\n        images, labels = [], []\n        for _, row in batch_data.iterrows():\n            img_path = os.path.join(self.image_folder, row['image'])\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(row['label'])\n        return np.array(images), np.array(labels)\n\n    def on_epoch_end(self):\n        if self.shuffle:\n            np.random.shuffle(self.indexes)\n\n# Prepare data splits\ntrain_df, val_df = train_test_split(df, test_size=0.3, random_state=42)\n\n# Parameters\nimage_folder = '/kaggle/input/cidaut-ai-fake-scene-classification-2024/Train/'\nbatch_size = 32\nimage_size = (224, 224)\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\n# Generators\ntrain_generator = ImageLabelGenerator(train_df, batch_size, image_size, image_folder, shuffle=True, augmentation_params=augmentation_params)\nval_generator = ImageLabelGenerator(val_df, batch_size, image_size, image_folder, shuffle=False)\n\n# Custom CNN Model\nmodel = Sequential([\n    Conv2D(32, (3, 3), activation='relu', input_shape=(224, 224, 3)),\n    BatchNormalization(),\n    MaxPooling2D(2, 2),\n\n    Conv2D(64, (3, 3), activation='relu'),\n    BatchNormalization(),\n    MaxPooling2D(2, 2),\n\n    Conv2D(128, (3, 3), activation='relu'),\n    BatchNormalization(),\n    MaxPooling2D(2, 2),\n\n    Flatten(),\n    Dense(128, activation='relu'),\n    Dropout(0.5),\n    Dense(1, activation='sigmoid')\n])\n\n# Compile\nmodel.compile(optimizer=Adam(learning_rate=0.0001), loss='binary_crossentropy', metrics=['accuracy'])\n\n# Early stopping\nearly_stopping = EarlyStopping(monitor='val_loss', patience=5, restore_best_weights=True)\n\n# Train\nhistory = model.fit(\n    train_generator,\n    epochs=20,\n    validation_data=val_generator,\n    callbacks=[early_stopping]\n)\n\n# Prediction on test data\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/'\nimage_filenames = [f for f in os.listdir(test_folder) if f.endswith(('.jpg', '.png', '.jpeg'))]\n\nresults = []\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# Save submission\nsubmission_df = pd.DataFrame(results)\nsubmission_csv_path = 'submission_cnn.csv'\nsubmission_df.to_csv(submission_csv_path, index=False)\nprint(f\"Predictions saved to {submission_csv_path}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-12T19:57:05.824549Z","iopub.execute_input":"2025-04-12T19:57:05.824851Z","iopub.status.idle":"2025-04-12T20:04:02.211646Z","shell.execute_reply.started":"2025-04-12T19:57:05.824825Z","shell.execute_reply":"2025-04-12T20:04:02.210154Z"}},"outputs":[],"execution_count":null}]}