{"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":"gpu","dataSources":[{"sourceId":87323,"databundleVersionId":9934427,"sourceType":"competition"}],"dockerImageVersionId":31013,"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-04-26T04:57:29.368874Z","iopub.execute_input":"2025-04-26T04:57:29.369045Z","iopub.status.idle":"2025-04-26T04:57:32.926389Z","shell.execute_reply.started":"2025-04-26T04:57:29.369029Z","shell.execute_reply":"2025-04-26T04:57:32.925552Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers, models\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.callbacks import ModelCheckpoint\nfrom tensorflow.keras.applications import EfficientNetB7\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.utils.class_weight import compute_class_weight\nimport matplotlib.pyplot as plt\nimport warnings\nwarnings.filterwarnings('ignore')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-26T04:57:32.927852Z","iopub.execute_input":"2025-04-26T04:57:32.928289Z","iopub.status.idle":"2025-04-26T04:57:46.101405Z","shell.execute_reply.started":"2025-04-26T04:57:32.928262Z","shell.execute_reply":"2025-04-26T04:57:46.100733Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"TRAIN_IMG_PATH = '/kaggle/input/cidaut-ai-fake-scene-classification-2024/Train'\nTEST_IMG_PATH = '/kaggle/input/cidaut-ai-fake-scene-classification-2024/Test'","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-26T04:57:46.102200Z","iopub.execute_input":"2025-04-26T04:57:46.102745Z","iopub.status.idle":"2025-04-26T04:57:46.106435Z","shell.execute_reply.started":"2025-04-26T04:57:46.102718Z","shell.execute_reply":"2025-04-26T04:57:46.105742Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_metadata = pd.read_csv('/kaggle/input/cidaut-ai-fake-scene-classification-2024/train.csv')\ntest_metadata =  pd.read_csv('/kaggle/input/cidaut-ai-fake-scene-classification-2024/sample_submission.csv')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-26T04:57:46.108120Z","iopub.execute_input":"2025-04-26T04:57:46.108315Z","iopub.status.idle":"2025-04-26T04:57:46.148261Z","shell.execute_reply.started":"2025-04-26T04:57:46.108299Z","shell.execute_reply":"2025-04-26T04:57:46.147618Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class_weights = compute_class_weight(\n    'balanced',  \n    classes=np.unique(train_metadata.label),  \n    y=train_metadata.label \n)\n\nclass_weight_dict = {i: class_weights[i] for i in range(len(class_weights))}","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-26T04:57:46.149060Z","iopub.execute_input":"2025-04-26T04:57:46.149311Z","iopub.status.idle":"2025-04-26T04:57:46.182482Z","shell.execute_reply.started":"2025-04-26T04:57:46.149294Z","shell.execute_reply":"2025-04-26T04:57:46.182033Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def custom_preprocessing(image):\n    image = image / 255.0\n    mean = np.array([0.485, 0.456, 0.406])\n    std = np.array([0.229, 0.224, 0.225])\n    return (image - mean) / std\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-26T04:57:46.183339Z","iopub.execute_input":"2025-04-26T04:57:46.183564Z","iopub.status.idle":"2025-04-26T04:57:46.187042Z","shell.execute_reply.started":"2025-04-26T04:57:46.183541Z","shell.execute_reply":"2025-04-26T04:57:46.186394Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_datagen = ImageDataGenerator(\n    rotation_range=15,\n    horizontal_flip=True,\n    brightness_range=[0.8, 1.2],\n    preprocessing_function=custom_preprocessing,\n    validation_split=0.2\n)\n\ntrain_img = train_datagen.flow_from_dataframe(\n    dataframe=train_metadata,\n    directory=TRAIN_IMG_PATH,\n    x_col='image',\n    y_col='label',\n    target_size=(512, 512),\n    batch_size=8,\n    class_mode='binary',\n    subset='training'\n)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-26T04:57:46.187756Z","iopub.execute_input":"2025-04-26T04:57:46.188058Z","iopub.status.idle":"2025-04-26T04:57:46.585320Z","shell.execute_reply.started":"2025-04-26T04:57:46.188034Z","shell.execute_reply":"2025-04-26T04:57:46.584781Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"datagen = ImageDataGenerator(rescale=1./255)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-26T04:57:46.585969Z","iopub.execute_input":"2025-04-26T04:57:46.586180Z","iopub.status.idle":"2025-04-26T04:57:46.589509Z","shell.execute_reply.started":"2025-04-26T04:57:46.586155Z","shell.execute_reply":"2025-04-26T04:57:46.588721Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"val_img = train_datagen.flow_from_dataframe(\n    dataframe=train_metadata,\n    directory=TRAIN_IMG_PATH,\n    x_col='image',\n    y_col='label',\n    target_size=(512, 512),\n    batch_size=8,\n    class_mode='binary',\n    subset='validation'\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-26T04:57:46.590312Z","iopub.execute_input":"2025-04-26T04:57:46.590739Z","iopub.status.idle":"2025-04-26T04:57:46.616224Z","shell.execute_reply.started":"2025-04-26T04:57:46.590722Z","shell.execute_reply":"2025-04-26T04:57:46.615334Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_img = datagen.flow_from_dataframe(\n    dataframe=test_metadata,\n    directory=TEST_IMG_PATH,\n    x_col='image',\n    target_size=(512, 512),\n    batch_size=8,\n    class_mode=None,\n    shuffle=False\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-26T04:57:46.619230Z","iopub.execute_input":"2025-04-26T04:57:46.619475Z","iopub.status.idle":"2025-04-26T04:57:46.719288Z","shell.execute_reply.started":"2025-04-26T04:57:46.619448Z","shell.execute_reply":"2025-04-26T04:57:46.718756Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_img = datagen.flow_from_dataframe(\n    dataframe=test_metadata,\n    directory=TEST_IMG_PATH,\n    x_col='image',\n    target_size=(512, 512),\n    batch_size=8,\n    class_mode=None,\n    shuffle=False\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-26T04:57:46.719897Z","iopub.execute_input":"2025-04-26T04:57:46.720095Z","iopub.status.idle":"2025-04-26T04:57:46.727206Z","shell.execute_reply.started":"2025-04-26T04:57:46.720079Z","shell.execute_reply":"2025-04-26T04:57:46.726585Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class_names = {v: k for k, v in train_img.class_indices.items()}","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-26T04:57:46.727892Z","iopub.execute_input":"2025-04-26T04:57:46.728092Z","iopub.status.idle":"2025-04-26T04:57:46.737342Z","shell.execute_reply.started":"2025-04-26T04:57:46.728061Z","shell.execute_reply":"2025-04-26T04:57:46.736603Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"input_shape = (512,512,3)\nnum_classes = 1\n\nimage_input = layers.Input(shape=input_shape)\neffnet = EfficientNetB7(weights='imagenet', include_top=False, input_shape=input_shape)\nx = effnet(image_input)\nx = layers.GlobalAveragePooling2D()(x)\nx = layers.Flatten()(x)  \nx = layers.Dense(1024, activation='relu')(x) \nx = layers.Dense(num_classes,activation='sigmoid')(x)\nmodel =  models.Model(inputs=image_input, outputs=x)\nmodel.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-26T04:57:46.738146Z","iopub.execute_input":"2025-04-26T04:57:46.738435Z","execution_failed":"2025-04-26T04:57:49.351Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=1e-4), \n              loss = tf.keras.losses.BinaryCrossentropy(from_logits=False),\n              metrics=['accuracy','AUC']) \n\nchkpnt_loss = ModelCheckpoint(\n    'best_model_loss.keras',           \n    monitor='val_loss',          \n    verbose=1,                  \n    save_best_only=True,        \n    mode='min',                 \n    save_weights_only=False,     \n)\n\nchkpnt_auc = ModelCheckpoint(\n    'best_model_auc.keras',            \n    monitor='val_AUC',         \n    verbose=1,                  \n    save_best_only=True,       \n    mode='max',                \n    save_weights_only=False,    \n)","metadata":{"trusted":true,"execution":{"execution_failed":"2025-04-26T04:57:49.352Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"history = model.fit(train_img,\n                    validation_data=val_img,\n                    epochs=64,\n                    class_weight=class_weight_dict,\n                    callbacks=[chkpnt_loss,chkpnt_auc])","metadata":{"trusted":true,"execution":{"execution_failed":"2025-04-26T04:57:49.352Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.figure(figsize=(8, 6))\nplt.plot(history.history['loss'], label='Training Loss')\nplt.plot(history.history['val_loss'], label='Validation Loss')\nplt.title('Training vs Validation Loss')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.legend()\nplt.show()","metadata":{"trusted":true,"execution":{"execution_failed":"2025-04-26T04:57:49.352Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.figure(figsize=(8, 6))\nplt.plot(history.history['accuracy'], label='Training Accuracy')\nplt.plot(history.history['val_accuracy'], label='Validation Accuracy')\nplt.title('Training vs Validation Accuracy')\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.legend()\nplt.show()","metadata":{"trusted":true,"execution":{"execution_failed":"2025-04-26T04:57:49.352Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"filenames = test_img.filenames\npredictions = model.predict(test_img)\npredicted_labels = (predictions > 0.5).astype(int)\nsubmission = pd.DataFrame({'image': filenames, 'label': predicted_labels.flatten()})\nsubmission.to_csv('submission.csv', index=False)","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}