{"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.6.6"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":4104,"databundleVersionId":46661,"sourceType":"competition"},{"sourceId":14774,"databundleVersionId":875431,"isSourceIdPinned":false,"sourceType":"competition"},{"sourceId":187731,"sourceType":"datasetVersion","datasetId":80814},{"sourceId":7352272,"sourceType":"datasetVersion","datasetId":4244554},{"sourceId":7869237,"sourceType":"datasetVersion","datasetId":4617269},{"sourceId":243364696,"sourceType":"kernelVersion"}],"dockerImageVersionId":28772,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import json\nimport math\nimport os\n\nimport cv2\nfrom PIL import Image\nimport numpy as np\nfrom keras import layers\nfrom keras.applications import DenseNet121\nfrom keras.callbacks import Callback, ModelCheckpoint\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom keras.optimizers import Adam\nfrom keras.utils import Sequence\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import cohen_kappa_score, accuracy_score\nimport scipy\nimport tensorflow as tf\nfrom tqdm import tqdm\n\n%matplotlib inline","metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","trusted":true,"execution":{"iopub.status.busy":"2025-08-25T07:57:31.178785Z","iopub.execute_input":"2025-08-25T07:57:31.179062Z","iopub.status.idle":"2025-08-25T07:57:33.882906Z","shell.execute_reply.started":"2025-08-25T07:57:31.179007Z","shell.execute_reply":"2025-08-25T07:57:33.882053Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Set random seed for reproducibility.","metadata":{}},{"cell_type":"code","source":"np.random.seed(2019)\ntf.set_random_seed(2019)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-25T07:57:33.885884Z","iopub.execute_input":"2025-08-25T07:57:33.886191Z","iopub.status.idle":"2025-08-25T07:57:33.913223Z","shell.execute_reply.started":"2025-08-25T07:57:33.886132Z","shell.execute_reply":"2025-08-25T07:57:33.912741Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Loading & Exploration","metadata":{}},{"cell_type":"code","source":"# train_df = pd.read_csv('../input/aptos2019-blindness-detection/train.csv')\n# test_df = pd.read_csv('../input/aptos2019-blindness-detection/test.csv')\n# print(train_df.shape)\n# print(test_df.shape)\n# train_df.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-25T07:57:33.914872Z","iopub.execute_input":"2025-08-25T07:57:33.915100Z","iopub.status.idle":"2025-08-25T07:57:33.918180Z","shell.execute_reply.started":"2025-08-25T07:57:33.915054Z","shell.execute_reply":"2025-08-25T07:57:33.917467Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os, random\n\nbase_dir = \"/kaggle/input/eyepacs-aptos-messidor-diabetic-retinopathy/augmented_resized_V2/train\"\n\n# Lists to store info\nimage_ids = []\ndiagnoses = []\n\n# Loop through each class folder\nfor label in sorted(os.listdir(base_dir)):\n    class_dir = os.path.join(base_dir, label)\n    if not os.path.isdir(class_dir):\n        continue\n    \n    # Get all image files in this class\n    files = [f for f in os.listdir(class_dir) if f.lower().endswith(('.png', '.jpg', '.jpeg'))]\n    \n    # Shuffle for randomness\n    random.shuffle(files)\n    \n    # Take only one tenth (at least 1 image to avoid empty)\n    n = max(1, len(files) // 5)\n    files = files[:n]\n    \n    for img_file in files:\n        image_id = os.path.splitext(img_file)[0]\n        image_ids.append(image_id)\n        diagnoses.append(int(label))\n\nprint(\"Total images selected:\", len(image_ids))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-25T07:57:33.919385Z","iopub.execute_input":"2025-08-25T07:57:33.919665Z","iopub.status.idle":"2025-08-25T07:57:35.163011Z","shell.execute_reply.started":"2025-08-25T07:57:33.919594Z","shell.execute_reply":"2025-08-25T07:57:35.162270Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_df = pd.DataFrame({\n    \"id_code\": image_ids,\n    \"diagnosis\": diagnoses\n})\n\n# Shuffle (optional)\ntrain_df = train_df.sample(frac=1, random_state=42).reset_index(drop=True)\n\n# Inspect\nprint(train_df.head())\nprint(train_df['diagnosis'].value_counts())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-25T07:57:35.164349Z","iopub.execute_input":"2025-08-25T07:57:35.164571Z","iopub.status.idle":"2025-08-25T07:57:35.183631Z","shell.execute_reply.started":"2025-08-25T07:57:35.164534Z","shell.execute_reply":"2025-08-25T07:57:35.183025Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os, random\nimport pandas as pd\n\nbase_dir = \"/kaggle/input/eyepacs-aptos-messidor-diabetic-retinopathy/augmented_resized_V2/val\"\n\n# Lists to store info\nimage_ids = []\ndiagnoses = []\n\n# Loop through each class folder\nfor label in sorted(os.listdir(base_dir)):\n    class_dir = os.path.join(base_dir, label)\n    if not os.path.isdir(class_dir):\n        continue\n\n    # Collect all images for this class\n    img_files = [f for f in os.listdir(class_dir) if f.lower().endswith(('.png', '.jpg', '.jpeg'))]\n\n    # Randomly shuffle and keep 1/10\n    random.shuffle(img_files)\n    take_n = max(1, len(img_files) // 5)   # at least 1 image\n    img_files = img_files[:take_n]\n\n    for img_file in img_files:\n        image_id = os.path.splitext(img_file)[0]\n        image_ids.append(image_id)\n        diagnoses.append(int(label))\n\n# Create dataframe\nval_df = pd.DataFrame({\n    \"id_code\": image_ids,\n    \"diagnosis\": diagnoses\n})\n\n# Shuffle final dataframe\nval_df = val_df.sample(frac=1, random_state=42).reset_index(drop=True)\n\n# Inspect\nprint(val_df.head())\nprint(val_df['diagnosis'].value_counts())\nprint(\"Total validation images selected:\", len(val_df))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-25T07:57:35.184671Z","iopub.execute_input":"2025-08-25T07:57:35.184985Z","iopub.status.idle":"2025-08-25T07:57:35.394859Z","shell.execute_reply.started":"2025-08-25T07:57:35.184933Z","shell.execute_reply":"2025-08-25T07:57:35.394102Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# base_dir = \"/kaggle/input/eyepacs-aptos-messidor-diabetic-retinopathy/augmented_resized_V2/test\"\n\n# # Lists to store info\n# image_ids = []\n# diagnoses = []\n# # Loop through each class folder\n# for label in sorted(os.listdir(base_dir)):\n#     class_dir = os.path.join(base_dir, label)\n#     if not os.path.isdir(class_dir):\n#         continue\n#     for img_file in os.listdir(class_dir):\n#         if img_file.lower().endswith(('.png', '.jpg', '.jpeg')):\n#             # Use the filename without extension as id_code\n#             image_id = os.path.splitext(img_file)[0]\n#             image_ids.append(image_id)\n#             diagnoses.append(int(label))\n\n\n# test_df = pd.DataFrame({\n#     \"id_code\": image_ids,\n#     \"diagnosis\": diagnoses\n# })\n\n# # Shuffle (optional)\n# test_df = test_df.sample(frac=1, random_state=42).reset_index(drop=True)\n\n# # Inspect\n# print(test_df.head())\n# print(test_df['diagnosis'].value_counts())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-25T07:57:35.395853Z","iopub.execute_input":"2025-08-25T07:57:35.396045Z","iopub.status.idle":"2025-08-25T07:57:35.399461Z","shell.execute_reply.started":"2025-08-25T07:57:35.396012Z","shell.execute_reply":"2025-08-25T07:57:35.398840Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# import os, random\n# import pandas as pd\n\n# base_dir = \"/kaggle/input/eyepacs-aptos-messidor-diabetic-retinopathy/augmented_resized_V2/test\"\n\n# # Lists to store info\n# image_ids = []\n# diagnoses = []\n\n# # Loop through each class folder\n# for label in sorted(os.listdir(base_dir)):\n#     class_dir = os.path.join(base_dir, label)\n#     if not os.path.isdir(class_dir):\n#         continue\n\n#     # Collect all images for this class\n#     img_files = [f for f in os.listdir(class_dir) if f.lower().endswith(('.png', '.jpg', '.jpeg'))]\n\n#     # Randomly shuffle and keep 1/10\n#     random.shuffle(img_files)\n#     take_n = max(1, len(img_files) // 2.5)   # at least 1 image\n#     img_files = img_files[:take_n]\n\n#     for img_file in img_files:\n#         image_id = os.path.splitext(img_file)[0]\n#         image_ids.append(image_id)\n#         diagnoses.append(int(label))\n\n# # Create dataframe\n# test_df = pd.DataFrame({\n#     \"id_code\": image_ids,\n#     \"diagnosis\": diagnoses\n# })\n\n# # Shuffle final dataframe\n# test_df = test_df.sample(frac=1, random_state=42).reset_index(drop=True)\n\n# # Inspect\n# print(test_df.head())\n# print(test_df['diagnosis'].value_counts())\n# print(\"Total test images selected:\", len(test_df))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-25T07:57:35.400930Z","iopub.execute_input":"2025-08-25T07:57:35.401234Z","iopub.status.idle":"2025-08-25T07:57:35.411135Z","shell.execute_reply.started":"2025-08-25T07:57:35.401177Z","shell.execute_reply":"2025-08-25T07:57:35.410272Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_dir = \"/kaggle/input/aptos2019-blindness-detection/test_images\"\n\n# Collect all image files\nall_images = [f for f in os.listdir(test_dir) if f.lower().endswith(('.png', '.jpg', '.jpeg'))]\n\n# Shuffle and take 10%\n# random.shuffle(all_images)\ntake_n = max(1, len(all_images))\nselected_images = all_images[:take_n]\n\n# Prepare dataframe\ntest_df = pd.DataFrame({\n    \"id_code\": [os.path.splitext(f)[0] for f in selected_images]\n})\n\nprint(\"Total test images selected:\", len(test_df))\nprint(test_df.head())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-25T07:57:35.412160Z","iopub.execute_input":"2025-08-25T07:57:35.412391Z","iopub.status.idle":"2025-08-25T07:57:35.456046Z","shell.execute_reply.started":"2025-08-25T07:57:35.412344Z","shell.execute_reply":"2025-08-25T07:57:35.455323Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### Displaying some Sample Images","metadata":{}},{"cell_type":"code","source":"def display_samples(df, columns=4, rows=3):\n    fig=plt.figure(figsize=(5*columns, 4*rows))\n\n    for i in range(columns*rows):\n        image_path = df.loc[i,'id_code']\n        image_id = df.loc[i,'diagnosis']\n        img = cv2.imread(f'/kaggle/input/eyepacs-aptos-messidor-diabetic-retinopathy/augmented_resized_V2/train/{image_id}/{image_path}.jpg')\n        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n        \n        fig.add_subplot(rows, columns, i+1)\n        plt.title(image_id)\n        plt.imshow(img)\n    \n    plt.tight_layout()\n\ndisplay_samples(train_df)","metadata":{"_kg_hide-input":true,"trusted":true,"execution":{"iopub.status.busy":"2025-08-25T07:57:35.457221Z","iopub.execute_input":"2025-08-25T07:57:35.457702Z","iopub.status.idle":"2025-08-25T07:57:37.990252Z","shell.execute_reply.started":"2025-08-25T07:57:35.457468Z","shell.execute_reply":"2025-08-25T07:57:37.989243Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Resize Images\n\nWe will resize the images to 224x224, then create a single numpy array to hold the data.","metadata":{}},{"cell_type":"code","source":"def get_pad_width(im, new_shape, is_rgb=True):\n    pad_diff = new_shape - im.shape[0], new_shape - im.shape[1]\n    t, b = math.floor(pad_diff[0]/2), math.ceil(pad_diff[0]/2)\n    l, r = math.floor(pad_diff[1]/2), math.ceil(pad_diff[1]/2)\n    if is_rgb:\n        pad_width = ((t,b), (l,r), (0, 0))\n    else:\n        pad_width = ((t,b), (l,r))\n    return pad_width\n\ndef preprocess_image(image_path, desired_size=224):\n    im = Image.open(image_path)\n    im = im.resize((desired_size, )*2, resample=Image.LANCZOS)\n    \n    return im\n\ndef preprocess_image_nature(image_path, desired_size=224, clahe_clip=2.0, clahe_grid=(8,8)):\n    \"\"\"\n    Preprocessing inspired by Nature paper:\n    - Convert to grayscale\n    - Apply CLAHE\n    - Resize to desired size\n    \"\"\"\n    # Read the image\n    im = cv2.imread(image_path)\n    \n    # Convert to grayscale\n    im_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)\n    \n    # Apply CLAHE\n    clahe = cv2.createCLAHE(clipLimit=clahe_clip, tileGridSize=clahe_grid)\n    im_clahe = clahe.apply(im_gray)\n    \n    # Convert back to 3 channels (so model can take 3-channel input)\n    im_final = cv2.merge([im_clahe, im_clahe, im_clahe])\n    \n    # Resize\n    im_resized = cv2.resize(im_final, (desired_size, desired_size), interpolation=cv2.INTER_LANCZOS4)\n    \n    return im_resized","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-25T07:57:37.991485Z","iopub.execute_input":"2025-08-25T07:57:37.991723Z","iopub.status.idle":"2025-08-25T07:57:38.000592Z","shell.execute_reply.started":"2025-08-25T07:57:37.991668Z","shell.execute_reply":"2025-08-25T07:57:37.999874Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# N = train_df.shape[0]\n# # x_train = np.empty((N, 224, 224, 3), dtype=np.uint8)\n# x_train = np.empty((N, 600, 600, 3), dtype=np.uint8)\n\n# for i, image_id, diag in enumerate(tqdm(train_df['id_code'], train_df['diagnosis'])):\n#     x_train[i, :, :, :] = preprocess_image(\n#         f'/kaggle/input/eyepacs-aptos-messidor-diabetic-retinopathy/augmented_resized_V2/train/{diag}/{image_id}.jpg'\n#     )\n\n# N = train_df.shape[0]\n# x_train = np.empty((N, 224, 224, 3), dtype=np.uint8)\n\n# for i, (image_id, diag) in enumerate(tqdm(zip(train_df['id_code'], train_df['diagnosis']), total=N)):\n#     x_train[i, :, :, :] = preprocess_image(\n#         f'/kaggle/input/eyepacs-aptos-messidor-diabetic-retinopathy/augmented_resized_V2/train/{diag}/{image_id}.jpg'\n#     )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-25T07:57:38.001838Z","iopub.execute_input":"2025-08-25T07:57:38.002104Z","iopub.status.idle":"2025-08-25T07:57:38.009256Z","shell.execute_reply.started":"2025-08-25T07:57:38.002065Z","shell.execute_reply":"2025-08-25T07:57:38.008632Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# N = test_df.shape[0]\n# x_test = np.empty((N, 224, 224, 3), dtype=np.uint8)\n\n# # for i, image_id in enumerate(tqdm(test_df['id_code'])):\n# for i, (image_id, diag) in enumerate(tqdm(zip(test_df['id_code'], test_df['diagnosis']), total=N)):\n#     x_test[i, :, :, :] = preprocess_image(\n#         f'/kaggle/input/eyepacs-aptos-messidor-diabetic-retinopathy/augmented_resized_V2/test/{diag}/{image_id}.jpg'\n#     )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-25T07:57:38.010233Z","iopub.execute_input":"2025-08-25T07:57:38.010507Z","iopub.status.idle":"2025-08-25T07:57:38.020997Z","shell.execute_reply.started":"2025-08-25T07:57:38.010452Z","shell.execute_reply":"2025-08-25T07:57:38.020338Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# N = len(test_df)\n# x_test = np.empty((N, 224, 224, 3), dtype=np.uint8)\n# # \n# for i, image_id in enumerate(tqdm(test_df['id_code'], total=N)):\n#     img_path = os.path.join(test_dir, f\"{image_id}.png\")  # adjust extension if needed\n#     x_test[i, :, :, :] = preprocess_image(img_path)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-25T07:57:38.021930Z","iopub.execute_input":"2025-08-25T07:57:38.022175Z","iopub.status.idle":"2025-08-25T07:57:38.030139Z","shell.execute_reply.started":"2025-08-25T07:57:38.022138Z","shell.execute_reply":"2025-08-25T07:57:38.029323Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# y_train = pd.get_dummies(train_df['diagnosis']).values\n\n# print(x_train.shape)\n# print(y_train.shape)\n# print(x_test.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-25T07:57:38.031175Z","iopub.execute_input":"2025-08-25T07:57:38.031425Z","iopub.status.idle":"2025-08-25T07:57:38.039120Z","shell.execute_reply.started":"2025-08-25T07:57:38.031373Z","shell.execute_reply":"2025-08-25T07:57:38.038605Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Creating multilabels\n\nInstead of predicting a single label, we will change our target to be a multilabel problem; i.e., if the target is a certain class, then it encompasses all the classes before it. E.g. encoding a class 4 retinopathy would usually be `[0, 0, 0, 1]`, but in our case we will predict `[1, 1, 1, 1]`. For more details, please check out [Lex's kernel](https://www.kaggle.com/lextoumbourou/blindness-detection-resnet34-ordinal-targets).","metadata":{}},{"cell_type":"code","source":"# y_train_multi = np.empty(y_train.shape, dtype=y_train.dtype)\n# y_train_multi[:, 4] = y_train[:, 4]\n\n# for i in range(3, -1, -1):\n#     y_train_multi[:, i] = np.logical_or(y_train[:, i], y_train_multi[:, i+1])\n\n# print(\"Original y_train:\", y_train.sum(axis=0))\n# print(\"Multilabel version:\", y_train_multi.sum(axis=0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-25T07:57:38.040002Z","iopub.execute_input":"2025-08-25T07:57:38.040176Z","iopub.status.idle":"2025-08-25T07:57:38.048373Z","shell.execute_reply.started":"2025-08-25T07:57:38.040144Z","shell.execute_reply":"2025-08-25T07:57:38.047621Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Now we can split it into a training and validation set.","metadata":{}},{"cell_type":"code","source":"# # x_train, x_val, y_train, y_val = train_test_split(\n# #     x_train, y_train_multi, \n# #     test_size=0.15, \n# #     random_state=2019\n# # )\n\n# N_val = val_df.shape[0]\n# x_val = np.empty((N_val, 224, 224, 3), dtype=np.uint8)\n# y_val = val_df['diagnosis'].values  # or one-hot encode if needed\n\n# for i in tqdm(range(N_val)):\n#     image_id = val_df.loc[i, 'id_code']\n#     diag = val_df.loc[i, 'diagnosis']\n#     x_val[i] = preprocess_image(\n#         f\"/kaggle/input/eyepacs-aptos-messidor-diabetic-retinopathy/augmented_resized_V2/val/{diag}/{image_id}.jpg\"\n#     )\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-25T07:57:38.051393Z","iopub.execute_input":"2025-08-25T07:57:38.051581Z","iopub.status.idle":"2025-08-25T07:57:38.057305Z","shell.execute_reply.started":"2025-08-25T07:57:38.051548Z","shell.execute_reply":"2025-08-25T07:57:38.056454Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# y_val = pd.get_dummies(val_df['diagnosis']).values\n\n# print(x_val.shape)\n# print(y_val.shape)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-25T07:57:38.058396Z","iopub.execute_input":"2025-08-25T07:57:38.058590Z","iopub.status.idle":"2025-08-25T07:57:38.068999Z","shell.execute_reply.started":"2025-08-25T07:57:38.058555Z","shell.execute_reply":"2025-08-25T07:57:38.068261Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Mixup & Data Generator\n\nPlease Note: Although I show how to construct Mixup, **it is currently unused**. Please see notice at the top of the kernel.","metadata":{}},{"cell_type":"code","source":"# # Instead of loading all images into memory, create a custom generator\n# class MemoryEfficientDataGenerator(Sequence):\n#     def __init__(self, df, base_dir, batch_size=32, shuffle=True, preprocessing_func=preprocess_image):\n#         self.df = df\n#         self.base_dir = base_dir\n#         self.batch_size = batch_size\n#         self.shuffle = shuffle\n#         self.preprocessing_func = preprocessing_func\n#         self.indices = np.arange(len(df))\n#         if self.shuffle:\n#             np.random.shuffle(self.indices)\n        \n#     def __len__(self):\n#         return int(np.ceil(len(self.df) / self.batch_size))\n    \n#     def __getitem__(self, idx):\n#         batch_indices = self.indices[idx * self.batch_size:(idx + 1) * self.batch_size]\n#         return self._generate_batch(batch_indices)\n    \n#     def _generate_batch(self, batch_indices):\n#         batch_x = np.empty((len(batch_indices), 224, 224, 3), dtype=np.uint8)\n#         batch_y = np.zeros((len(batch_indices), 5))\n        \n#         for i, idx in enumerate(batch_indices):\n#             row = self.df.iloc[idx]\n#             image_id = row['id_code']\n#             diagnosis = row['diagnosis']\n            \n#             img_path = f\"{self.base_dir}/{diagnosis}/{image_id}.jpg\"\n#             img = self.preprocessing_func(img_path)\n#             # Convert PIL Image to numpy array\n#             batch_x[i] = np.array(img)\n            \n#             # Multi-label encoding (cumulative)\n#             for j in range(diagnosis + 1):\n#                 batch_y[i, j] = 1\n            \n#         return batch_x, batch_y\n    \n#     def on_epoch_end(self):\n#         if self.shuffle:\n#             np.random.shuffle(self.indices)\n\n# # Memory-efficient Mixup Generator\n# class MemoryEfficientMixupGenerator:\n#     def __init__(self, df, base_dir, batch_size=32, alpha=0.2, shuffle=True, \n#                  datagen=None, preprocessing_func=preprocess_image):\n#         self.df = df\n#         self.base_dir = base_dir\n#         self.batch_size = batch_size\n#         self.alpha = alpha\n#         self.shuffle = shuffle\n#         self.datagen = datagen\n#         self.preprocessing_func = preprocessing_func\n#         self.sample_num = len(df)\n        \n#     def __call__(self):\n#         while True:\n#             indexes = self._get_exploration_order()\n#             itr_num = int(len(indexes) // (self.batch_size * 2))\n            \n#             for i in range(itr_num):\n#                 batch_ids = indexes[i * self.batch_size * 2:(i + 1) * self.batch_size * 2]\n#                 X, y = self._data_generation(batch_ids)\n#                 yield X, y\n    \n#     def _get_exploration_order(self):\n#         indexes = np.arange(self.sample_num)\n#         if self.shuffle:\n#             np.random.shuffle(indexes)\n#         return indexes\n    \n#     def _load_image(self, idx):\n#         row = self.df.iloc[idx]\n#         image_id = row['id_code']\n#         diagnosis = row['diagnosis']\n#         img_path = f\"{self.base_dir}/{diagnosis}/{image_id}.jpg\"\n#         return self.preprocessing_func(img_path)\n    \n#     def _data_generation(self, batch_ids):\n#         l = np.random.beta(self.alpha, self.alpha, self.batch_size)\n#         X_l = l.reshape(self.batch_size, 1, 1, 1)\n#         y_l = l.reshape(self.batch_size, 1)\n        \n#         # Load images on-demand\n#         X1 = np.array([self._load_image(idx) for idx in batch_ids[:self.batch_size]])\n#         X2 = np.array([self._load_image(idx) for idx in batch_ids[self.batch_size:]])\n        \n#         X = X1 * X_l + X2 * (1 - X_l)\n        \n#         if self.datagen:\n#             for i in range(self.batch_size):\n#                 X[i] = self.datagen.random_transform(X[i])\n#                 X[i] = self.datagen.standardize(X[i])\n        \n#         # Create multi-label encoded labels\n#         y1 = np.zeros((self.batch_size, 5))\n#         y2 = np.zeros((self.batch_size, 5))\n        \n#         for i, idx in enumerate(batch_ids[:self.batch_size]):\n#             diagnosis = self.df.iloc[idx]['diagnosis']\n#             for j in range(diagnosis + 1):\n#                 y1[i, j] = 1\n                \n#         for i, idx in enumerate(batch_ids[self.batch_size:]):\n#             diagnosis = self.df.iloc[idx]['diagnosis']\n#             for j in range(diagnosis + 1):\n#                 y2[i, j] = 1\n        \n#         y = y1 * y_l + y2 * (1 - y_l)\n        \n#         return X, y","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-25T07:57:38.069929Z","iopub.execute_input":"2025-08-25T07:57:38.070179Z","iopub.status.idle":"2025-08-25T07:57:38.080760Z","shell.execute_reply.started":"2025-08-25T07:57:38.070133Z","shell.execute_reply":"2025-08-25T07:57:38.080138Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class MemoryEfficientDataGenerator(Sequence):\n    def __init__(self, df, base_dir, batch_size=32, shuffle=True, preprocessing_func=preprocess_image_nature):\n        self.df = df\n        self.base_dir = base_dir\n        self.batch_size = batch_size\n        self.shuffle = shuffle\n        self.preprocessing_func = preprocessing_func\n        self.indices = np.arange(len(df))\n        if self.shuffle:\n            np.random.shuffle(self.indices)\n        \n    def __len__(self):\n        return int(np.ceil(len(self.df) / self.batch_size))\n    \n    def __getitem__(self, idx):\n        batch_indices = self.indices[idx * self.batch_size:(idx + 1) * self.batch_size]\n        return self._generate_batch(batch_indices)\n    \n    def _generate_batch(self, batch_indices):\n        batch_x = np.empty((len(batch_indices), 224, 224, 3), dtype=np.uint8)\n        batch_y = np.zeros((len(batch_indices), 5))\n        \n        for i, idx in enumerate(batch_indices):\n            row = self.df.iloc[idx]\n            image_id = row['id_code']\n            diagnosis = row['diagnosis']\n            \n            img_path = f\"{self.base_dir}/{diagnosis}/{image_id}.jpg\"\n            img = self.preprocessing_func(img_path)\n            # Convert PIL Image to numpy array\n            batch_x[i] = np.array(img)\n            \n            # Multi-label encoding (cumulative)\n            for j in range(diagnosis + 1):\n                batch_y[i, j] = 1\n            \n        return batch_x, batch_y\n    \n    def on_epoch_end(self):\n        if self.shuffle:\n            np.random.shuffle(self.indices)\n\n# Memory-efficient Mixup Generator\nclass MemoryEfficientMixupGenerator:\n    def __init__(self, df, base_dir, batch_size=32, alpha=0.2, shuffle=True, \n                 datagen=None, preprocessing_func=preprocess_image):\n        self.df = df\n        self.base_dir = base_dir\n        self.batch_size = batch_size\n        self.alpha = alpha\n        self.shuffle = shuffle\n        self.datagen = datagen\n        self.preprocessing_func = preprocessing_func\n        self.sample_num = len(df)\n        \n    def __call__(self):\n        while True:\n            indexes = self._get_exploration_order()\n            itr_num = int(len(indexes) // (self.batch_size * 2))\n            \n            for i in range(itr_num):\n                batch_ids = indexes[i * self.batch_size * 2:(i + 1) * self.batch_size * 2]\n                X, y = self._data_generation(batch_ids)\n                yield X, y\n    \n    def _get_exploration_order(self):\n        indexes = np.arange(self.sample_num)\n        if self.shuffle:\n            np.random.shuffle(indexes)\n        return indexes\n    \n    def _load_image(self, idx):\n        row = self.df.iloc[idx]\n        image_id = row['id_code']\n        diagnosis = row['diagnosis']\n        img_path = f\"{self.base_dir}/{diagnosis}/{image_id}.jpg\"\n        img = self.preprocessing_func(img_path)\n        # Convert PIL Image to numpy array\n        return np.array(img)\n    \n    def _data_generation(self, batch_ids):\n        l = np.random.beta(self.alpha, self.alpha, self.batch_size)\n        X_l = l.reshape(self.batch_size, 1, 1, 1)\n        y_l = l.reshape(self.batch_size, 1)\n        \n        # Load images on-demand\n        X1 = np.array([self._load_image(idx) for idx in batch_ids[:self.batch_size]])\n        X2 = np.array([self._load_image(idx) for idx in batch_ids[self.batch_size:]])\n        \n        X = X1 * X_l + X2 * (1 - X_l)\n        \n        if self.datagen:\n            for i in range(self.batch_size):\n                X[i] = self.datagen.random_transform(X[i])\n                X[i] = self.datagen.standardize(X[i])\n        \n        # Create multi-label encoded labels\n        y1 = np.zeros((self.batch_size, 5))\n        y2 = np.zeros((self.batch_size, 5))\n        \n        for i, idx in enumerate(batch_ids[:self.batch_size]):\n            diagnosis = self.df.iloc[idx]['diagnosis']\n            for j in range(diagnosis + 1):\n                y1[i, j] = 1\n                \n        for i, idx in enumerate(batch_ids[self.batch_size:]):\n            diagnosis = self.df.iloc[idx]['diagnosis']\n            for j in range(diagnosis + 1):\n                y2[i, j] = 1\n        \n        y = y1 * y_l + y2 * (1 - y_l)\n        \n        return X, y\n\n\nclass TestDataGenerator:\n    def __init__(self, df, test_dir, batch_size=32):\n        self.df = df\n        self.test_dir = test_dir\n        self.batch_size = batch_size\n        \n    def predict_all(self, model):\n        predictions = []\n        \n        for i in range(0, len(self.df), self.batch_size):\n            batch_df = self.df.iloc[i:i+self.batch_size]\n            batch_x = np.empty((len(batch_df), 224, 224, 3), dtype=np.uint8)\n            \n            for j, (idx, row) in enumerate(batch_df.iterrows()):\n                image_id = row['id_code']\n                img_path = os.path.join(self.test_dir, f\"{image_id}.png\")\n                batch_x[j] = np.array(preprocess_image_nature(img_path))\n            \n            batch_pred = model.predict(batch_x, verbose=0)\n            predictions.append(batch_pred)\n            \n        return np.concatenate(predictions, axis=0)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-25T07:57:38.081837Z","iopub.execute_input":"2025-08-25T07:57:38.082061Z","iopub.status.idle":"2025-08-25T07:57:38.107626Z","shell.execute_reply.started":"2025-08-25T07:57:38.082008Z","shell.execute_reply":"2025-08-25T07:57:38.106766Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# BATCH_SIZE = 32\n\ndef create_datagen():\n    return ImageDataGenerator(\n        zoom_range=0.15,  # set range for random zoom\n        # set mode for filling points outside the input boundaries\n        fill_mode='constant',\n        cval=0.,  # value used for fill_mode = \"constant\"\n        horizontal_flip=True,  # randomly flip images\n        vertical_flip=True,  # randomly flip images\n    )\n\n# # Using original generator\n# data_generator = create_datagen().flow(x_train, y_train, batch_size=BATCH_SIZE, seed=2019)\n# # Using Mixup\n# mixup_generator = MixupGenerator(x_train, y_train, batch_size=BATCH_SIZE, alpha=0.2, datagen=create_datagen())()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-25T07:57:38.108754Z","iopub.execute_input":"2025-08-25T07:57:38.109023Z","iopub.status.idle":"2025-08-25T07:57:38.118610Z","shell.execute_reply.started":"2025-08-25T07:57:38.108974Z","shell.execute_reply":"2025-08-25T07:57:38.118055Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Don't load x_train into memory! Instead use generators:\nBATCH_SIZE = 32\n\n# For regular training\ntrain_generator = MemoryEfficientDataGenerator(\n    train_df, \n    \"/kaggle/input/eyepacs-aptos-messidor-diabetic-retinopathy/augmented_resized_V2/train\",\n    batch_size=BATCH_SIZE,\n    preprocessing_func=preprocess_image_nature\n)\n\n# For validation (you can keep your current val loading if it's small enough)\nval_generator = MemoryEfficientDataGenerator(\n    val_df,\n    \"/kaggle/input/eyepacs-aptos-messidor-diabetic-retinopathy/augmented_resized_V2/val\",\n    batch_size=BATCH_SIZE,\n    shuffle=False,\n    preprocessing_func=preprocess_image_nature\n)\n\n# For mixup training\nmixup_generator = MemoryEfficientMixupGenerator(\n    train_df,\n    \"/kaggle/input/eyepacs-aptos-messidor-diabetic-retinopathy/augmented_resized_V2/train\",\n    batch_size=BATCH_SIZE,\n    alpha=0.2,\n    datagen=create_datagen(),\n    preprocessing_func=preprocess_image_nature\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-25T07:57:38.119454Z","iopub.execute_input":"2025-08-25T07:57:38.119716Z","iopub.status.idle":"2025-08-25T07:57:38.135774Z","shell.execute_reply.started":"2025-08-25T07:57:38.119660Z","shell.execute_reply":"2025-08-25T07:57:38.135010Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"true_labels = np.array([1, 0, 1, 1, 0, 1])\npred_labels = np.array([1, 0, 0, 0, 0, 1])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-25T07:57:38.136801Z","iopub.execute_input":"2025-08-25T07:57:38.137022Z","iopub.status.idle":"2025-08-25T07:57:38.145450Z","shell.execute_reply.started":"2025-08-25T07:57:38.136979Z","shell.execute_reply":"2025-08-25T07:57:38.144848Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"accuracy_score(true_labels, pred_labels)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-25T07:57:38.146241Z","iopub.execute_input":"2025-08-25T07:57:38.146411Z","iopub.status.idle":"2025-08-25T07:57:38.158793Z","shell.execute_reply.started":"2025-08-25T07:57:38.146381Z","shell.execute_reply":"2025-08-25T07:57:38.157988Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"cohen_kappa_score(true_labels, pred_labels)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-25T07:57:38.159791Z","iopub.execute_input":"2025-08-25T07:57:38.160128Z","iopub.status.idle":"2025-08-25T07:57:38.170372Z","shell.execute_reply.started":"2025-08-25T07:57:38.159979Z","shell.execute_reply":"2025-08-25T07:57:38.169641Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### Creating keras callback for QWK","metadata":{}},{"cell_type":"code","source":"class Metrics(Callback):\n    def on_train_begin(self, logs={}):\n        self.val_kappas = []\n\n    def on_epoch_end(self, epoch, logs={}):\n        X_val, y_val = self.validation_data[:2]\n        y_val = y_val.sum(axis=1) - 1\n        \n        y_pred = self.model.predict(X_val) > 0.5\n        y_pred = y_pred.astype(int).sum(axis=1) - 1\n\n        _val_kappa = cohen_kappa_score(\n            y_val,\n            y_pred, \n            weights='quadratic'\n        )\n\n        self.val_kappas.append(_val_kappa)\n\n        print(f\"val_kappa: {_val_kappa:.4f}\")\n        \n        if _val_kappa == max(self.val_kappas):\n            print(\"Validation Kappa has improved. Saving model.\")\n            self.model.save('model.h5')\n\n        return\n\n\nclass GeneratorCompatibleKappa(Callback):\n    def __init__(self, val_generator, val_steps):\n        super().__init__()\n        self.val_generator = val_generator\n        self.val_steps = val_steps\n        self.val_kappas = []  # ADD THIS LINE\n        \n    def on_epoch_end(self, epoch, logs={}):\n        # Collect all validation predictions and true labels\n        y_pred_list = []\n        y_true_list = []\n        \n        # Reset generator to start\n        self.val_generator.on_epoch_end()\n        \n        # Get predictions for entire validation set\n        for i in range(self.val_steps):\n            X_val_batch, y_val_batch = self.val_generator[i]\n            \n            # Get predictions\n            y_pred_batch = self.model.predict(X_val_batch, verbose=0)\n            \n            y_pred_list.append(y_pred_batch)\n            y_true_list.append(y_val_batch)\n        \n        # Concatenate all batches\n        y_pred = np.concatenate(y_pred_list, axis=0)\n        y_true = np.concatenate(y_true_list, axis=0)\n        \n        # Convert multi-label to single label for kappa calculation\n        y_true_single = y_true.sum(axis=1) - 1  # Convert back to 0-4 scale\n        y_pred_single = y_pred.sum(axis=1) - 1  # Convert back to 0-4 scale\n        \n        # Round predictions to nearest integer\n        y_pred_single = np.round(np.clip(y_pred_single, 0, 4)).astype(int)\n        \n        # Calculate quadratic weighted kappa\n        kappa = cohen_kappa_score(y_true_single, y_pred_single, weights='quadratic')\n        \n        self.val_kappas.append(kappa)  # ADD THIS LINE\n        \n        print(f\" - val_kappa: {kappa:.4f}\")\n        logs['val_kappa'] = kappa","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-25T07:57:38.171493Z","iopub.execute_input":"2025-08-25T07:57:38.171939Z","iopub.status.idle":"2025-08-25T07:57:38.184565Z","shell.execute_reply.started":"2025-08-25T07:57:38.171885Z","shell.execute_reply":"2025-08-25T07:57:38.184064Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Model: DenseNet-121","metadata":{}},{"cell_type":"code","source":"densenet = DenseNet121(\n    weights='../input/densenet-keras/DenseNet-BC-121-32-no-top.h5',\n    include_top=False,\n    input_shape=(224,224,3)\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-25T07:57:38.185698Z","iopub.execute_input":"2025-08-25T07:57:38.185958Z","iopub.status.idle":"2025-08-25T07:57:58.482611Z","shell.execute_reply.started":"2025-08-25T07:57:38.185895Z","shell.execute_reply":"2025-08-25T07:57:58.481764Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def build_model():\n    model = Sequential()\n    model.add(densenet)\n    model.add(layers.GlobalAveragePooling2D())\n    model.add(layers.Dropout(0.5))\n    model.add(layers.Dense(5, activation='sigmoid'))\n    \n    model.compile(\n        loss='binary_crossentropy',\n        optimizer=Adam(lr=0.00005),\n        metrics=['accuracy']\n    )\n    \n    return model","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-25T07:57:58.483834Z","iopub.execute_input":"2025-08-25T07:57:58.484041Z","iopub.status.idle":"2025-08-25T07:57:58.493406Z","shell.execute_reply.started":"2025-08-25T07:57:58.484005Z","shell.execute_reply":"2025-08-25T07:57:58.492738Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = build_model()\nmodel.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-25T07:57:58.494433Z","iopub.execute_input":"2025-08-25T07:57:58.494697Z","iopub.status.idle":"2025-08-25T07:58:06.615984Z","shell.execute_reply.started":"2025-08-25T07:57:58.494622Z","shell.execute_reply":"2025-08-25T07:58:06.615235Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Training & Evaluation","metadata":{}},{"cell_type":"code","source":"# kappa_metrics = Metrics()\n\n# history = model.fit_generator(\n#     data_generator,\n#     steps_per_epoch=x_train.shape[0] / BATCH_SIZE,\n#     epochs=50,\n#     validation_data=(x_val, y_val),\n#     callbacks=[kappa_metrics]\n# )\n\n# Training becomes:\n# BATCH_SIZE = 32\n\nval_steps = math.ceil(len(val_df) / BATCH_SIZE)\nkappa_metrics = GeneratorCompatibleKappa(val_generator, val_steps)\n\nhistory = model.fit_generator(\n    mixup_generator(),  # or train_generator for regular training\n    steps_per_epoch=len(train_df) // BATCH_SIZE,\n    epochs=50,\n    validation_data=val_generator,  # Now this will work!\n    validation_steps = val_steps,\n    callbacks=[kappa_metrics]\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-25T07:58:06.617040Z","iopub.execute_input":"2025-08-25T07:58:06.617236Z","iopub.status.idle":"2025-08-25T08:00:25.769110Z","shell.execute_reply.started":"2025-08-25T07:58:06.617203Z","shell.execute_reply":"2025-08-25T08:00:25.768138Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"with open('history.json', 'w') as f:\n    json.dump(history.history, f)\n\nhistory_df = pd.DataFrame(history.history)\nhistory_df[['loss', 'val_loss']].plot()\nhistory_df[['acc', 'val_acc']].plot()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-25T08:00:25.770818Z","iopub.execute_input":"2025-08-25T08:00:25.771087Z","iopub.status.idle":"2025-08-25T08:00:26.166978Z","shell.execute_reply.started":"2025-08-25T08:00:25.771041Z","shell.execute_reply":"2025-08-25T08:00:26.166245Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.plot(kappa_metrics.val_kappas)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-25T08:00:26.168200Z","iopub.execute_input":"2025-08-25T08:00:26.168471Z","iopub.status.idle":"2025-08-25T08:00:26.340229Z","shell.execute_reply.started":"2025-08-25T08:00:26.168426Z","shell.execute_reply":"2025-08-25T08:00:26.338887Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.save_weights('model.h5')\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-25T08:00:26.341284Z","iopub.execute_input":"2025-08-25T08:00:26.341519Z","iopub.status.idle":"2025-08-25T08:00:28.028055Z","shell.execute_reply.started":"2025-08-25T08:00:26.341467Z","shell.execute_reply":"2025-08-25T08:00:28.027310Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Then load and use\nmodel.load_weights('model.h5')\n\n# y_val_pred = model.predict(x_val)\n# y_val_pred = model.predict(x_val)\n\n# def compute_score_inv(threshold):\n#     y1 = y_val_pred > threshold\n#     y1 = y1.astype(int).sum(axis=1) - 1\n#     y2 = y_val.sum(axis=1) - 1\n#     score = cohen_kappa_score(y1, y2, weights='quadratic')\n    \n#     return 1 - score\n\n# simplex = scipy.optimize.minimize(\n#     compute_score_inv, 0.5, method='nelder-mead'\n# )\n\n# best_threshold = simplex['x'][0]\n\n# Get predictions using the generator\ny_val_pred_list = []\ny_val_true_list = []\n\nfor i in range(len(val_generator)):\n    X_batch, y_batch = val_generator[i]\n    pred_batch = model.predict(X_batch, verbose=0)\n    \n    y_val_pred_list.append(pred_batch)\n    y_val_true_list.append(y_batch)\n\ny_val_pred = np.concatenate(y_val_pred_list, axis=0)\ny_val = np.concatenate(y_val_true_list, axis=0)\n\n# Rest of the code remains the same\ndef compute_score_inv(threshold):\n    y1 = y_val_pred > threshold\n    y1 = y1.astype(int).sum(axis=1) - 1\n    y2 = y_val.sum(axis=1) - 1\n    score = cohen_kappa_score(y1, y2, weights='quadratic')\n    \n    return 1 - score\n\nimport scipy.optimize\nsimplex = scipy.optimize.minimize(\n    compute_score_inv, 0.5, method='nelder-mead'\n)\nbest_threshold = simplex['x'][0]\nprint(f\"Best threshold: {best_threshold}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-25T08:00:28.029307Z","iopub.execute_input":"2025-08-25T08:00:28.029598Z","iopub.status.idle":"2025-08-25T08:00:32.700980Z","shell.execute_reply.started":"2025-08-25T08:00:28.029528Z","shell.execute_reply":"2025-08-25T08:00:32.700244Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Submit","metadata":{}},{"cell_type":"code","source":"# Use test generator\ntest_generator = TestDataGenerator(test_df, test_dir, batch_size=32)\ny_test_pred = test_generator.predict_all(model)\n\n# Apply optimized threshold and convert to diagnosis\ny_test = y_test_pred > best_threshold  # Use optimized threshold\ny_test = y_test.astype(int).sum(axis=1) - 1\n\ntest_df['diagnosis'] = y_test\ntest_df.to_csv('submission.csv', index=False)\nprint(f\"Submission saved! Predictions range: {y_test.min()} to {y_test.max()}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-25T08:00:32.702215Z","iopub.execute_input":"2025-08-25T08:00:32.702415Z","iopub.status.idle":"2025-08-25T08:02:07.999007Z","shell.execute_reply.started":"2025-08-25T08:00:32.702381Z","shell.execute_reply":"2025-08-25T08:02:07.998167Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# y_test = model.predict(x_test) > 0.5\n# y_test = y_test.astype(int).sum(axis=1) - 1\n\n# test_df['diagnosis'] = y_test\n# test_df.to_csv('submission.csv',index=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-25T08:02:08.000417Z","iopub.execute_input":"2025-08-25T08:02:08.000748Z","iopub.status.idle":"2025-08-25T08:02:08.003923Z","shell.execute_reply.started":"2025-08-25T08:02:08.000692Z","shell.execute_reply":"2025-08-25T08:02:08.003279Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# loss, acc = model.evaluate(x_val, y_val, verbose=0)\n# print(\"Validation Accuracy:\", acc)\n# Comprehensive validation evaluation\ndef comprehensive_validation_eval(model, val_generator, val_steps):\n    y_pred_list = []\n    y_true_list = []\n    total_loss = 0\n    total_acc = 0\n    total_samples = 0\n    \n    for i in range(val_steps):\n        X_batch, y_batch = val_generator[i]\n        \n        # Get predictions and metrics for this batch\n        y_pred_batch = model.predict(X_batch, verbose=0)\n        batch_loss, batch_acc = model.evaluate(X_batch, y_batch, verbose=0)\n        batch_size = len(X_batch)\n        \n        # Store predictions for kappa calculation\n        y_pred_list.append(y_pred_batch)\n        y_true_list.append(y_batch)\n        \n        # Accumulate metrics\n        total_loss += batch_loss * batch_size\n        total_acc += batch_acc * batch_size\n        total_samples += batch_size\n    \n    # Calculate average metrics\n    avg_loss = total_loss / total_samples\n    avg_acc = total_acc / total_samples\n    \n    # Calculate kappa\n    y_pred = np.concatenate(y_pred_list, axis=0)\n    y_true = np.concatenate(y_true_list, axis=0)\n    \n    # Convert to single labels for kappa\n    y_true_single = y_true.sum(axis=1) - 1\n    y_pred_single = (y_pred > best_threshold).astype(int).sum(axis=1) - 1\n    \n    kappa = cohen_kappa_score(y_true_single, y_pred_single, weights='quadratic')\n    \n    return avg_loss, avg_acc, kappa\n\n# Use comprehensive evaluation\nval_loss, val_acc, val_kappa = comprehensive_validation_eval(model, val_generator, val_steps)\nprint(f\"Validation Loss: {val_loss:.4f}\")\nprint(f\"Validation Accuracy: {val_acc:.4f}\")\nprint(f\"Validation Kappa: {val_kappa:.4f}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-25T08:02:08.005015Z","iopub.execute_input":"2025-08-25T08:02:08.005231Z","iopub.status.idle":"2025-08-25T08:02:09.926302Z","shell.execute_reply.started":"2025-08-25T08:02:08.005187Z","shell.execute_reply":"2025-08-25T08:02:09.925581Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}