{"metadata":{"kernelspec":{"name":"python3","display_name":"Python 3","language":"python"},"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":187731,"sourceType":"datasetVersion","datasetId":80814},{"sourceId":7352272,"sourceType":"datasetVersion","datasetId":4244554},{"sourceId":7869237,"sourceType":"datasetVersion","datasetId":4617269}],"dockerImageVersionId":31089,"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\n\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.applications import DenseNet121\nfrom tensorflow.keras.callbacks import Callback, ModelCheckpoint\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.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\nimport random\n\n\n#\n\n%matplotlib inline","metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","execution":{"iopub.status.busy":"2025-08-26T21:08:15.221954Z","iopub.execute_input":"2025-08-26T21:08:15.222120Z","iopub.status.idle":"2025-08-26T21:08:28.288508Z","shell.execute_reply.started":"2025-08-26T21:08:15.222104Z","shell.execute_reply":"2025-08-26T21:08:28.287725Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\nimport tensorflow as tf\nimport time\n\n# Make sure TensorFlow sees your GPU\nprint(\"Num GPUs Available: \", len(tf.config.list_physical_devices('GPU')))\n\n# Create a large random matrix and do a matrix multiplication on GPU\nmatrix_size = 5000\na = tf.random.uniform((matrix_size, matrix_size))\nb = tf.random.uniform((matrix_size, matrix_size))\n\n# Warm-up (first run can be slower)\ntf.matmul(a, b)\n\n# Measure GPU computation time\nstart = time.time()\nc = tf.matmul(a, b)\nend = time.time()\n\nprint(f\"Time for 5000x5000 matrix multiplication: {end - start:.4f} seconds\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-26T21:08:28.290175Z","iopub.execute_input":"2025-08-26T21:08:28.290613Z","iopub.status.idle":"2025-08-26T21:08:29.101262Z","shell.execute_reply.started":"2025-08-26T21:08:28.290595Z","shell.execute_reply":"2025-08-26T21:08:29.100399Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.mixed_precision import set_global_policy\nset_global_policy('mixed_float16')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-26T21:08:29.104412Z","iopub.execute_input":"2025-08-26T21:08:29.104623Z","iopub.status.idle":"2025-08-26T21:08:29.172933Z","shell.execute_reply.started":"2025-08-26T21:08:29.104607Z","shell.execute_reply":"2025-08-26T21:08:29.172224Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Set random seed for reproducibility.","metadata":{}},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"seed = 2019\nnp.random.seed(seed)\ntf.random.set_seed(seed)\nrandom.seed(seed)\nos.environ[\"PYTHONHASHSEED\"] = str(seed)","metadata":{"execution":{"iopub.status.busy":"2025-08-26T21:08:29.173801Z","iopub.execute_input":"2025-08-26T21:08:29.174021Z","iopub.status.idle":"2025-08-26T21:08:29.184600Z","shell.execute_reply.started":"2025-08-26T21:08:29.173997Z","shell.execute_reply":"2025-08-26T21:08:29.183888Z"},"trusted":true},"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":{"execution":{"iopub.status.busy":"2025-08-26T21:08:29.185300Z","iopub.execute_input":"2025-08-26T21:08:29.185558Z","iopub.status.idle":"2025-08-26T21:08:29.199574Z","shell.execute_reply.started":"2025-08-26T21:08:29.185538Z","shell.execute_reply":"2025-08-26T21:08:29.198889Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"base_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) // 10)\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":{"execution":{"iopub.status.busy":"2025-08-26T21:08:29.201645Z","iopub.execute_input":"2025-08-26T21:08:29.201860Z","iopub.status.idle":"2025-08-26T21:08:30.280220Z","shell.execute_reply.started":"2025-08-26T21:08:29.201837Z","shell.execute_reply":"2025-08-26T21:08:30.279477Z"},"trusted":true},"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":{"execution":{"iopub.status.busy":"2025-08-26T21:08:30.281022Z","iopub.execute_input":"2025-08-26T21:08:30.281279Z","iopub.status.idle":"2025-08-26T21:08:30.305491Z","shell.execute_reply.started":"2025-08-26T21:08:30.281256Z","shell.execute_reply":"2025-08-26T21:08:30.304925Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\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) // 10)   # 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":{"execution":{"iopub.status.busy":"2025-08-26T21:08:30.306172Z","iopub.execute_input":"2025-08-26T21:08:30.306465Z","iopub.status.idle":"2025-08-26T21:08:30.484513Z","shell.execute_reply.started":"2025-08-26T21:08:30.306445Z","shell.execute_reply":"2025-08-26T21:08:30.483822Z"},"trusted":true},"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":{"execution":{"iopub.status.busy":"2025-08-26T21:08:30.485395Z","iopub.execute_input":"2025-08-26T21:08:30.485686Z","iopub.status.idle":"2025-08-26T21:08:30.489526Z","shell.execute_reply.started":"2025-08-26T21:08:30.485662Z","shell.execute_reply":"2025-08-26T21:08:30.488790Z"},"trusted":true},"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":{"execution":{"iopub.status.busy":"2025-08-26T21:08:30.490394Z","iopub.execute_input":"2025-08-26T21:08:30.490634Z","iopub.status.idle":"2025-08-26T21:08:30.508563Z","shell.execute_reply.started":"2025-08-26T21:08:30.490610Z","shell.execute_reply":"2025-08-26T21:08:30.507914Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# test_dir = \"input/aptos2019-blindness-detection/test_images\"\n\n# # Collect all image files\n# all_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)\n# take_n = max(1, len(all_images))\n# selected_images = all_images[:take_n]\n\n# # Prepare dataframe\n# test_df = pd.DataFrame({\n#     \"id_code\": [os.path.splitext(f)[0] for f in selected_images]\n# })\n\n# print(\"Total test images selected:\", len(test_df))\n# print(test_df.head())","metadata":{"execution":{"iopub.status.busy":"2025-08-26T21:08:30.509279Z","iopub.execute_input":"2025-08-26T21:08:30.509882Z","iopub.status.idle":"2025-08-26T21:08:30.526837Z","shell.execute_reply.started":"2025-08-26T21:08:30.509865Z","shell.execute_reply":"2025-08-26T21:08:30.526253Z"},"trusted":true},"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,"execution":{"iopub.status.busy":"2025-08-26T21:08:30.527624Z","iopub.execute_input":"2025-08-26T21:08:30.527879Z","iopub.status.idle":"2025-08-26T21:08:33.761678Z","shell.execute_reply.started":"2025-08-26T21:08:30.527857Z","shell.execute_reply":"2025-08-26T21:08:33.760904Z"},"trusted":true},"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    - Normalize to [0,1]\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    # Normalize to [0,1]\n    im_normalized = im_resized.astype(\"float32\") / 255.0\n    \n    return im_normalized","metadata":{"execution":{"iopub.status.busy":"2025-08-26T21:08:33.762814Z","iopub.execute_input":"2025-08-26T21:08:33.763277Z","iopub.status.idle":"2025-08-26T21:08:33.770799Z","shell.execute_reply.started":"2025-08-26T21:08:33.763239Z","shell.execute_reply":"2025-08-26T21:08:33.770158Z"},"trusted":true},"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":{"execution":{"iopub.status.busy":"2025-08-26T21:08:33.771662Z","iopub.execute_input":"2025-08-26T21:08:33.771857Z","iopub.status.idle":"2025-08-26T21:08:33.785683Z","shell.execute_reply.started":"2025-08-26T21:08:33.771841Z","shell.execute_reply":"2025-08-26T21:08:33.784998Z"},"trusted":true},"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":{"execution":{"iopub.status.busy":"2025-08-26T21:08:33.786329Z","iopub.execute_input":"2025-08-26T21:08:33.786549Z","iopub.status.idle":"2025-08-26T21:08:33.799015Z","shell.execute_reply.started":"2025-08-26T21:08:33.786532Z","shell.execute_reply":"2025-08-26T21:08:33.798181Z"},"trusted":true},"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":{"execution":{"iopub.status.busy":"2025-08-26T21:08:33.799944Z","iopub.execute_input":"2025-08-26T21:08:33.800157Z","iopub.status.idle":"2025-08-26T21:08:33.813498Z","shell.execute_reply.started":"2025-08-26T21:08:33.800143Z","shell.execute_reply":"2025-08-26T21:08:33.812609Z"},"trusted":true},"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":{"execution":{"iopub.status.busy":"2025-08-26T21:08:33.814377Z","iopub.execute_input":"2025-08-26T21:08:33.814681Z","iopub.status.idle":"2025-08-26T21:08:33.827764Z","shell.execute_reply.started":"2025-08-26T21:08:33.814664Z","shell.execute_reply":"2025-08-26T21:08:33.826963Z"},"trusted":true},"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":{"execution":{"iopub.status.busy":"2025-08-26T21:08:33.828580Z","iopub.execute_input":"2025-08-26T21:08:33.828829Z","iopub.status.idle":"2025-08-26T21:08:33.842206Z","shell.execute_reply.started":"2025-08-26T21:08:33.828811Z","shell.execute_reply":"2025-08-26T21:08:33.841629Z"},"trusted":true},"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":{"execution":{"iopub.status.busy":"2025-08-26T21:08:33.842848Z","iopub.execute_input":"2025-08-26T21:08:33.843095Z","iopub.status.idle":"2025-08-26T21:08:33.857223Z","shell.execute_reply.started":"2025-08-26T21:08:33.843073Z","shell.execute_reply":"2025-08-26T21:08:33.856596Z"},"trusted":true},"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":{"execution":{"iopub.status.busy":"2025-08-26T21:08:33.858049Z","iopub.execute_input":"2025-08-26T21:08:33.858302Z","iopub.status.idle":"2025-08-26T21:08:33.878547Z","shell.execute_reply.started":"2025-08-26T21:08:33.858281Z","shell.execute_reply":"2025-08-26T21:08:33.877864Z"},"trusted":true},"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":{"execution":{"iopub.status.busy":"2025-08-26T21:08:33.881749Z","iopub.execute_input":"2025-08-26T21:08:33.882465Z","iopub.status.idle":"2025-08-26T21:08:33.893185Z","shell.execute_reply.started":"2025-08-26T21:08:33.882449Z","shell.execute_reply":"2025-08-26T21:08:33.892486Z"},"trusted":true},"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\n# class 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":{"execution":{"iopub.status.busy":"2025-08-26T21:08:33.894024Z","iopub.execute_input":"2025-08-26T21:08:33.894313Z","iopub.status.idle":"2025-08-26T21:08:33.916997Z","shell.execute_reply.started":"2025-08-26T21:08:33.894291Z","shell.execute_reply":"2025-08-26T21:08:33.916387Z"},"trusted":true},"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":{"execution":{"iopub.status.busy":"2025-08-26T21:08:33.917625Z","iopub.execute_input":"2025-08-26T21:08:33.917826Z","iopub.status.idle":"2025-08-26T21:08:33.934048Z","shell.execute_reply.started":"2025-08-26T21:08:33.917808Z","shell.execute_reply":"2025-08-26T21:08:33.933514Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Don't load x_train into memory! Instead use generators:\nBATCH_SIZE = 16\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\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\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\n)","metadata":{"execution":{"iopub.status.busy":"2025-08-26T21:14:25.742911Z","iopub.execute_input":"2025-08-26T21:14:25.743198Z","iopub.status.idle":"2025-08-26T21:14:25.748529Z","shell.execute_reply.started":"2025-08-26T21:14:25.743177Z","shell.execute_reply":"2025-08-26T21:14:25.747665Z"},"trusted":true},"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":{"execution":{"iopub.status.busy":"2025-08-26T21:08:33.949377Z","iopub.execute_input":"2025-08-26T21:08:33.949598Z","iopub.status.idle":"2025-08-26T21:08:33.965028Z","shell.execute_reply.started":"2025-08-26T21:08:33.949579Z","shell.execute_reply":"2025-08-26T21:08:33.964382Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"accuracy_score(true_labels, pred_labels)","metadata":{"execution":{"iopub.status.busy":"2025-08-26T21:08:33.965637Z","iopub.execute_input":"2025-08-26T21:08:33.966188Z","iopub.status.idle":"2025-08-26T21:08:33.980264Z","shell.execute_reply.started":"2025-08-26T21:08:33.966171Z","shell.execute_reply":"2025-08-26T21:08:33.979643Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"cohen_kappa_score(true_labels, pred_labels)","metadata":{"execution":{"iopub.status.busy":"2025-08-26T21:08:33.981019Z","iopub.execute_input":"2025-08-26T21:08:33.981320Z","iopub.status.idle":"2025-08-26T21:08:33.996789Z","shell.execute_reply.started":"2025-08-26T21:08:33.981300Z","shell.execute_reply":"2025-08-26T21:08:33.996093Z"},"trusted":true},"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":{"execution":{"iopub.status.busy":"2025-08-26T21:08:33.997625Z","iopub.execute_input":"2025-08-26T21:08:33.997889Z","iopub.status.idle":"2025-08-26T21:08:34.014061Z","shell.execute_reply.started":"2025-08-26T21:08:33.997869Z","shell.execute_reply":"2025-08-26T21:08:34.013384Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Model: DenseNet-121","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.applications import DenseNet121\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import GlobalAveragePooling2D, Dropout, Dense\nfrom tensorflow.keras.optimizers import Adam","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-26T21:08:34.014821Z","iopub.execute_input":"2025-08-26T21:08:34.015080Z","iopub.status.idle":"2025-08-26T21:08:34.032463Z","shell.execute_reply.started":"2025-08-26T21:08:34.015056Z","shell.execute_reply":"2025-08-26T21:08:34.031490Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"densenet = DenseNet121(\n    weights='/kaggle/input/densenet-keras/DenseNet-BC-121-32-no-top.h5',  # or 'imagenet'\n    include_top=False,\n    input_shape=(224,224,3)\n)","metadata":{"execution":{"iopub.status.busy":"2025-08-26T21:08:34.033690Z","iopub.execute_input":"2025-08-26T21:08:34.033964Z","iopub.status.idle":"2025-08-26T21:08:38.163986Z","shell.execute_reply.started":"2025-08-26T21:08:34.033940Z","shell.execute_reply":"2025-08-26T21:08:38.163388Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def build_model():\n    model = Sequential([\n        densenet,\n        GlobalAveragePooling2D(),\n        Dropout(0.5),\n        Dense(5, activation='sigmoid')\n    ])\n    \n    model.compile(\n        loss='binary_crossentropy',\n        optimizer=Adam(learning_rate=5e-5),\n        metrics=['binary_accuracy']\n    )\n    \n    return model","metadata":{"execution":{"iopub.status.busy":"2025-08-26T21:08:38.165077Z","iopub.execute_input":"2025-08-26T21:08:38.165328Z","iopub.status.idle":"2025-08-26T21:08:38.169538Z","shell.execute_reply.started":"2025-08-26T21:08:38.165305Z","shell.execute_reply":"2025-08-26T21:08:38.168790Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = build_model()\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2025-08-26T21:08:38.170238Z","iopub.execute_input":"2025-08-26T21:08:38.170744Z","iopub.status.idle":"2025-08-26T21:08:38.232586Z","shell.execute_reply.started":"2025-08-26T21:08:38.170721Z","shell.execute_reply":"2025-08-26T21:08:38.231839Z"},"trusted":true},"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\n# history = model.fit_generator(\n#     mixup_generator(),  # or train_generator for regular training\n#     steps_per_epoch=len(train_df) // BATCH_SIZE,\n#     epochs=3,\n#     validation_data=val_generator,  # Now this will work!\n#     validation_steps = val_steps,\n#     callbacks=[kappa_metrics]\n# )\n\nhistory = model.fit(\n    mixup_generator(),  # or train_generator\n    steps_per_epoch=len(train_df) // BATCH_SIZE,\n    epochs=10,\n    validation_data=val_generator,\n    validation_steps=val_steps,\n    callbacks=[kappa_metrics]\n)","metadata":{"execution":{"iopub.status.busy":"2025-08-26T21:15:47.458124Z","iopub.execute_input":"2025-08-26T21:15:47.458813Z","iopub.status.idle":"2025-08-26T21:18:14.103406Z","shell.execute_reply.started":"2025-08-26T21:15:47.458790Z","shell.execute_reply":"2025-08-26T21:18:14.102603Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# with open('history.json', 'w') as f:\n#     json.dump(history.history, f)\n\n# history_df = pd.DataFrame(history.history)\n# history_df[['loss', 'val_loss']].plot()\n# history_df[['acc', 'val_acc']].plot()\n# Save history\nwith open('history.json', 'w') as f:\n    json.dump(history.history, f)\n\n# Load into DataFrame\nhistory_df = pd.DataFrame(history.history)\n\n# Plot losses\nhistory_df[['loss', 'val_loss']].plot()\n\n# Plot accuracies (use correct keys)\nhistory_df[['binary_accuracy', 'val_binary_accuracy']].plot()","metadata":{"execution":{"iopub.status.busy":"2025-08-26T21:18:26.005229Z","iopub.execute_input":"2025-08-26T21:18:26.005825Z","iopub.status.idle":"2025-08-26T21:18:26.390329Z","shell.execute_reply.started":"2025-08-26T21:18:26.005800Z","shell.execute_reply":"2025-08-26T21:18:26.389602Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.plot(kappa_metrics.val_kappas)","metadata":{"execution":{"iopub.status.busy":"2025-08-26T21:18:29.287920Z","iopub.execute_input":"2025-08-26T21:18:29.288872Z","iopub.status.idle":"2025-08-26T21:18:29.432655Z","shell.execute_reply.started":"2025-08-26T21:18:29.288844Z","shell.execute_reply":"2025-08-26T21:18:29.431915Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.save_weights('model.weights.h5')\n","metadata":{"execution":{"iopub.status.busy":"2025-08-26T21:18:32.229696Z","iopub.execute_input":"2025-08-26T21:18:32.229959Z","iopub.status.idle":"2025-08-26T21:18:34.075950Z","shell.execute_reply.started":"2025-08-26T21:18:32.229941Z","shell.execute_reply":"2025-08-26T21:18:34.075137Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Then load and use\nmodel.load_weights('model.weights.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":{"execution":{"iopub.status.busy":"2025-08-26T21:18:35.373147Z","iopub.execute_input":"2025-08-26T21:18:35.373459Z","iopub.status.idle":"2025-08-26T21:18:39.620374Z","shell.execute_reply.started":"2025-08-26T21:18:35.373440Z","shell.execute_reply":"2025-08-26T21:18:39.619665Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Submit","metadata":{}},{"cell_type":"code","source":"# # Use test generator\n# test_generator = TestDataGenerator(test_df, test_dir, batch_size=32)\n# y_test_pred = test_generator.predict_all(model)\n\n# # Apply optimized threshold and convert to diagnosis\n# y_test = y_test_pred > best_threshold  # Use optimized threshold\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)\n# print(f\"Submission saved! Predictions range: {y_test.min()} to {y_test.max()}\")","metadata":{"execution":{"iopub.status.busy":"2025-08-26T21:12:42.065656Z","iopub.status.idle":"2025-08-26T21:12:42.065969Z","shell.execute_reply.started":"2025-08-26T21:12:42.065819Z","shell.execute_reply":"2025-08-26T21:12:42.065833Z"},"trusted":true},"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":{"execution":{"iopub.status.busy":"2025-08-26T21:12:42.067070Z","iopub.status.idle":"2025-08-26T21:12:42.067295Z","shell.execute_reply.started":"2025-08-26T21:12:42.067191Z","shell.execute_reply":"2025-08-26T21:12:42.067200Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# loss, acc = model.evaluate(x_val, y_val, verbose=0)\n# print(\"Validation Accuracy:\", acc)\n","metadata":{"execution":{"iopub.status.busy":"2025-08-26T21:12:42.068662Z","iopub.status.idle":"2025-08-26T21:12:42.068977Z","shell.execute_reply.started":"2025-08-26T21:12:42.068812Z","shell.execute_reply":"2025-08-26T21:12:42.068825Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def 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-26T21:18:45.255124Z","iopub.execute_input":"2025-08-26T21:18:45.255432Z","iopub.status.idle":"2025-08-26T21:19:07.755729Z","shell.execute_reply.started":"2025-08-26T21:18:45.255409Z","shell.execute_reply":"2025-08-26T21:19:07.754915Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.metrics import (\n    precision_score, recall_score, f1_score, matthews_corrcoef,\n    confusion_matrix, cohen_kappa_score, classification_report\n)\n\ndef comprehensive_validation_metrics(\n    model,\n    val_generator,\n    val_steps,\n    best_threshold=None,      # if provided, uses (preds > best_threshold).sum(axis=1)-1 like your code\n    class_names=None,\n    plot_cm=True,\n    average='weighted'        # for aggregated precision/recall/f1\n):\n    \"\"\"\n    Batch-wise evaluation that returns avg loss/acc + many metrics.\n    Keeps the same pattern as your original comprehensive_validation_eval.\n    If best_threshold is None, predicted labels are obtained via argmax (softmax case).\n    If best_threshold is provided, it uses the cumulative-threshold logic:\n        pred_single = (y_pred > best_threshold).astype(int).sum(axis=1) - 1\n    For true labels it attempts to detect cumulative encoding and falls back to argmax.\n    Returns a dict of metrics and prints + optionally plots confusion matrix.\n    \"\"\"\n    y_pred_list = []\n    y_true_list = []\n    total_loss = 0.0\n    total_acc = 0.0\n    total_samples = 0\n\n    # iterate over batches (same pattern as your function)\n    for i in range(val_steps):\n        X_batch, y_batch = val_generator[i]\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        y_pred_list.append(y_pred_batch)\n        y_true_list.append(y_batch)\n\n        total_loss += batch_loss * batch_size\n        total_acc += batch_acc * batch_size\n        total_samples += batch_size\n\n    # averages\n    avg_loss = total_loss / total_samples\n    avg_acc = total_acc / total_samples\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 to single-label indices (y_true_single, y_pred_single) ---\n    # True labels: try to detect cumulative encoding (non-decreasing rows like [1,1,0,0..])\n    if y_true.ndim > 1 and y_true.shape[1] > 1:\n        # check monotonic non-decreasing across columns -> likely cumulative encoding\n        try:\n            is_cumulative = np.all(np.diff(y_true, axis=1) >= 0)\n        except Exception:\n            is_cumulative = False\n\n        if is_cumulative:\n            y_true_single = y_true.sum(axis=1).astype(int) - 1\n        else:\n            # assume standard one-hot\n            y_true_single = np.argmax(y_true, axis=1).astype(int)\n    else:\n        y_true_single = y_true.ravel().astype(int)\n\n    # Predicted labels: two modes\n    if best_threshold is None:\n        # typical softmax -> argmax\n        if y_pred.ndim > 1 and y_pred.shape[1] > 1:\n            y_pred_single = np.argmax(y_pred, axis=1).astype(int)\n        else:\n            # single-prob binary classification\n            y_pred_single = (y_pred.ravel() > 0.5).astype(int)\n    else:\n        # use the same logic you used for kappa (cumulative thresholding)\n        y_pred_bin = (y_pred > best_threshold).astype(int)\n        y_pred_single = y_pred_bin.sum(axis=1).astype(int) - 1\n\n    # --- Metrics ---\n    # Avoid failing on degenerate cases by checking number of classes\n    labels_unique = np.unique(np.concatenate([y_true_single, y_pred_single]))\n    n_classes = int(max(labels_unique.max() + 1, 1))\n\n    precision = precision_score(y_true_single, y_pred_single, average=average, zero_division=0)\n    recall = recall_score(y_true_single, y_pred_single, average=average, zero_division=0)  # sensitivity\n    f1 = f1_score(y_true_single, y_pred_single, average=average, zero_division=0)\n    mcc = matthews_corrcoef(y_true_single, y_pred_single)\n\n    kappa = cohen_kappa_score(y_true_single, y_pred_single, weights='quadratic')\n\n    cm = confusion_matrix(y_true_single, y_pred_single, labels=np.arange(n_classes))\n\n    # Specificity per class = TN / (TN + FP)\n    tn = cm.sum() - (cm.sum(axis=1) + cm.sum(axis=0) - np.diag(cm))\n    fp = cm.sum(axis=0) - np.diag(cm)\n    denom = (tn + fp).astype(float)\n    specificity_per_class = np.where(denom == 0, 0.0, tn / denom)\n    specificity = float(np.mean(specificity_per_class))\n\n    # Per-class precision/recall/f1 (arrays)\n    per_class_precision = precision_score(y_true_single, y_pred_single, average=None, zero_division=0)\n    per_class_recall = recall_score(y_true_single, y_pred_single, average=None, zero_division=0)\n    per_class_f1 = f1_score(y_true_single, y_pred_single, average=None, zero_division=0)\n\n    # --- Print summary ---\n    print(\"=== Validation summary ===\")\n    print(f\"Avg loss: {avg_loss:.4f}, Avg acc: {avg_acc:.4f}\")\n    print(f\"Cohen's kappa (quadratic): {kappa:.4f}\")\n    print(f\"Precision ({average}): {precision:.4f}\")\n    print(f\"Recall/Sensitivity ({average}): {recall:.4f}\")\n    print(f\"Specificity (macro avg): {specificity:.4f}\")\n    print(f\"F1 ({average}): {f1:.4f}\")\n    print(f\"MCC: {mcc:.4f}\")\n    print()\n\n    # Per-class table\n    if class_names is None:\n        class_names = [str(i) for i in range(n_classes)]\n    print(\"Per-class metrics:\")\n    for idx, name in enumerate(class_names[:n_classes]):\n        print(f\"  class {name} -> precision: {per_class_precision[idx]:.4f}, recall: {per_class_recall[idx]:.4f}, f1: {per_class_f1[idx]:.4f}, specificity: {specificity_per_class[idx]:.4f}\")\n\n    # full classification report\n    print(\"\\nClassification report:\")\n    print(classification_report(y_true_single, y_pred_single, labels=np.arange(n_classes), target_names=class_names[:n_classes], zero_division=0))\n\n    # Plot confusion matrix\n    if plot_cm:\n        plt.figure(figsize=(8, 6))\n        sns.heatmap(cm, annot=True, fmt='d', cmap='Blues',\n                    xticklabels=class_names[:n_classes],\n                    yticklabels=class_names[:n_classes])\n        plt.xlabel(\"Predicted\")\n        plt.ylabel(\"True\")\n        plt.title(\"Confusion Matrix\")\n        plt.show()\n\n    # return everything convenient for downstream use\n    return {\n        'avg_loss': avg_loss,\n        'avg_acc': avg_acc,\n        'kappa': kappa,\n        'precision': precision,\n        'recall': recall,\n        'specificity': specificity,\n        'f1': f1,\n        'mcc': mcc,\n        'confusion_matrix': cm,\n        'per_class_precision': per_class_precision,\n        'per_class_recall': per_class_recall,\n        'per_class_f1': per_class_f1,\n        'specificity_per_class': specificity_per_class,\n        'y_true_single': y_true_single,\n        'y_pred_single': y_pred_single\n    }\n\n# Example usage (paste and run):\n# metrics = comprehensive_validation_metrics(model, val_generator, val_steps, best_threshold=best_threshold, class_names=None, plot_cm=True)\n# print(metrics['avg_loss'], metrics['avg_acc'])\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-26T21:21:55.093852Z","iopub.execute_input":"2025-08-26T21:21:55.094157Z","iopub.status.idle":"2025-08-26T21:21:55.109485Z","shell.execute_reply.started":"2025-08-26T21:21:55.094134Z","shell.execute_reply":"2025-08-26T21:21:55.108794Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class_names = [\"0\", \"1\", \"2\", \"3\", \"4\"]   # adjust if you have actual class labels\n\nmetrics = comprehensive_validation_metrics(\n    model,\n    val_generator,\n    val_steps,\n    best_threshold=best_threshold,   # or None if you just want argmax\n    class_names=class_names,\n    plot_cm=True\n)\n\n# Access metrics programmatically\nprint(\"Validation F1:\", metrics[\"f1\"])\nprint(\"Confusion Matrix:\\n\", metrics[\"cm\"])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-26T21:23:57.749276Z","iopub.execute_input":"2025-08-26T21:23:57.749979Z","iopub.status.idle":"2025-08-26T21:24:02.474706Z","shell.execute_reply.started":"2025-08-26T21:23:57.749956Z","shell.execute_reply":"2025-08-26T21:24:02.473781Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.metrics import (\n    precision_score, recall_score, f1_score,\n    matthews_corrcoef, cohen_kappa_score, confusion_matrix\n)\n\ndef simple_validation_metrics(\n    model,\n    val_generator,\n    val_steps,\n    best_threshold=None,\n    average='weighted'\n):\n    y_pred_list, y_true_list = [], []\n    total_loss = total_acc = total_samples = 0\n\n    for i in range(val_steps):\n        X_batch, y_batch = val_generator[i]\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        y_pred_list.append(y_pred_batch)\n        y_true_list.append(y_batch)\n\n        total_loss += batch_loss * batch_size\n        total_acc += batch_acc * batch_size\n        total_samples += batch_size\n\n    avg_loss = total_loss / total_samples\n    avg_acc = total_acc / total_samples\n\n    y_pred = np.concatenate(y_pred_list, axis=0)\n    y_true = np.concatenate(y_true_list, axis=0)\n\n    # label conversion (same logic as before)\n    if y_true.ndim > 1 and y_true.shape[1] > 1:\n        is_cumulative = np.all(np.diff(y_true, axis=1) >= 0)\n        if is_cumulative:\n            y_true_single = y_true.sum(axis=1).astype(int) - 1\n        else:\n            y_true_single = np.argmax(y_true, axis=1).astype(int)\n    else:\n        y_true_single = y_true.ravel().astype(int)\n\n    if best_threshold is None:\n        y_pred_single = np.argmax(y_pred, axis=1).astype(int)\n    else:\n        y_pred_bin = (y_pred > best_threshold).astype(int)\n        y_pred_single = y_pred_bin.sum(axis=1).astype(int) - 1\n\n    # overall metrics only\n    precision = precision_score(y_true_single, y_pred_single, average=average, zero_division=0)\n    recall = recall_score(y_true_single, y_pred_single, average=average, zero_division=0)\n    f1 = f1_score(y_true_single, y_pred_single, average=average, zero_division=0)\n    mcc = matthews_corrcoef(y_true_single, y_pred_single)\n    kappa = cohen_kappa_score(y_true_single, y_pred_single, weights='quadratic')\n\n    cm = confusion_matrix(y_true_single, y_pred_single)\n    tn = cm.sum() - (cm.sum(axis=1) + cm.sum(axis=0) - np.diag(cm))\n    fp = cm.sum(axis=0) - np.diag(cm)\n    specificity_per_class = tn / (tn + fp)\n    specificity = np.mean(specificity_per_class)\n\n    print(\"=== Validation Metrics (Overall) ===\")\n    print(f\"Loss: {avg_loss:.4f}, Accuracy: {avg_acc:.4f}\")\n    print(f\"Cohen’s Kappa: {kappa:.4f}\")\n    print(f\"Precision ({average}): {precision:.4f}\")\n    print(f\"Recall/Sensitivity ({average}): {recall:.4f}\")\n    print(f\"Specificity (avg): {specificity:.4f}\")\n    print(f\"F1 ({average}): {f1:.4f}\")\n    print(f\"MCC: {mcc:.4f}\")\n\n    return {\n        \"avg_loss\": avg_loss,\n        \"avg_acc\": avg_acc,\n        \"kappa\": kappa,\n        \"precision\": precision,\n        \"recall\": recall,\n        \"specificity\": specificity,\n        \"f1\": f1,\n        \"mcc\": mcc\n    }\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-26T21:46:13.748738Z","iopub.execute_input":"2025-08-26T21:46:13.749360Z","iopub.status.idle":"2025-08-26T21:46:13.759659Z","shell.execute_reply.started":"2025-08-26T21:46:13.749323Z","shell.execute_reply":"2025-08-26T21:46:13.758827Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"simple_metrics = simple_validation_metrics(\n    model,\n    val_generator,\n    val_steps,\n    best_threshold=best_threshold,   # or None if you just want argmax\n    # class_names=class_names,\n    # plot_cm=True\n)\n\n# Access metrics programmatically\nprint(\"Validation F1:\", metrics[\"f1\"])\n# print(\"Confusion Matrix:\\n\", metrics[\"cm\"])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-26T21:47:23.473812Z","iopub.execute_input":"2025-08-26T21:47:23.474662Z","iopub.status.idle":"2025-08-26T21:47:26.466438Z","shell.execute_reply.started":"2025-08-26T21:47:23.474639Z","shell.execute_reply":"2025-08-26T21:47:26.465735Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"tf.keras.backend.clear_session()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-26T21:12:42.071133Z","iopub.status.idle":"2025-08-26T21:12:42.071473Z","shell.execute_reply.started":"2025-08-26T21:12:42.071281Z","shell.execute_reply":"2025-08-26T21:12:42.071294Z"}},"outputs":[],"execution_count":null}]}