{"metadata":{"kernelspec":{"name":"python3","display_name":"Python 3","language":"python"},"language_info":{"name":"python","version":"3.10.14","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":14774,"databundleVersionId":875431,"sourceType":"competition"},{"sourceId":3863247,"sourceType":"datasetVersion","datasetId":2296461},{"sourceId":7352272,"sourceType":"datasetVersion","datasetId":4244554},{"sourceId":212683777,"sourceType":"kernelVersion"}],"dockerImageVersionId":30805,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"<a id=\"1\"></a>\n# <div style=\"text-align:center; border-radius:30px 30px; padding:7px; color:white; margin:0; font-size:110%; font-family:Pacifico; background-color:#5b81d4; overflow:hidden\"><b> APTOS 2019 Blindness Detection </b></div>\n<h2><center>Detect diabetic retinopathy to stop blindness before it's too late</center></h2>\n<center><img src=\"https://raw.githubusercontent.com/dimitreOliveira/MachineLearning/master/Kaggle/APTOS%202019%20Blindness%20Detection/aux_img.png\"></center>\n\nIn this notebook, we address the urgent issue of diabetic retinopathy detection, a major cause of blindness among working-aged adults. Aravind Eye Hospital in India aims to improve healthcare access in rural areas, where technicians capture retinal images, but trained doctors are needed to manually review them. While effective, this method is time-consuming and limits scalability.\n\nOur goal is to build a machine learning model that automates the detection of diabetic retinopathy, enabling faster and more accurate diagnoses. By leveraging state-of-the-art deep learning models, we aim to improve disease detection and expand this technology's potential to identify other conditions, like glaucoma and macular degeneration.\n\nModels Utilized\nWe combine the strengths of multiple cutting-edge models for effective image classification:\n\n**ResNetV2_50**: A deep convolutional network that specializes in feature extraction, allowing it to detect subtle features in retinal images with high precision.\n\n**DeiT_base_patch16** (Vision Transformer): A transformer-based architecture that excels at capturing global dependencies within images, making it ideal for complex medical images.\n\n**FastViT_s12**: A faster version of Vision Transformers, optimized for speed without sacrificing accuracy, ensuring quick inference times in real-time diagnostic settings.\n\n**swinv2_small_window16_256**: A Shifted Window Transformer capable of handling images at multiple scales, providing fine-grained detail for more accurate detection of retinopathy.\n","metadata":{}},{"cell_type":"markdown","source":"- <a href=\"#libraries\">1. Importing Required Libraries</a>\n- <a href=\"#EDA\">2. EDA</a>\n- <a href=\"#Data Preprocssing\">3. Data Preprecssing</a>\n- <a href=\"#Transformation\">4. Data Splitting and Transformation </a>\n- <a href=\"#Tuning\">5. Fine Tuning The Models </a>\n    - <a href=\"#function\">5.1. Train and validation function   </a> \n    - <a href=\"#Models\">5.2. Fine tuning  swinv2_small_window16_256 </a> \n- <a href=\"#Evalution\">6. Evalution</a>","metadata":{}},{"cell_type":"markdown","source":"<a id=\"libraries\"></a>\n# <div style=\"text-align:center; border-radius:30px 30px; padding:7px; color:white; margin:0; font-size:110%; font-family:Pacifico; background-color:#5b81d4; overflow:hidden\"><b> Importing Required Libraries </b></div>","metadata":{}},{"cell_type":"code","source":"import torch\nfrom torch.utils.data import Dataset, DataLoader\nfrom PIL import Image\nimport pandas as pd\nimport os\nimport timm\nimport random\nimport time\nfrom collections import OrderedDict\nfrom torch.cuda import amp\nimport numpy as np\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torchvision import transforms as T\nimport matplotlib.pyplot as plt\nfrom torchvision.io import read_image\nimport cv2\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import classification_report, f1_score\nimport seaborn as sns\nfrom tqdm import tqdm\nprint(torch.__version__)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-04T12:16:44.130731Z","iopub.execute_input":"2025-12-04T12:16:44.131114Z","iopub.status.idle":"2025-12-04T12:16:44.145910Z","shell.execute_reply.started":"2025-12-04T12:16:44.131067Z","shell.execute_reply":"2025-12-04T12:16:44.144821Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"<a id=\"EDA\"></a>\n# <div style=\"text-align:center; border-radius:30px 30px; padding:7px; color:white; margin:0; font-size:110%; font-family:Pacifico; background-color:#5b81d4; overflow:hidden\"><b> EDA </b></div>","metadata":{}},{"cell_type":"code","source":"import os\nimport pandas as pd\n\nprint(\"\\n### Adding extra datasets... ###\")\n\n# --------------------------\n# 0️⃣ Load Base APTOS Dataset\n# --------------------------\nprint(\"✔ Loading APTOS 2019 dataset...\")\n\naptos = pd.read_csv(\"../input/aptos2019-blindness-detection/train.csv\")\naptos[\"image\"] = aptos[\"id_code\"] + \".png\"\naptos[\"path\"] = \"../input/aptos2019-blindness-detection/train_images/\"\naptos.rename(columns={\"diagnosis\": \"label\"}, inplace=True)\n\nprint(f\"Loaded: {len(aptos)} APTOS images\")\n\n\n# Correct base path for EYEPACS+DR_UNIFIED\nbase_path = \"../input/eyepacs-aptos-messidor-diabetic-retinopathy/\"\n\n\n# --------------------------\n# 1️⃣ AUGMENTED_RESIZED_V2\n# --------------------------\naug_path = base_path + \"augmented_resized_V2/train/\"\naugmented_list = []\n\nif os.path.exists(aug_path):\n    print(\"✔ Found augmented_resized_V2 — loading...\")\n    for label_folder in sorted(os.listdir(aug_path)):\n        folder_path = os.path.join(aug_path, label_folder)\n        if os.path.isdir(folder_path):\n            for img in os.listdir(folder_path):\n                augmented_list.append([img, int(label_folder), folder_path + \"/\"])\n    augmented_df = pd.DataFrame(augmented_list, columns=[\"image\", \"label\", \"path\"])\n    print(f\"Loaded: {len(augmented_df)} images from augmented dataset\")\nelse:\n    augmented_df = pd.DataFrame()\n    print(\"⚠ augmented_resized_V2 NOT FOUND\")\n\n\n# --------------------------\n# 2️⃣ DR_UNIFIED_V2\n# --------------------------\ndr_unified_path = base_path + \"dr_unified_v2/dr_unified_v2/train/\"\ndr_unified_list = []\n\nif os.path.exists(dr_unified_path):\n    print(\"✔ Found dr_unified_v2 — loading...\")\n    for label_folder in sorted(os.listdir(dr_unified_path)):\n        folder_path = os.path.join(dr_unified_path, label_folder)\n        if os.path.isdir(folder_path):\n            for img in os.listdir(folder_path):\n                dr_unified_list.append([img, int(label_folder), folder_path + \"/\"])\n    dr_unified_df = pd.DataFrame(dr_unified_list, columns=[\"image\", \"label\", \"path\"])\n    print(f\"Loaded: {len(dr_unified_df)} images from dr_unified dataset\")\nelse:\n    dr_unified_df = pd.DataFrame()\n    print(\"⚠ dr_unified_v2 NOT FOUND\")\n\n\n# --------------------------\n# 3️⃣ Glaucoma datasets\n# --------------------------\nprint(\"\\n✔ Loading Glaucoma datasets...\")\n\ng1020 = pd.read_csv(\"../input/glaucoma-datasets/G1020/G1020.csv\")\ng1020[\"image\"] = g1020[\"imageID\"]\ng1020[\"label\"] = g1020[\"binaryLabels\"]\ng1020[\"path\"] = \"../input/glaucoma-datasets/G1020/Images/\"\ng1020 = g1020[[\"image\", \"label\", \"path\"]]\n\noriga = pd.read_csv(\"../input/glaucoma-datasets/ORIGA/origa_info.csv\")\noriga[\"image\"] = origa[\"Image\"]\noriga[\"label\"] = origa[\"Label\"]\noriga[\"path\"] = \"../input/glaucoma-datasets/ORIGA/Images/\"\noriga = origa[[\"image\", \"label\", \"path\"]]\n\nprint(f\"G1020: {len(g1020)}   ORIGA: {len(origa)}\")\n\n\n# --------------------------\n# 📌 MERGE FINAL\n# --------------------------\ndr_full = pd.concat([aptos, augmented_df, dr_unified_df], ignore_index=True).sample(frac=1, random_state=42)\nglaucoma_full = pd.concat([g1020, origa], ignore_index=True).sample(frac=1, random_state=42)\n\nprint(\"\\n🔥 FINAL DATASET COUNTS:\")\nprint(f\"➡ DR Images Total: {len(dr_full)}\")\nprint(f\"➡ Glaucoma Images Total: {len(glaucoma_full)}\")\n\nprint(\"\\n📍 DR Dataset Example:\")\ndisplay(dr_full.head())\n\nprint(\"\\n📍 Glaucoma Dataset Example:\")\ndisplay(glaucoma_full.head())\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-04T12:16:47.537395Z","iopub.execute_input":"2025-12-04T12:16:47.538017Z","iopub.status.idle":"2025-12-04T12:16:59.039040Z","shell.execute_reply.started":"2025-12-04T12:16:47.537983Z","shell.execute_reply":"2025-12-04T12:16:59.038214Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ============================================================\n# 📌 Create Train/Validation Split for Both Models\n# ============================================================\n\nfrom sklearn.model_selection import train_test_split\n\n# DR classification dataset split\ntrain_dr, val_dr = train_test_split(\n    dr_full,\n    test_size=0.2,\n    stratify=dr_full[\"label\"],\n    random_state=42\n)\n\n# Glaucoma dataset split\ntrain_gl, val_gl = train_test_split(\n    glaucoma_full,\n    test_size=0.2,\n    stratify=glaucoma_full[\"label\"],\n    random_state=42\n)\n\nprint(\"\\n### Dataset Split Summary ###\")\nprint(f\"DR Train: {len(train_dr)} | DR Validation: {len(val_dr)}\")\nprint(f\"Glaucoma Train: {len(train_gl)} | Glaucoma Validation: {len(val_gl)}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-04T12:17:02.477374Z","iopub.execute_input":"2025-12-04T12:17:02.477720Z","iopub.status.idle":"2025-12-04T12:17:02.573996Z","shell.execute_reply.started":"2025-12-04T12:17:02.477688Z","shell.execute_reply":"2025-12-04T12:17:02.573140Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms\nfrom PIL import Image\nimport torch\n\n# ============================================================\n# 📌 PyTorch Dataset Class\n# ============================================================\n\nclass EyeDataset(Dataset):\n    def __init__(self, df, transform=None):\n        self.df = df\n        self.transform = transform\n\n    def __len__(self):\n        return len(self.df)\n\n    def __getitem__(self, idx):\n        row = self.df.iloc[idx]\n        image = Image.open(row[\"path\"] + row[\"image\"]).convert(\"RGB\")\n\n        if self.transform:\n            image = self.transform(image)\n\n        return image, torch.tensor(row[\"label\"], dtype=torch.long)\n\n\n# ============================================================\n# 📌 Image Transformations\n# ============================================================\n\ntrain_transform = transforms.Compose([\n    transforms.Resize((224, 224)),\n    transforms.RandomHorizontalFlip(),\n    transforms.RandomRotation(10),\n    transforms.ToTensor(),\n])\n\ntest_transform = transforms.Compose([\n    transforms.Resize((224, 224)),\n    transforms.ToTensor(),\n])\n\n\n# ============================================================\n# 📌 Create DataLoaders\n# ============================================================\n\ntrain_loader_dr = DataLoader(EyeDataset(train_dr, train_transform), batch_size=16, shuffle=True)\nval_loader_dr   = DataLoader(EyeDataset(val_dr, test_transform), batch_size=16)\n\ntrain_loader_gl = DataLoader(EyeDataset(train_gl, train_transform), batch_size=16, shuffle=True)\nval_loader_gl   = DataLoader(EyeDataset(val_gl, test_transform), batch_size=16)\n\nprint(\"\\n✔ DataLoaders Ready!\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-04T12:17:07.284956Z","iopub.execute_input":"2025-12-04T12:17:07.285526Z","iopub.status.idle":"2025-12-04T12:17:07.305893Z","shell.execute_reply.started":"2025-12-04T12:17:07.285493Z","shell.execute_reply":"2025-12-04T12:17:07.305001Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(\"📌 Dataset Summary\")\nprint(\"-----------------------------------\")\nprint(f\"APTOS Original Images: {len(aptos)}\")\nprint(f\"Eyepacs + DR_Unified Added: {len(dr_full) - len(aptos)}\")\nprint(f\"🔥 Final DR Dataset Total: {len(dr_full)}\")\n\nprint(f\"\\nGlaucoma Images (G1020 + ORIGA): {len(glaucoma_full)}\")\n\nprint(\"\\n🔹 Training Split:\")\nprint(f\"DR -> Train: {len(train_dr)} | Validation: {len(val_dr)}\")\nprint(f\"Glaucoma -> Train: {len(train_gl)} | Validation: {len(val_gl)}\")\n\nprint(\"\\n📍 DR Dataset Example:\")\ndisplay(dr_full.head())\n\nprint(\"\\n📍 Glaucoma Dataset Example:\")\ndisplay(glaucoma_full.head())\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-04T12:17:11.270630Z","iopub.execute_input":"2025-12-04T12:17:11.271522Z","iopub.status.idle":"2025-12-04T12:17:11.292926Z","shell.execute_reply.started":"2025-12-04T12:17:11.271472Z","shell.execute_reply":"2025-12-04T12:17:11.291826Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import seaborn as sns\nimport matplotlib.pyplot as plt\n\nf, ax = plt.subplots(figsize=(14, 8.7))\nax = sns.countplot(x=\"label\", data=dr_full, palette=\"GnBu_d\")\nsns.despine()\nplt.title(\"Distribution of DR Labels\")\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-04T12:17:15.253875Z","iopub.execute_input":"2025-12-04T12:17:15.254511Z","iopub.status.idle":"2025-12-04T12:17:15.533164Z","shell.execute_reply.started":"2025-12-04T12:17:15.254478Z","shell.execute_reply":"2025-12-04T12:17:15.532367Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import cv2\nimport matplotlib.pyplot as plt\n\n# Setting the style for the plot\nsns.set_style(\"white\")\n\n# Mapping class labels to text categories\nlevel_to_category = {\n    0: \"No_DR\",\n    1: \"Mild\",\n    2: \"Moderate\",\n    3: \"Severe\",\n    4: \"Proliferate_DR\"\n}\n\n# Plot first 15 images from merged dataset\nplt.figure(figsize=(20, 20))\n\nfor i, row in enumerate(dr_full.iloc[:15].itertuples(), 1):\n    img_path = row.path + row.image\n    img = cv2.imread(img_path)\n    \n    if img is None:\n        continue  # skip missing files\n    \n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n    plt.subplot(5, 5, i)\n    plt.imshow(img)\n    plt.axis(\"off\")\n    plt.title(f\"{level_to_category[row.label]}\")\n    \nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-04T12:18:34.483457Z","iopub.execute_input":"2025-12-04T12:18:34.484179Z","iopub.status.idle":"2025-12-04T12:18:39.423593Z","shell.execute_reply.started":"2025-12-04T12:18:34.484147Z","shell.execute_reply":"2025-12-04T12:18:39.422360Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"<a id=\"Transformation\"></a>\n# <div style=\"text-align:center; border-radius:30px 30px; padding:7px; color:white; margin:0; font-size:110%; font-family:Pacifico; background-color:#5b81d4; overflow:hidden\"><b> Data Splitting and Transformation </b></div>","metadata":{}},{"cell_type":"code","source":"# ==============================\n# GLOBAL CONFIGURATION\n# ==============================\n\n# ---- Dataset Paths ----\nAPTOS_DIR = \"../input/aptos2019-blindness-detection/train_images/\"\nEYEPACS_DIR = \"../input/eyepacs-aptos-messidor-diabetic-retinopathy/augmented_resized_V2/train/\"\nDR_UNIFIED_DIR = \"../input/eyepacs-aptos-messidor-diabetic-retinopathy/dr_unified_v2/dr_unified_v2/train/\"\nGLAUCOMA_G1020_DIR = \"../input/glaucoma-datasets/G1020/Images/\"\nGLAUCOMA_ORIGA_DIR = \"../input/glaucoma-datasets/ORIGA/Images/\"\n\n# ---- Model + Saving ----\nMODEL_SAVE_DIR = \"./models/\"\nos.makedirs(MODEL_SAVE_DIR, exist_ok=True)\n\n# ---- Training Params ----\nIMG_WIDTH = 256\nIMG_HEIGHT = 256\nLEARNING_RATE = 1e-4\nTRAIN_BATCH_SIZE = 32\nVALID_BATCH_SIZE = 32\nNUM_WORKERS = 2\nUSE_AMP = True  # Automatic Mixed Precision for faster GPU\nEPOCHS = 10\n\n# ---- DR & Glaucoma Train Ratio ----\nTRAIN_SPLIT = 0.8  # 80/20\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-04T12:19:07.849691Z","iopub.execute_input":"2025-12-04T12:19:07.850427Z","iopub.status.idle":"2025-12-04T12:19:07.855309Z","shell.execute_reply.started":"2025-12-04T12:19:07.850391Z","shell.execute_reply":"2025-12-04T12:19:07.854482Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class RetinopathyDataset(Dataset):\n    def __init__(self, image_dir, csv_file, transforms=None):\n        self.data = pd.read_csv(csv_file)\n        self.transforms = transforms\n        self.image_dir = image_dir\n\n    def __len__(self):\n        return len(self.data)\n\n    def __getitem__(self, idx):\n        # img_name = os.path.join('../input/aptos2019-blindness-detection/train_images',\n        #                         self.data.loc[idx, 'id_code'] + '.png')\n\n        img_name = os.path.join(self.image_dir, self.data.loc[idx, 'id_code'] + '.png')\n\n        tensor_image = read_image(img_name)\n        label = torch.tensor(self.data.loc[idx, 'diagnosis'], dtype=torch.long)\n\n        if self.transforms is not None:\n            tensor_image = self.transforms(tensor_image)\n\n        return (tensor_image, label)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-04T12:19:13.825179Z","iopub.execute_input":"2025-12-04T12:19:13.826044Z","iopub.status.idle":"2025-12-04T12:19:13.831834Z","shell.execute_reply.started":"2025-12-04T12:19:13.826006Z","shell.execute_reply":"2025-12-04T12:19:13.830917Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from torch.utils.data import Dataset, DataLoader\nfrom PIL import Image\nimport torch\nimport torchvision.transforms as T\n\n# =========================\n# NEW DATASET CLASS\n# =========================\nclass RetinopathyDataset(Dataset):\n    def __init__(self, df, transforms=None):\n        self.df = df\n        self.transforms = transforms\n\n    def __len__(self):\n        return len(self.df)\n\n    def __getitem__(self, idx):\n        row = self.df.iloc[idx]\n        image_path = row[\"path\"] + row[\"image\"]\n        label = row[\"label\"]\n\n        image = Image.open(image_path).convert(\"RGB\")\n\n        if self.transforms:\n            image = self.transforms(image)\n\n        return image, torch.tensor(label, dtype=torch.long)\n\n\n# =========================\n# TRANSFORMS\n# =========================\ntrain_transforms = T.Compose([\n    T.Resize((IMG_WIDTH, IMG_HEIGHT)),\n    T.RandomHorizontalFlip(),\n    T.ToTensor(),\n    T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n])\n\nval_transforms = T.Compose([\n    T.Resize((IMG_WIDTH, IMG_HEIGHT)),\n    T.ToTensor(),\n    T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n])\n\n\n# =========================\n# TRAIN / VAL SPLIT USING dr_full\n# =========================\nfrom sklearn.model_selection import train_test_split\n\ntrain_dr, val_dr = train_test_split(\n    dr_full, test_size=0.2, stratify=dr_full[\"label\"], random_state=42\n)\n\n# Create datasets\ntrain_dataset = RetinopathyDataset(train_dr, transforms=train_transforms)\nval_dataset = RetinopathyDataset(val_dr, transforms=val_transforms)\n\n# Create dataloaders\ntrain_loader = DataLoader(train_dataset, batch_size=TRAIN_BATCH_SIZE,\n                          shuffle=True, num_workers=NUM_WORKERS)\n\nval_loader = DataLoader(val_dataset, batch_size=VALID_BATCH_SIZE,\n                        shuffle=False, num_workers=NUM_WORKERS)\n\nprint(\"✔ DataLoader Ready\")\nprint(f\"Training Samples: {len(train_dataset)}\")\nprint(f\"Validation Samples: {len(val_dataset)}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-04T12:19:17.524140Z","iopub.execute_input":"2025-12-04T12:19:17.525008Z","iopub.status.idle":"2025-12-04T12:19:17.645883Z","shell.execute_reply.started":"2025-12-04T12:19:17.524971Z","shell.execute_reply":"2025-12-04T12:19:17.645008Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### Helper Functions and Utilities for Training and Evaluation","metadata":{}},{"cell_type":"code","source":"@torch.no_grad()\ndef accuracy(output, target, topk=(1,)):\n    \"\"\"\n    Computes the accuracy over the k top predictions for the specified values of k.\n\n    Args:\n        output (torch.Tensor): Model predictions with shape (batch_size, num_classes).\n        target (torch.Tensor): True labels with shape (batch_size,).\n        topk (tuple): Tuple of integers indicating top-k values to calculate.\n\n    Returns:\n        list: Accuracy values for each top-k specified.\n    \"\"\"\n    maxk = max(topk)  # Determine the maximum k\n    batch_size = target.size(0)  # Get the batch size\n    _, pred = output.topk(maxk, 1, True, True)  # Get top-k predictions\n    pred = pred.t()  # Transpose for comparison\n    correct = pred.eq(target.reshape(1, -1).expand_as(pred))  # Check correctness\n    return [correct[:k].reshape(-1).float().sum(0) * 100. / batch_size for k in topk]\n\n\ndef set_debug_apis(state: bool = False):\n    \"\"\"\n    Configures PyTorch debugging tools.\n\n    Args:\n        state (bool): If True, enables debugging tools for profiling and anomaly detection.\n    \"\"\"\n    torch.autograd.profiler.profile(enabled=state)\n    torch.autograd.profiler.emit_nvtx(enabled=state)\n    torch.autograd.set_detect_anomaly(mode=state)\n\n\ndef seed_everything(seed):\n    \"\"\"\n    Sets seeds for reproducibility in training.\n\n    Args:\n        seed (int): Seed value to ensure determinism.\n    \"\"\"\n    random.seed(seed)\n    os.environ[\"PYTHONHASHSEED\"] = str(seed)  # Seed for hash-based operations\n    np.random.seed(seed)  # Seed for NumPy\n    torch.manual_seed(seed)  # Seed for PyTorch (CPU)\n    torch.cuda.manual_seed(seed)  # Seed for PyTorch (GPU)\n    torch.backends.cudnn.deterministic = True  # Make CuDNN deterministic\n    torch.backends.cudnn.benchmark = True  # Enable benchmark mode for CuDNN\n\n\ndef print_size_of_model(model):\n    \"\"\"\n    Calculates and prints the size of a PyTorch model.\n\n    Args:\n        model (torch.nn.Module): The model whose size is to be calculated.\n    \"\"\"\n    torch.save(model.state_dict(), \"temp.p\")  # Save model state\n    print(\"Size (MB):\", os.path.getsize(\"temp.p\") / 1e6)  # Convert bytes to MB\n    os.remove(\"temp.p\")  # Clean up temporary file\n\n\nclass AverageMeter(object):\n    \"\"\"\n    Computes and stores the average and current value of a metric.\n    Useful for tracking performance metrics during training or evaluation.\n    \"\"\"\n\n    def __init__(self):\n        self.reset()  # Initialize/reset all attributes\n\n    def reset(self):\n        \"\"\"Resets all statistics to their initial state.\"\"\"\n        self.val = 0\n        self.avg = 0\n        self.sum = 0\n        self.count = 0\n\n    def update(self, val, n=1):\n        \"\"\"\n        Updates statistics with a new value.\n\n        Args:\n            val (float): New value to update.\n            n (int): Weight of the value (e.g., batch size).\n        \"\"\"\n        self.val = val  # Current value\n        self.sum += val * n  # Accumulated value\n        self.count += n  # Count of items\n        self.avg = self.sum / self.count  # Average\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-04T12:19:21.966021Z","iopub.execute_input":"2025-12-04T12:19:21.966389Z","iopub.status.idle":"2025-12-04T12:19:21.976809Z","shell.execute_reply.started":"2025-12-04T12:19:21.966359Z","shell.execute_reply":"2025-12-04T12:19:21.975791Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(torch.cuda.is_available())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-04T12:19:26.490917Z","iopub.execute_input":"2025-12-04T12:19:26.491227Z","iopub.status.idle":"2025-12-04T12:19:26.495844Z","shell.execute_reply.started":"2025-12-04T12:19:26.491199Z","shell.execute_reply":"2025-12-04T12:19:26.494958Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"<a id=\"Tuning\"></a>\n# <div style=\"text-align:center; border-radius:30px 30px; padding:7px; color:white; margin:0; font-size:110%; font-family:Pacifico; background-color:#5b81d4; overflow:hidden\"><b> Fine Tuning The Models </b></div>","metadata":{}},{"cell_type":"markdown","source":"<a id=\"function\"></a>\n### <div style=\"text-align:center; border-radius:15px; padding:5px; color:white; margin:0; font-size:100%; font-family:Arial; background-color:#f39c12;\"><b>Training function and validations</b></div>\n","metadata":{}},{"cell_type":"code","source":"def train_step(model: nn.Module, train_loader, criterion,\n               device: str, optimizer,\n               scheduler=None, num_batches: int = None,\n               log_interval: int = 100,\n               scaler=None,):\n    \"\"\"\n    Performs one step of training. Calculates loss, forward pass, computes gradient and returns metrics.\n    Args:\n        model : A pytorch CNN Model.\n        train_loader : Train loader.\n        criterion : Loss function to be optimized.\n        device : \"cuda\" or \"cpu\"\n        optimizer : Torch optimizer to train.\n        scheduler : Learning rate scheduler.\n        num_batches : (optional) Integer To limit training to certain number of batches.\n        log_interval : (optional) Defualt 100. Integer to Log after specified batch ids in every batch.\n        scaler: (optional)  Pass torch.cuda.amp.GradScaler() for fp16 precision Training.\n    \"\"\"\n\n    model = model.to(device)\n    start_train_step = time.time()\n    metrics = OrderedDict()\n    model.train()\n    last_idx = len(train_loader) - 1\n    batch_time_m = AverageMeter()\n    # data_time_m = AverageMeter()\n    losses_m = AverageMeter()\n    top1_m = AverageMeter()\n    top5_m = AverageMeter()\n    cnt = 0\n    batch_start = time.time()\n    # num_updates = epoch * len(loader)\n\n    for batch_idx, (inputs, target) in enumerate(train_loader):\n        last_batch = batch_idx == last_idx\n        # data_time_m.update(time.time() - batch_start)\n        inputs = inputs.to(device)\n        target = target.to(device)\n\n        # zero the parameter gradients\n        optimizer.zero_grad()\n\n        if scaler is not None:\n            with amp.autocast():\n                output = model(inputs)\n                loss = criterion(output, target)\n                # Scale the loss using Grad Scaler\n            scaler.scale(loss).backward()\n            # Step using scaler.step()\n            scaler.step(optimizer)\n            # Update for next iteration\n            scaler.update()\n\n        else:\n            output = model(inputs)\n            loss = criterion(output, target)\n            loss.backward()\n            optimizer.step()\n\n        if scheduler is not None:\n            scheduler.step()\n\n        cnt += 1\n        acc1, acc5 = accuracy(output, target, topk=(1, 5))\n\n        top1_m.update(acc1.item(), output.size(0))\n        top5_m.update(acc5.item(), output.size(0))\n        losses_m.update(loss.item(), inputs.size(0))\n\n        batch_time_m.update(time.time() - batch_start)\n        batch_start = time.time()\n        if last_batch or batch_idx % log_interval == 0:  # If we reach the log intervel\n            print(\n                \"Batch Train Time: {batch_time.val:.3f} ({batch_time.avg:.3f})  \"\n                \"Loss: {loss.val:>7.4f} ({loss.avg:>6.4f})  \"\n                \"Top 1 Accuracy: {top1.val:>7.4f} ({top1.avg:>7.4f})  \"\n                \"Top 5 Accuracy: {top5.val:>7.4f} ({top5.avg:>7.4f})\".format(\n                    batch_time=batch_time_m, loss=losses_m, top1=top1_m, top5=top5_m))\n\n        if num_batches is not None:\n            if cnt >= num_batches:\n                end_train_step = time.time()\n                metrics[\"loss\"] = losses_m.avg\n                metrics[\"top1\"] = top1_m.avg\n                metrics[\"top5\"] = top5_m.avg\n                print(f\"Done till {num_batches} train batches\")\n                print(f\"Time taken for train step = {end_train_step - start_train_step} sec\")\n                return metrics\n\n    metrics[\"loss\"] = losses_m.avg\n    metrics[\"top1\"] = top1_m.avg\n    metrics[\"top5\"] = top5_m.avg\n    end_train_step = time.time()\n    print(f\"Time taken for train step = {end_train_step - start_train_step} sec\")\n    return metrics","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-04T12:19:29.435106Z","iopub.execute_input":"2025-12-04T12:19:29.435446Z","iopub.status.idle":"2025-12-04T12:19:29.446964Z","shell.execute_reply.started":"2025-12-04T12:19:29.435417Z","shell.execute_reply":"2025-12-04T12:19:29.445953Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"@torch.no_grad()\ndef val_step(model: nn.Module, val_loader, criterion,\n             device: str, num_batches=None,\n             log_interval: int = 100):\n\n    \"\"\"\n    Performs one step of validation. Calculates loss, forward pass and returns metrics.\n    Args:\n        model : A pytorch CNN Model.\n        val_loader : Validation loader.\n        criterion : Loss function to be optimized.\n        device : \"cuda\" or \"cpu\"\n        num_batches : (optional) Integer To limit validation to certain number of batches.\n        log_interval : (optional) Defualt 100. Integer to Log after specified batch ids in every batch.\n    \"\"\"\n\n    model = model.to(device)\n    start_val_step = time.time()\n    last_idx = len(val_loader) - 1\n    batch_time_m = AverageMeter()\n    # data_time_m = AverageMeter()\n    losses_m = AverageMeter()\n    top1_m = AverageMeter()\n    top5_m = AverageMeter()\n    cnt = 0\n    model.eval()\n    batch_start = time.time()\n    metrics = OrderedDict()\n\n    for batch_idx, (inputs, target) in enumerate(val_loader):\n        last_batch = batch_idx == last_idx\n        inputs = inputs.to(device)\n        target = target.to(device)\n\n        output = model(inputs)\n        loss = criterion(output, target)\n        cnt += 1\n        acc1, acc5 = accuracy(output, target, topk=(1, 5))\n        reduced_loss = loss.data\n\n        losses_m.update(reduced_loss.item(), inputs.size(0))\n        top1_m.update(acc1.item(), output.size(0))\n        top5_m.update(acc5.item(), output.size(0))\n        batch_time_m.update(time.time() - batch_start)\n\n        batch_start = time.time()\n\n        if (last_batch or batch_idx % log_interval == 0):  # If we reach the log intervel\n            print(\n                \"Batch Inference Time: {batch_time.val:.3f} ({batch_time.avg:.3f})  \"\n                \"Loss: {loss.val:>7.4f} ({loss.avg:>6.4f})  \"\n                \"Top 1 Accuracy: {top1.val:>7.4f} ({top1.avg:>7.4f})  \"\n                \"Top 5 Accuracy: {top5.val:>7.4f} ({top5.avg:>7.4f})\".format(\n                    batch_time=batch_time_m, loss=losses_m, top1=top1_m, top5=top5_m))\n\n        if num_batches is not None:\n            if cnt >= num_batches:\n                end_val_step = time.time()\n                metrics[\"loss\"] = losses_m.avg\n                metrics[\"top1\"] = top1_m.avg\n                metrics[\"top5\"] = top5_m.avg\n                print(f\"Done till {num_batches} validation batches\")\n                print(f\"Time taken for validation step = {end_val_step - start_val_step} sec\")\n                return metrics\n\n    metrics[\"loss\"] = losses_m.avg\n    metrics[\"top1\"] = top1_m.avg\n    metrics[\"top5\"] = top5_m.avg\n    print(\"Finished the validation epoch\")\n\n    end_val_step = time.time()\n    print(f\"Time taken for validation step = {end_val_step - start_val_step} sec\")\n    return metrics","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-04T12:19:37.265118Z","iopub.execute_input":"2025-12-04T12:19:37.266083Z","iopub.status.idle":"2025-12-04T12:19:37.275557Z","shell.execute_reply.started":"2025-12-04T12:19:37.266037Z","shell.execute_reply":"2025-12-04T12:19:37.274669Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"<a id=\"Models\"></a>\n### <div style=\"text-align:center; border-radius:15px; padding:5px; color:white; margin:0; font-size:100%; font-family:Arial; background-color:#f39c12;\"><b> Fine Tuning  SWIN </b></div>\n","metadata":{}},{"cell_type":"code","source":"MODEL_NAME = \"swinv2_small_window16_256\"\nMODEL_SAVE = \"/kaggle/working/swinv2_dr_model.pth\"   # <-- FIXED\nseed_everything(42)\nset_debug_apis(False)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-04T12:19:41.713119Z","iopub.execute_input":"2025-12-04T12:19:41.713854Z","iopub.status.idle":"2025-12-04T12:19:41.719703Z","shell.execute_reply.started":"2025-12-04T12:19:41.713817Z","shell.execute_reply":"2025-12-04T12:19:41.718830Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model= timm.create_model(MODEL_NAME, pretrained=True, num_classes=5)\n\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.AdamW(model.parameters(), lr=1e-4)\n\nif torch.cuda.is_available():\n    device = \"cuda\"\nelse:\n    device = \"cpu\"\n\nif USE_AMP:\n    from torch.cuda import amp\n    scaler = amp.GradScaler()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-04T12:19:44.921920Z","iopub.execute_input":"2025-12-04T12:19:44.922735Z","iopub.status.idle":"2025-12-04T12:19:45.913130Z","shell.execute_reply.started":"2025-12-04T12:19:44.922700Z","shell.execute_reply":"2025-12-04T12:19:45.912252Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ============================================================\n# 📌 IMPORTS\n# ============================================================\nimport os, time, cv2, random\nimport numpy as np\nimport pandas as pd\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms as T\nfrom timm import create_model\nfrom sklearn.model_selection import train_test_split\nfrom tqdm.auto import tqdm\nimport matplotlib.pyplot as plt\n\n# ============================================================\n# 📌 SETTINGS\n# ============================================================\n\nDATA_DIR = \"../input/aptos2019-blindness-detection/\"\nIMG_DIR = DATA_DIR + \"train_images/\"\nCSV_PATH = DATA_DIR + \"train.csv\"\n\nDEVICE = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n\nIMG_SIZE = 256\nBATCH_SIZE = 8\nEPOCHS = 5\nUSE_AMP = True  \n\n\n# ============================================================\n# 📌 LOAD DATA\n# ============================================================\ntrain_df = pd.read_csv(CSV_PATH)\ntrain_df[\"id_code\"] = train_df[\"id_code\"] + \".png\"\nprint(\"✔ Dataset Loaded:\", train_df.shape)\n\n\n# ============================================================\n# 📌 DATASET CLASS\n# ============================================================\nclass RetinopathyDataset(Dataset):\n    def __init__(self, df, img_dir, transform=None):\n        self.df = df\n        self.img_dir = img_dir\n        self.transform = transform\n\n    def __len__(self):\n        return len(self.df)\n\n    def __getitem__(self, idx):\n        row = self.df.iloc[idx]\n        img_path = os.path.join(self.img_dir, row[\"id_code\"])\n        img = cv2.imread(img_path)[..., ::-1]\n        img = cv2.resize(img, (IMG_SIZE, IMG_SIZE))\n\n        if self.transform:\n            img = self.transform(img)\n\n        return img, torch.tensor(row[\"diagnosis\"]).long()\n\n\n# ============================================================\n# 📌 TRANSFORMS\n# ============================================================\ntransform = T.Compose([\n    T.ToTensor(),\n    T.Resize((IMG_SIZE, IMG_SIZE)),\n    T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n])\n\n\n# ============================================================\n# 📌 TRAIN/VAL SPLIT\n# ============================================================\ntrain_df, val_df = train_test_split(train_df, test_size=0.2, stratify=train_df[\"diagnosis\"], random_state=42)\n\ntrain_set = RetinopathyDataset(train_df, IMG_DIR, transform)\nval_set = RetinopathyDataset(val_df, IMG_DIR, transform)\n\ntrain_loader = DataLoader(train_set, batch_size=BATCH_SIZE, shuffle=True, num_workers=2)\nval_loader = DataLoader(val_set, batch_size=BATCH_SIZE, shuffle=False, num_workers=2)\n\nprint(f\"Train: {len(train_set)} | Validation: {len(val_set)}\")\n\n\n# ============================================================\n# 📌 MODEL (Offline EfficientNet B3)\n# ============================================================\nMODEL_NAME = \"tf_efficientnet_b3_ns\"\n\ntry:\n    model = create_model(MODEL_NAME, pretrained=True, num_classes=5).to(DEVICE)\n    print(\"✔ Model loaded with pretrained weights.\")\nexcept:\n    model = create_model(MODEL_NAME, pretrained=False, num_classes=5).to(DEVICE)\n    print(\"⚠ Pretrained weights unavailable — using random init.\")\n\ncriterion = nn.CrossEntropyLoss()\noptimizer = torch.optim.Adam(model.parameters(), lr=1e-4)\nscaler = torch.cuda.amp.GradScaler(enabled=USE_AMP)\n\ntorch.cuda.empty_cache()\n\n\n# ============================================================\n# 📌 TRAINING LOOP\n# ============================================================\n\nbest_loss = float(\"inf\")\n\nprint(\"\\n🚀 Training Started...\\n\")\n\nfor epoch in range(EPOCHS):\n    model.train()\n    total_loss, correct, total = 0, 0, 0\n\n    for imgs, labels in tqdm(train_loader):\n        imgs, labels = imgs.to(DEVICE), labels.to(DEVICE)\n\n        optimizer.zero_grad()\n        with torch.amp.autocast(\"cuda\", enabled=USE_AMP):\n            outputs = model(imgs)\n            loss = criterion(outputs, labels)\n\n        scaler.scale(loss).backward()\n        scaler.step(optimizer)\n        scaler.update()\n\n        total_loss += loss.item()\n        correct += outputs.argmax(1).eq(labels).sum().item()\n        total += labels.size(0)\n\n    train_acc = (correct / total) * 100\n    train_loss = total_loss / len(train_loader)\n\n    # ----- Validation -----\n    model.eval()\n    val_loss, val_correct, val_total = 0, 0, 0\n\n    with torch.no_grad():\n        for imgs, labels in val_loader:\n            imgs, labels = imgs.to(DEVICE), labels.to(DEVICE)\n\n            with torch.amp.autocast(\"cuda\", enabled=USE_AMP):\n                outputs = model(imgs)\n                loss = criterion(outputs, labels)\n\n            val_loss += loss.item()\n            val_correct += outputs.argmax(1).eq(labels).sum().item()\n            val_total += labels.size(0)\n\n    val_acc = (val_correct / val_total) * 100\n    val_loss /= len(val_loader)\n\n    print(f\"📌 Epoch [{epoch+1}/{EPOCHS}] | Train Loss: {train_loss:.4f} | Acc: {train_acc:.2f}% | Val Loss: {val_loss:.4f} | Val Acc: {val_acc:.2f}%\")\n\n    # Save best model\n    if val_loss < best_loss:\n        best_loss = val_loss\n        torch.save(model.state_dict(), \"/kaggle/working/best_model.pth\")\n        print(\"💾 Saved Best Model\\n\")\n\n\nprint(\"\\n🎉 Training Complete!\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-04T12:19:51.175957Z","iopub.execute_input":"2025-12-04T12:19:51.176316Z","iopub.status.idle":"2025-12-04T12:39:01.167845Z","shell.execute_reply.started":"2025-12-04T12:19:51.176265Z","shell.execute_reply":"2025-12-04T12:39:01.166623Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"<a id=\"Evalution\"></a>\n# <div style=\"text-align:center; border-radius:30px 30px; padding:7px; color:white; margin:0; font-size:110%; font-family:Pacifico; background-color:#5b81d4; overflow:hidden\"><b>Evalution </b></div>","metadata":{}},{"cell_type":"code","source":"metrics_path = \"/kaggle/input/swinv2-small-window16-256/fastvit_s12.Csv\"  # Path to metrics CSV\nmetrics_df = pd.read_csv(metrics_path)\n\n# Set Seaborn style for better aesthetics\nsns.set_theme(style=\"whitegrid\")\n\n# Create a figure for visualizations\nplt.figure(figsize=(12, 8))\n\n# Plot training and validation loss\nplt.subplot(2, 1, 1)\nsns.lineplot(x='epoch', y='train_loss', data=metrics_df, label='Train Loss', color='blue', marker=\"o\")\nsns.lineplot(x='epoch', y='val_loss', data=metrics_df, label='Validation Loss', color='orange', marker=\"o\")\nplt.title(\"Training and Validation Loss per Epoch\", fontsize=14, fontweight='bold')\nplt.xlabel(\"Epoch\", fontsize=12)\nplt.ylabel(\"Loss\", fontsize=12)\nplt.legend()\nplt.grid(alpha=0.3)\n\n# Plot training and validation accuracy\nplt.subplot(2, 1, 2)\nsns.lineplot(x='epoch', y='train_top1_acc', data=metrics_df, label='Train Accuracy', color='green', marker=\"o\")\nsns.lineplot(x='epoch', y='val_top1_acc', data=metrics_df, label='Validation Accuracy', color='red', marker=\"o\")\nplt.title(\"Training and Validation Accuracy per Epoch\", fontsize=14, fontweight='bold')\nplt.xlabel(\"Epoch\", fontsize=12)\nplt.ylabel(\"Accuracy\", fontsize=12)\nplt.legend()\nplt.grid(alpha=0.3)\n\n# Adjust spacing between plots\nplt.tight_layout()\n\n# Save the visualization as a file (optional)\noutput_plot_path = f\"{MODEL_NAME}_training_visualization.png\"\nplt.savefig(output_plot_path, dpi=300)\nprint(f\"Visualization saved to {output_plot_path}\")\n\n# Show the plots\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-04T12:58:44.278589Z","iopub.execute_input":"2025-12-04T12:58:44.278943Z","iopub.status.idle":"2025-12-04T12:58:45.881394Z","shell.execute_reply.started":"2025-12-04T12:58:44.278911Z","shell.execute_reply":"2025-12-04T12:58:45.880521Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Load your model from checkpoint\ndef load_model_from_checkpoint(checkpoint_path, model_class, device):\n    model.load_state_dict(torch.load(checkpoint_path, map_location=device))\n    model.to(device)\n    model.eval()  # Set to evaluation mode\n    return model","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-04T12:58:53.242047Z","iopub.execute_input":"2025-12-04T12:58:53.242879Z","iopub.status.idle":"2025-12-04T12:58:53.246892Z","shell.execute_reply.started":"2025-12-04T12:58:53.242843Z","shell.execute_reply":"2025-12-04T12:58:53.246095Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Predict on validation data\ndef predict_on_validation(model, dataloader, device):\n    model.eval()  # Set the model to evaluation mode\n    y_true = []\n    y_pred = []\n\n    with torch.no_grad():  # No need to compute gradients for validation\n        for inputs, labels in val_loader:  # Assuming dataloader is a dictionary with 'val' key\n            inputs = inputs.to(device)\n            labels = labels.to(device)\n            outputs = model(inputs)\n            _, preds = torch.max(outputs, 1)\n\n            # Collect true and predicted labels\n            y_true.extend(labels.cpu().numpy())\n            y_pred.extend(preds.cpu().numpy())\n\n    return np.array(y_true), np.array(y_pred)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-04T12:58:59.594248Z","iopub.execute_input":"2025-12-04T12:58:59.594634Z","iopub.status.idle":"2025-12-04T12:58:59.600746Z","shell.execute_reply.started":"2025-12-04T12:58:59.594600Z","shell.execute_reply":"2025-12-04T12:58:59.599653Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch\nimport timm\n\n# Paths and config\ncheckpoint_path = \"/kaggle/input/swinv2-small-window16-256/swinv2_small_window16_256_9.pt\"\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nnum_classes = 5\n\n# ---- Load SwinV2 model ----\nmodel = timm.create_model(\n    \"swinv2_small_window16_256\", \n    pretrained=False, \n    num_classes=num_classes\n)\n\n# ---- Load checkpoint ----\nstate_dict = torch.load(checkpoint_path, map_location=device)\n\n# If checkpoint contains wrapper keys (like \"model\")\nif \"model\" in state_dict:\n    state_dict = state_dict[\"model\"]\n\nmissing, unexpected = model.load_state_dict(state_dict, strict=False)\n\nprint(\"Missing keys:\", missing)\nprint(\"Unexpected keys:\", unexpected)\n\nmodel.to(device)\nmodel.eval()\nprint(\"Model loaded successfully!\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-04T13:00:19.069951Z","iopub.execute_input":"2025-12-04T13:00:19.070326Z","iopub.status.idle":"2025-12-04T13:00:20.165609Z","shell.execute_reply.started":"2025-12-04T13:00:19.070269Z","shell.execute_reply":"2025-12-04T13:00:20.164736Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Run prediction\ny_true, y_pred = predict_on_validation(model, val_loader, device)\nprint(\"Prediction completed!\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-04T13:01:11.743026Z","iopub.execute_input":"2025-12-04T13:01:11.743872Z","iopub.status.idle":"2025-12-04T13:01:58.185559Z","shell.execute_reply.started":"2025-12-04T13:01:11.743838Z","shell.execute_reply":"2025-12-04T13:01:58.184504Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.metrics import classification_report\n\nreport = classification_report(y_true, y_pred, digits=2)\nprint(\"\\nClassification Report:\\n\", report)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-04T13:02:08.136557Z","iopub.execute_input":"2025-12-04T13:02:08.137332Z","iopub.status.idle":"2025-12-04T13:02:08.152272Z","shell.execute_reply.started":"2025-12-04T13:02:08.137269Z","shell.execute_reply":"2025-12-04T13:02:08.151472Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import confusion_matrix\n\n# Define the mapping of class labels to category names\nlevel_to_category = {\n    0: \"No_DR\",\n    1: \"Mild\",\n    2: \"Moderate\",\n    3: \"Severe\",\n    4: \"Proliferate_DR\"\n}\n\n# Compute confusion matrix\ncm = confusion_matrix(y_true, y_pred)\n\n# Plot confusion matrix using seaborn\nplt.figure(figsize=(8, 6))\nsns.heatmap(cm, annot=True, fmt='d', cmap='Blues', \n            xticklabels=[level_to_category[i] for i in range(cm.shape[0])],\n            yticklabels=[level_to_category[i] for i in range(cm.shape[0])])\n\nplt.xlabel('Predicted')\nplt.ylabel('True')\nplt.title('Confusion Matrix')\nplt.xticks(rotation=45)\nplt.yticks(rotation=45)\nplt.savefig('/kaggle/working/Confision.png')\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-04T13:02:19.800802Z","iopub.execute_input":"2025-12-04T13:02:19.801605Z","iopub.status.idle":"2025-12-04T13:02:20.300018Z","shell.execute_reply.started":"2025-12-04T13:02:19.801573Z","shell.execute_reply":"2025-12-04T13:02:20.299199Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\n\n# Calculate errors per class (misclassifications)\nclass_errors = {}\nnum_classes = cm.shape[0]\n\nfor i in range(num_classes):\n    total = np.sum(cm[i, :])  # Total number of instances of class i\n    incorrect = total - cm[i, i]  # Misclassified instances of class i\n    error_rate = incorrect / total if total != 0 else 0\n    class_errors[level_to_category[i]] = round(error_rate, 4)  # Round error_rate and map to class name\n\n# Print class errors\nfor class_name, error_rate in class_errors.items():\n    print(f\"Class {class_name}: Error Rate = {error_rate}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-04T13:02:26.654695Z","iopub.execute_input":"2025-12-04T13:02:26.655279Z","iopub.status.idle":"2025-12-04T13:02:26.660945Z","shell.execute_reply.started":"2025-12-04T13:02:26.655244Z","shell.execute_reply":"2025-12-04T13:02:26.660063Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Create a DataFrame for the error rates\nerror_data = pd.DataFrame(list(class_errors.items()), columns=['Class', 'Error Rate'])\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-04T13:02:36.081603Z","iopub.execute_input":"2025-12-04T13:02:36.082344Z","iopub.status.idle":"2025-12-04T13:02:36.086975Z","shell.execute_reply.started":"2025-12-04T13:02:36.082274Z","shell.execute_reply":"2025-12-04T13:02:36.086100Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Plot only the table, fitting the entire figure\nfig, ax = plt.subplots(figsize=(8, 4))  # Adjust size as needed\nax.axis('off')  # Turn off axis for the table\n\n# Create and display the table, making it fill the figure\ntable = ax.table(cellText=error_data.values, colLabels=error_data.columns, cellLoc='center', loc='center')\ntable.auto_set_font_size(False)\ntable.set_fontsize(12)\ntable.auto_set_column_width(col=list(range(len(error_data.columns))))\ntable.scale(20, 5)  # Scale table size (adjust the values as needed)\n\nplt.tight_layout()\nplt.savefig('/kaggle/working/TableSWINAdamW.png')\n\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-04T13:02:40.940772Z","iopub.execute_input":"2025-12-04T13:02:40.941196Z","iopub.status.idle":"2025-12-04T13:02:41.402802Z","shell.execute_reply.started":"2025-12-04T13:02:40.941163Z","shell.execute_reply":"2025-12-04T13:02:41.401332Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# End","metadata":{}}]}