{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":11848,"databundleVersionId":862157,"sourceType":"competition"}],"dockerImageVersionId":31193,"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\n# for 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-12-14T07:27:10.255976Z","iopub.execute_input":"2025-12-14T07:27:10.256271Z","iopub.status.idle":"2025-12-14T07:27:10.261060Z","shell.execute_reply.started":"2025-12-14T07:27:10.256241Z","shell.execute_reply":"2025-12-14T07:27:10.260242Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np \nimport pandas as pd\n\nimport os\nbase_dir = '../input/'\nprint(os.listdir(base_dir))\n\n\nimport matplotlib.pyplot as plt\nplt.style.use(\"ggplot\")\n\n\nimport cv2\n\n\nimport tensorflow as tf\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, ReduceLROnPlateau\n\n\nimport sklearn\nfrom sklearn.metrics import roc_auc_score, accuracy_score\nfrom sklearn.model_selection import train_test_split\nfrom PIL import Image","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-14T12:38:58.347826Z","iopub.execute_input":"2025-12-14T12:38:58.348182Z","iopub.status.idle":"2025-12-14T12:39:16.603685Z","shell.execute_reply.started":"2025-12-14T12:38:58.348155Z","shell.execute_reply":"2025-12-14T12:39:16.602921Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"full_train_df = pd.read_csv(\"../input/histopathologic-cancer-detection/train_labels.csv\")\nfull_train_df.head()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-14T12:39:25.611091Z","iopub.execute_input":"2025-12-14T12:39:25.611705Z","iopub.status.idle":"2025-12-14T12:39:25.954284Z","shell.execute_reply.started":"2025-12-14T12:39:25.611646Z","shell.execute_reply":"2025-12-14T12:39:25.953386Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(\"Train Size: {}\".format(len(os.listdir('../input/histopathologic-cancer-detection/train/'))))\nprint(\"Test Size: {}\".format(len(os.listdir('../input/histopathologic-cancer-detection/test/'))))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-14T06:24:58.170181Z","iopub.execute_input":"2025-12-14T06:24:58.170517Z","iopub.status.idle":"2025-12-14T06:25:01.221721Z","shell.execute_reply.started":"2025-12-14T06:24:58.170493Z","shell.execute_reply":"2025-12-14T06:25:01.220941Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"labels_count = full_train_df.label.value_counts()\nplt.figure(figsize=(6,4))\n\nlabels_count.plot(kind='barh')\n\nplt.title(\"Class Distribution\")\nplt.xlabel(\"Number of Samples\")\nplt.ylabel(\"Class\")\nplt.grid(axis='x', alpha=0.3)\n\nplt.show()\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-14T12:39:38.940948Z","iopub.execute_input":"2025-12-14T12:39:38.941313Z","iopub.status.idle":"2025-12-14T12:39:39.215562Z","shell.execute_reply.started":"2025-12-14T12:39:38.941287Z","shell.execute_reply":"2025-12-14T12:39:39.214734Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\nSAMPLE_SIZE = 80000\n\n\ntrain_path = '../input/histopathologic-cancer-detection/train/'\ntest_path = '../input/histopathologic-cancer-detection/test/'\n\n\ndf_negatives = full_train_df[full_train_df['label'] == 0].sample(SAMPLE_SIZE, random_state=42)\ndf_positives = full_train_df[full_train_df['label'] == 1].sample(SAMPLE_SIZE, random_state=42)\n\n\ntrain_df = sklearn.utils.shuffle(pd.concat([df_positives, df_negatives], axis=0).reset_index(drop=True))\n\ntrain_df.shape\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-14T12:40:15.749486Z","iopub.execute_input":"2025-12-14T12:40:15.749830Z","iopub.status.idle":"2025-12-14T12:40:15.827857Z","shell.execute_reply.started":"2025-12-14T12:40:15.749805Z","shell.execute_reply":"2025-12-14T12:40:15.826975Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\ntrain_df['id'] = train_df['id'].apply(lambda x: x + '.tif')\nfull_train_df['id'] = full_train_df['id'].apply(lambda x: x + '.tif')\n\n\ntrain_split, valid_split = train_test_split(train_df, test_size=0.1, stratify=train_df['label'], random_state=42)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-14T12:40:18.615807Z","iopub.execute_input":"2025-12-14T12:40:18.616093Z","iopub.status.idle":"2025-12-14T12:40:18.826441Z","shell.execute_reply.started":"2025-12-14T12:40:18.616074Z","shell.execute_reply":"2025-12-14T12:40:18.825604Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\nsample_sub = pd.read_csv(\"../input/histopathologic-cancer-detection/sample_submission.csv\")\nsample_sub['id'] = sample_sub['id'].apply(lambda x: x + '.tif')\n\ntest_generator = test_datagen.flow_from_dataframe(\n    dataframe=sample_sub,\n    directory=test_path,\n    x_col='id',\n    y_col=None,\n    target_size=(96, 96),\n    batch_size=128,\n    class_mode=None,\n    shuffle=False\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-14T12:41:55.119512Z","iopub.execute_input":"2025-12-14T12:41:55.120229Z","iopub.status.idle":"2025-12-14T12:42:02.013183Z","shell.execute_reply.started":"2025-12-14T12:41:55.120202Z","shell.execute_reply":"2025-12-14T12:42:02.012014Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\ntrain_datagen = ImageDataGenerator(\n    rescale=1./255,\n    horizontal_flip=True,\n    vertical_flip=True,\n    rotation_range=20,\n    shear_range=0.2,\n    zoom_range=0.2,\n    width_shift_range=0.2,\n    height_shift_range=0.2,\n    fill_mode='nearest'\n)\n\n\nvalid_datagen = ImageDataGenerator(rescale=1./255)\n\n\ntrain_generator = train_datagen.flow_from_dataframe(\n    dataframe=train_split,\n    directory=train_path,\n    x_col='id',\n    y_col='label',\n    target_size=(96, 96),\n    batch_size=128,\n    class_mode='raw',\n    seed=42\n)\n\n\nvalid_generator = valid_datagen.flow_from_dataframe(\n    dataframe=valid_split,\n    directory=train_path,\n    x_col='id',\n    y_col='label',\n    target_size=(96, 96),\n    batch_size=128,\n    class_mode='raw',\n    seed=42\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-14T06:28:06.847095Z","iopub.execute_input":"2025-12-14T06:28:06.847692Z","iopub.status.idle":"2025-12-14T06:32:35.107301Z","shell.execute_reply.started":"2025-12-14T06:28:06.847668Z","shell.execute_reply":"2025-12-14T06:32:35.106254Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\nmodel = Sequential([\n    Conv2D(32, (3, 3), activation='relu', input_shape=(96, 96, 3)),\n    BatchNormalization(),\n    MaxPooling2D(2, 2),\n    \n    Conv2D(64, (2, 2), activation='relu', padding='same'),\n    BatchNormalization(),\n    MaxPooling2D(2, 2),\n    \n    Conv2D(128, (3, 3), activation='relu', padding='same'),\n    BatchNormalization(),\n    MaxPooling2D(2, 2),\n    \n    Conv2D(256, (3, 3), activation='relu', padding='same'),\n    BatchNormalization(),\n    MaxPooling2D(2, 2),\n    \n    Conv2D(512, (3, 3), activation='relu', padding='same'),\n    BatchNormalization(),\n    MaxPooling2D(2, 2),\n    \n    Flatten(),\n    Dense(1024, activation='relu'),\n    Dropout(0.4),\n    Dense(512, activation='relu'),\n    Dropout(0.4),\n    Dense(1, activation='sigmoid')\n])\n\nmodel.compile(optimizer=Adam(learning_rate=0.00015), loss='binary_crossentropy', metrics=['accuracy', tf.keras.metrics.AUC(name='auc')])\n\nmodel.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-14T06:32:59.351198Z","iopub.execute_input":"2025-12-14T06:32:59.351540Z","iopub.status.idle":"2025-12-14T06:33:01.245980Z","shell.execute_reply.started":"2025-12-14T06:32:59.351519Z","shell.execute_reply":"2025-12-14T06:33:01.245221Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\nearly_stop = EarlyStopping(monitor='val_loss', patience=5, restore_best_weights=True)\nreduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=3, min_lr=1e-6)\n\nhistory = model.fit(\n    train_generator,\n    steps_per_epoch=len(train_generator),\n    epochs=16,\n    validation_data=valid_generator,\n    validation_steps=len(valid_generator),\n    callbacks=[early_stop, reduce_lr]\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-14T06:35:22.945174Z","iopub.execute_input":"2025-12-14T06:35:22.945809Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\nmodel.save('best_model.h5')","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\npreds = model.predict(test_generator, steps=len(test_generator))\n\n\npreds = preds.flatten()\n\n\nsample_sub['label'] = preds\nsample_sub['id'] = sample_sub['id'].str.replace('.tif', '')  \nsample_sub.to_csv('submission.csv', index=False)\nsample_sub.head()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(\"Hello\")","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}