{"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":418031,"sourceType":"datasetVersion","datasetId":131128}],"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\nimport torch.optim.optimizer\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 f1_score\nimport seaborn as sns\nfrom tqdm import tqdm\nimport concurrent.futures\nfrom torch.utils.data import random_split\nfrom sklearn.metrics import classification_report, f1_score\n\nprint(torch.__version__)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-02T15:22:10.245984Z","iopub.execute_input":"2025-10-02T15:22:10.246724Z","iopub.status.idle":"2025-10-02T15:22:17.175777Z","shell.execute_reply.started":"2025-10-02T15:22:10.246687Z","shell.execute_reply":"2025-10-02T15:22:17.174873Z"}},"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":"train= pd.read_csv('/kaggle/input/diabetic-retinopathy-resized/trainLabels.csv')\ntest= pd.read_csv('../input/aptos2019-blindness-detection/test.csv')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-02T15:22:17.177757Z","iopub.execute_input":"2025-10-02T15:22:17.178566Z","iopub.status.idle":"2025-10-02T15:22:17.222584Z","shell.execute_reply.started":"2025-10-02T15:22:17.178523Z","shell.execute_reply":"2025-10-02T15:22:17.221934Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print('Number of train samples: ', train.shape[0])\nprint('Number of test samples: ', test.shape[0])\ndisplay(train.head())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-02T15:22:17.223537Z","iopub.execute_input":"2025-10-02T15:22:17.223858Z","iopub.status.idle":"2025-10-02T15:22:17.239203Z","shell.execute_reply.started":"2025-10-02T15:22:17.223819Z","shell.execute_reply":"2025-10-02T15:22:17.238216Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"f, ax = plt.subplots(figsize=(14, 8.7))\nax = sns.countplot(x=\"level\", data=train, palette=\"GnBu_d\")\nsns.despine()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-02T15:22:17.240205Z","iopub.execute_input":"2025-10-02T15:22:17.240498Z","iopub.status.idle":"2025-10-02T15:22:17.489518Z","shell.execute_reply.started":"2025-10-02T15:22:17.240473Z","shell.execute_reply":"2025-10-02T15:22:17.488649Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Setting the style for the plot\nsns.set_style(\"white\")\n\n# Mapping class labels to their corresponding categories\nlevel_to_category = {\n    0: \"No_DR\",\n    1: \"Mild\",\n    2: \"Moderate\",\n    3: \"Severe\",\n    4: \"Proliferate_DR\"\n}\n\n# Plotting the first 15 images along with their labels\ncount = 1\nplt.figure(figsize=[20, 20])\n\nfor img_name in train['image'][:15]:  # Assuming 'train' contains the dataset\n    img = cv2.imread(f\"../input/diabetic-retinopathy-resized/resized_train/resized_train/{img_name}.jpeg\")[..., [2, 1, 0]]  # Reading the image\n    \n    # Getting the label (class) for the image\n    label = train[train['image'] == img_name]['level'].values[0]  # Assuming 'diagnosis' is the label column\n    \n    # Setting up the subplot with image and label\n    plt.subplot(5, 5, count)\n    plt.imshow(img)\n    plt.title(f\"Image {count}: {level_to_category[label]}\")  # Display the class label\n    count += 1\n# Display the plot\nplt.savefig('/kaggle/working/imagebeforepreprecssing.png')\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-02T15:22:17.491552Z","iopub.execute_input":"2025-10-02T15:22:17.491856Z","iopub.status.idle":"2025-10-02T15:22:23.808426Z","shell.execute_reply.started":"2025-10-02T15:22:17.491830Z","shell.execute_reply":"2025-10-02T15:22:23.807298Z"}},"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> Data Preprocessing </b></div>","metadata":{}},{"cell_type":"code","source":"# Function to crop the image based on grayscale threshold\ndef crop_image_from_gray(img, tol=7):\n    if img.ndim == 2:\n        mask = img > tol\n        return img[np.ix_(mask.any(1), mask.any(0))]\n    elif img.ndim == 3:\n        gray_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n        mask = gray_img > tol\n        \n        check_shape = img[:,:,0][np.ix_(mask.any(1), mask.any(0))].shape[0]\n        if check_shape == 0:  # Image is too dark so that we crop out everything\n            return img  # Return original image\n        else:\n            img1 = img[:,:,0][np.ix_(mask.any(1), mask.any(0))]\n            img2 = img[:,:,1][np.ix_(mask.any(1), mask.any(0))]\n            img3 = img[:,:,2][np.ix_(mask.any(1), mask.any(0))]\n            img = np.stack([img1, img2, img3], axis=-1)\n        return img","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-02T15:22:23.809478Z","iopub.execute_input":"2025-10-02T15:22:23.809751Z","iopub.status.idle":"2025-10-02T15:22:23.816110Z","shell.execute_reply.started":"2025-10-02T15:22:23.809725Z","shell.execute_reply":"2025-10-02T15:22:23.815173Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Set input and output directories\ninput_dir = '/kaggle/input/diabetic-retinopathy-resized/resized_train/resized_train/'\noutput_dir = '/kaggle/working/processed_images/'\n\n# Ensure the output directory exists\nos.makedirs(output_dir, exist_ok=True)\n\n# Load the CSV containing image names and labels\ncsv_path = '/kaggle/input/diabetic-retinopathy-resized/trainLabels.csv'\ndf = pd.read_csv(csv_path)\n\n# Create a CLAHE object\nclahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))\n\n# Function to process a single image\ndef process_image(row):\n    sample_image_id = row['image']  # Get the image ID\n    sample_image_file = sample_image_id + '.jpeg'  # Assuming the image files have .png extension\n    sample_image_path = os.path.join(input_dir, sample_image_file)\n\n    if os.path.exists(sample_image_path):\n        # Load the image\n        image = cv2.imread(sample_image_path)\n        \n        # Crop the image based on gray threshold\n        image_cropped = crop_image_from_gray(image)\n        \n        # Resize the image to 256x256\n        image_resized = cv2.resize(image_cropped, (256, 256))\n        \n        # Split the image into its channels (BGR format)\n        blue, green, red = cv2.split(image_resized)\n        \n        # Apply CLAHE to all three channels\n        blue_clahe = clahe.apply(blue)\n        green_clahe = clahe.apply(green)\n        red_clahe = clahe.apply(red)\n        \n        # Merge the CLAHE-enhanced channels back together\n        result_image = cv2.merge([blue_clahe, green_clahe, red_clahe])\n        \n        # Save the processed image to the output directory\n        output_path = os.path.join(output_dir, sample_image_file)\n        cv2.imwrite(output_path, result_image)\n\n# Using ThreadPoolExecutor to process images in parallel\nwith concurrent.futures.ThreadPoolExecutor(max_workers=8) as executor:\n    # Using tqdm to show progress bar while processing images\n    list(tqdm(executor.map(process_image, [row for _, row in df.iterrows()]), total=df.shape[0], desc=\"Processing images\", unit=\"image\"))\n\nprint(\"Processing complete for all images.\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-02T15:22:23.817316Z","iopub.execute_input":"2025-10-02T15:22:23.817587Z","iopub.status.idle":"2025-10-02T15:27:55.420911Z","shell.execute_reply.started":"2025-10-02T15:22:23.817563Z","shell.execute_reply":"2025-10-02T15:27:55.419877Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Setting the style for the plot\nsns.set_style(\"white\")\n\n# Mapping class labels to their corresponding categories\nlevel_to_category = {\n    0: \"No_DR\",\n    1: \"Mild\",\n    2: \"Moderate\",\n    3: \"Severe\",\n    4: \"Proliferate_DR\"\n}\n\n# Plotting the first 15 images along with their labels\ncount = 1\nplt.figure(figsize=[20, 20])\n\nfor img_name in train['image'][:15]:  # Assuming 'train' contains the dataset\n    img = cv2.imread(f\"/kaggle/working/processed_images/{img_name}.jpeg\")[..., [2, 1, 0]]  # Reading the image\n    \n    # Getting the label (class) for the image\n    label = train[train['image'] == img_name]['level'].values[0]  # Assuming 'diagnosis' is the label column\n    \n    # Setting up the subplot with image and label\n    plt.subplot(5, 5, count)\n    plt.imshow(img)\n    plt.title(f\"Image {count}: {level_to_category[label]}\")  # Display the class label\n    count += 1\n\n# Display the plot\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-02T15:27:55.422113Z","iopub.execute_input":"2025-10-02T15:27:55.422578Z","iopub.status.idle":"2025-10-02T15:27:58.671621Z","shell.execute_reply.started":"2025-10-02T15:27:55.422546Z","shell.execute_reply":"2025-10-02T15:27:58.670602Z"}},"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":"DATA_DIR = \"/kaggle/working/processed_images\"\nTRAIN_DIR = \"/kaggle/working/processed_images\"\nCSV_PATH = \"/kaggle/input/diabetic-retinopathy-resized/trainLabels.csv\"\nMODEL_PATH = \"./kaggle/working/\"\nLEARNING_RATE = 1e-4\nTRAIN_BATCH_SIZE = 32\nVALID_BATCH_SIZE = 32\nTRAIN_SPLIT = 0.8\nNUM_WORKERS = 2\nUSE_AMP = True\nEPOCHS=25","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-02T15:27:58.672821Z","iopub.execute_input":"2025-10-02T15:27:58.673099Z","iopub.status.idle":"2025-10-02T15:27:58.677492Z","shell.execute_reply.started":"2025-10-02T15:27:58.673071Z","shell.execute_reply":"2025-10-02T15:27:58.676689Z"}},"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, 'image'] + '.jpeg')\n\n        tensor_image = read_image(img_name)\n        label = torch.tensor(self.data.loc[idx, 'level'], 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-10-02T15:27:58.678375Z","iopub.execute_input":"2025-10-02T15:27:58.678642Z","iopub.status.idle":"2025-10-02T15:27:58.689067Z","shell.execute_reply.started":"2025-10-02T15:27:58.678618Z","shell.execute_reply":"2025-10-02T15:27:58.688213Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_trasforms_DeiT_base_patch16= T.Compose([\n    T.ConvertImageDtype(torch.float32),\n    T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n])\n\nfull_dataset = RetinopathyDataset(TRAIN_DIR, CSV_PATH, transforms=train_trasforms_DeiT_base_patch16)\n\ntrain_size = int(TRAIN_SPLIT * len(full_dataset))\ntest_size = len(full_dataset) - train_size\n\ntrain_dataset, val_dataset = torch.utils.data.random_split(full_dataset, [train_size, test_size])\n\ntrain_loader = DataLoader(full_dataset, batch_size=TRAIN_BATCH_SIZE,\n                          shuffle=False, num_workers=NUM_WORKERS, drop_last=True, pin_memory=False)\n\nval_loader = DataLoader(val_dataset, batch_size=VALID_BATCH_SIZE, shuffle=False,\n                        num_workers=NUM_WORKERS, drop_last=True, pin_memory=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-02T15:27:58.689936Z","iopub.execute_input":"2025-10-02T15:27:58.690171Z","iopub.status.idle":"2025-10-02T15:27:58.740274Z","shell.execute_reply.started":"2025-10-02T15:27:58.690146Z","shell.execute_reply":"2025-10-02T15:27:58.739518Z"}},"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):\n    \"\"\"\n    Computes the overall accuracy of predictions.\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\n    Returns:\n        float: Accuracy as a percentage.\n    \"\"\"\n    with torch.no_grad():\n        _, predicted = output.max(1)  # Get the class index with the highest score\n        correct = predicted.eq(target).sum().item()  # Count correct predictions\n        total = target.size(0)  # Total number of samples\n        accuracy = 100.0 * correct / total  # Compute accuracy percentage\n\n    return accuracy\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","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-02T15:27:58.741426Z","iopub.execute_input":"2025-10-02T15:27:58.741710Z","iopub.status.idle":"2025-10-02T15:27:58.751361Z","shell.execute_reply.started":"2025-10-02T15:27:58.741681Z","shell.execute_reply":"2025-10-02T15:27:58.750600Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(torch.cuda.is_available())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-02T15:27:58.752630Z","iopub.execute_input":"2025-10-02T15:27:58.752892Z","iopub.status.idle":"2025-10-02T15:27:58.815837Z","shell.execute_reply.started":"2025-10-02T15:27:58.752864Z","shell.execute_reply":"2025-10-02T15:27:58.814873Z"}},"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: torch.nn.Module, train_loader, criterion, device: str, optimizer, scheduler=None, num_batches: int = None, log_interval: int = 100, scaler=None):\n    \"\"\"\n    Performs one step of training with progress tracking using tqdm, and updates progress at each epoch.\n    \"\"\"\n    model = model.to(device)\n    model.train()\n\n    start_train_step = time.time()\n    metrics = OrderedDict()\n\n    total_loss = 0\n    correct_predictions = 0\n    total_samples = 0\n\n    # Initialize tqdm progress bar for the training loop (per epoch)\n    with tqdm(train_loader, desc=\"Training\", unit=\"batch\") as pbar:\n        for batch_idx, (inputs, target) in enumerate(pbar):\n            inputs = inputs.to(device)\n            target = target.to(device)\n\n            # Zero the parameter gradients\n            optimizer.zero_grad()\n\n            # Mixed precision training if scaler is provided\n            if scaler is not None:\n                with torch.cuda.amp.autocast():\n                    output = model(inputs)\n                    loss = criterion(output, target)\n                scaler.scale(loss).backward()\n                scaler.step(optimizer)\n                scaler.update()\n            else:\n                output = model(inputs)\n                loss = criterion(output, target)\n                loss.backward()\n                optimizer.step()\n\n            # Update the scheduler if it's provided\n            if scheduler is not None:\n                scheduler.step()\n\n            # Update metrics\n            total_loss += loss.item() * inputs.size(0)\n            _, predicted = output.max(1)\n            correct_predictions += predicted.eq(target).sum().item()\n            total_samples += inputs.size(0)\n\n            # Update progress bar (per batch)\n            pbar.set_postfix({\n                \"Loss\": f\"{total_loss / total_samples:.4f}\",\n                \"Accuracy\": f\"{100.0 * correct_predictions / total_samples:.2f}%\"\n            })\n\n            # Break if num_batches is set and we've reached the limit\n            if num_batches is not None and batch_idx + 1 >= num_batches:\n                break\n\n    # Final metrics for the epoch\n    end_train_step = time.time()\n    metrics[\"loss\"] = total_loss / total_samples\n    metrics[\"accuracy\"] = 100.0 * correct_predictions / total_samples\n\n    # Print the time taken for the train step and the summary of the metrics\n    print(f\"\\nEpoch Summary: Time taken for train step = {end_train_step - start_train_step:.2f} sec\")\n    print(f\"Training loss = {metrics['loss']:.4f}, Training accuracy = {metrics['accuracy']:.2f}%\")\n\n    return metrics","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-02T15:27:58.819595Z","iopub.execute_input":"2025-10-02T15:27:58.820166Z","iopub.status.idle":"2025-10-02T15:27:58.831608Z","shell.execute_reply.started":"2025-10-02T15:27:58.820131Z","shell.execute_reply":"2025-10-02T15:27:58.830777Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"@torch.no_grad()  # No gradient calculation needed during validation\ndef val_step(model: torch.nn.Module, val_loader, criterion, device: str, num_batches=None, log_interval: int = 100):\n    \"\"\"\n    Performs one step of validation with progress tracking using tqdm.\n\n    Args:\n        model: A PyTorch CNN Model.\n        val_loader: DataLoader for the validation set.\n        criterion: Loss function to evaluate.\n        device: \"cuda\" or \"cpu\".\n        num_batches: (optional) Limit validation to a certain number of batches.\n        log_interval: (optional) Log after every specified number of batches.\n    \"\"\"\n    \n    model = model.to(device)\n    model.eval()  # Set the model to evaluation mode\n\n    start_val_step = time.time()  # Track the start time of the validation step\n    metrics = OrderedDict()\n\n    total_loss = 0\n    correct_predictions = 0\n    total_samples = 0\n\n    # Initialize tqdm progress bar for the validation loop (per epoch)\n    with tqdm(val_loader, desc=\"Validation\", unit=\"batch\") as pbar:\n        for batch_idx, (inputs, target) in enumerate(pbar):\n            inputs = inputs.to(device)\n            target = target.to(device)\n\n            # Forward pass (no gradient computation)\n            output = model(inputs)\n            loss = criterion(output, target)\n\n            # Update metrics\n            total_loss += loss.item() * inputs.size(0)\n            _, predicted = output.max(1)  # Get predictions\n            correct_predictions += predicted.eq(target).sum().item()  # Compare predictions with targets\n            total_samples += inputs.size(0)\n\n            # Update progress bar with the current loss and accuracy\n            pbar.set_postfix({\n                \"Loss\": f\"{total_loss / total_samples:.4f}\",\n                \"Accuracy\": f\"{100.0 * correct_predictions / total_samples:.2f}%\"\n            })\n\n            # Break if num_batches is specified and we've reached the limit\n            if num_batches is not None and batch_idx + 1 >= num_batches:\n                break\n\n    # Final metrics for the epoch\n    end_val_step = time.time()  # Track the end time of the validation step\n    metrics[\"loss\"] = total_loss / total_samples\n    metrics[\"accuracy\"] = 100.0 * correct_predictions / total_samples\n\n    # Print the time taken and the final validation metrics\n    print(f\"\\nValidation Summary: Time taken for validation step = {end_val_step - start_val_step:.2f} sec\")\n    print(f\"Validation loss = {metrics['loss']:.4f}, Validation accuracy = {metrics['accuracy']:.2f}%\")\n\n    return metrics\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-02T15:27:58.832976Z","iopub.execute_input":"2025-10-02T15:27:58.833320Z","iopub.status.idle":"2025-10-02T15:27:58.845298Z","shell.execute_reply.started":"2025-10-02T15:27:58.833284Z","shell.execute_reply":"2025-10-02T15:27:58.844487Z"}},"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":"\nMODEL_NAME = \"swinv2_small_window16_256\"\nMODEL_SAVE=  \"/kaggle/working/swinv2.Csv\"\nseed_everything(42)\nset_debug_apis(False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-02T15:27:58.846299Z","iopub.execute_input":"2025-10-02T15:27:58.846592Z","iopub.status.idle":"2025-10-02T15:27:58.862154Z","shell.execute_reply.started":"2025-10-02T15:27:58.846561Z","shell.execute_reply":"2025-10-02T15:27:58.861365Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Handle imbalnced Classes ","metadata":{}},{"cell_type":"code","source":"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-02T15:27:58.863138Z","iopub.execute_input":"2025-10-02T15:27:58.863487Z","iopub.status.idle":"2025-10-02T15:27:58.867633Z","shell.execute_reply.started":"2025-10-02T15:27:58.863441Z","shell.execute_reply":"2025-10-02T15:27:58.866836Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.utils.class_weight import compute_class_weight\n# Extract the class labels (diagnosis column)\nclass_labels = train['level'].values\n\n# Compute class weights using sklearn\nunique_classes = np.unique(class_labels)\nclass_weights = compute_class_weight('balanced', classes=unique_classes, y=class_labels)\n\n# Create a dictionary that maps class labels to their corresponding weights\nclass_weight_dict = {class_label: weight for class_label, weight in zip(unique_classes, class_weights)}\n\nprint(\"Class Weights:\", class_weight_dict)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-02T15:27:58.868598Z","iopub.execute_input":"2025-10-02T15:27:58.868839Z","iopub.status.idle":"2025-10-02T15:27:58.886925Z","shell.execute_reply.started":"2025-10-02T15:27:58.868816Z","shell.execute_reply":"2025-10-02T15:27:58.886127Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model= timm.create_model(MODEL_NAME, pretrained=True, num_classes=5)\nweights_tensor = torch.tensor(list(class_weight_dict.values())).float()\ncriterion= nn.CrossEntropyLoss(weight=weights_tensor.to(device))\noptimizer= optim.AdamW(model.parameters(), lr=LEARNING_RATE)\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-10-02T15:27:58.887865Z","iopub.execute_input":"2025-10-02T15:27:58.888112Z","iopub.status.idle":"2025-10-02T15:28:01.063084Z","shell.execute_reply.started":"2025-10-02T15:27:58.888086Z","shell.execute_reply":"2025-10-02T15:28:01.062186Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tqdm import tqdm\nimport time\nimport torch\nimport pandas as pd\n\n# Initialize lists to store metrics\ntrain_loss = []\ntrain_accuracy = []\nval_loss = []\nval_accuracy = []\n\n# Record start time\nstart_time = time.time()\n\n# Total number of batches for training and validation\ntrain_batches = len(train_loader)\nval_batches = len(val_loader)\n\n# Start epoch loop with tqdm tracking total iterations per epoch\nfor epoch in tqdm(range(EPOCHS), desc=\"Epochs\"):\n    print(f\"Epoch {epoch+1}/{EPOCHS}\")\n\n    # Initialize tqdm for the training loop (track overall progress for the epoch)\n    with tqdm(total=train_batches, desc=f\"Training Epoch {epoch+1}\", unit=\"batch\") as pbar_train:\n        # Perform training step\n        train_metrics = train_step(model, train_loader, criterion, device, optimizer, scaler=scaler)\n        train_loss.append(train_metrics[\"loss\"])\n        train_accuracy.append(train_metrics[\"accuracy\"])\n\n        # Update progress bar after training\n        pbar_train.set_postfix({\n            \"Loss\": f\"{train_metrics['loss']:.4f}\",\n            \"Accuracy\": f\"{train_metrics['accuracy']:.2f}%\"\n        })\n        pbar_train.update(train_batches)  # Update progress bar to the total number of batches\n\n    # Initialize tqdm for the validation loop (track overall progress for the epoch)\n    with tqdm(total=val_batches, desc=f\"Validation Epoch {epoch+1}\", unit=\"batch\") as pbar_val:\n        # Perform validation step\n        val_metrics = val_step(model, val_loader, criterion, device)\n        val_loss.append(val_metrics[\"loss\"])\n        val_accuracy.append(val_metrics[\"accuracy\"])\n\n        # Update progress bar after validation\n        pbar_val.set_postfix({\n            \"Loss\": f\"{val_metrics['loss']:.4f}\",\n            \"Accuracy\": f\"{val_metrics['accuracy']:.2f}%\"\n        })\n        pbar_val.update(val_batches)  # Update progress bar to the total number of batches\n\n    # Print epoch summary (not per-batch)\n    print(f\"\\nEpoch {epoch+1} Summary:\")\n    print(f\"Training loss = {train_metrics['loss']:.4f}, Training accuracy = {train_metrics['accuracy']:.2f}%\")\n    print(f\"Validation loss = {val_metrics['loss']:.4f}, Validation accuracy = {val_metrics['accuracy']:.2f}%\")\n\n    # Save model checkpoint\n    checkpoint_path = f\"{MODEL_NAME}_epoch_{epoch+1}.pt\"\n    torch.save(model.state_dict(), checkpoint_path)\n\n# Record end time\nend_time = time.time()\n\n# Calculate total training time\ntotal_time = end_time - start_time\nprint(f\"\\nTotal training time: {total_time:.2f} seconds\")\n\n# Create a DataFrame to store the metrics\nmetrics_df = pd.DataFrame({\n    \"epoch\": range(1, EPOCHS + 1),\n    \"train_loss\": train_loss,\n    \"train_accuracy\": train_accuracy,\n    \"val_loss\": val_loss,\n    \"val_accuracy\": val_accuracy,\n})\n\n# Save the DataFrame to CSV\nmetrics_df.to_csv(MODEL_SAVE, index=False)\nprint(\"Training metrics saved to CSV.\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-02T15:28:01.064263Z","iopub.execute_input":"2025-10-02T15:28:01.064561Z","iopub.status.idle":"2025-10-02T22:42:28.938530Z","shell.execute_reply.started":"2025-10-02T15:28:01.064534Z","shell.execute_reply":"2025-10-02T22:42:28.937478Z"}},"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 = f\"{MODEL_NAME}_metrics.csv\"  # Path to metrics CSV\nmetrics_df = pd.read_csv(MODEL_SAVE)\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')\nsns.lineplot(x='epoch', y='val_loss', data=metrics_df, label='Validation Loss', color='orange')\nplt.title(\"Training and Validation Loss per Epoch\", fontsize=14, fontweight='bold')\nplt.xlabel(\"Epoch\", fontsize=12)\nplt.ylabel(\"Loss\", fontsize=12)\nplt.legend()\n\n# Plot training and validation accuracy\nplt.subplot(2, 1, 2)\nsns.lineplot(x='epoch', y='train_accuracy', data=metrics_df, label='Train Accuracy', color='green')\nsns.lineplot(x='epoch', y='val_accuracy', data=metrics_df, label='Validation Accuracy', color='red')\nplt.title(\"Training and Validation Accuracy per Epoch\", fontsize=14, fontweight='bold')\nplt.xlabel(\"Epoch\", fontsize=12)\nplt.ylabel(\"Accuracy\", fontsize=12)\nplt.legend()\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-10-02T22:42:28.940270Z","iopub.execute_input":"2025-10-02T22:42:28.940682Z","iopub.status.idle":"2025-10-02T22:42:30.593789Z","shell.execute_reply.started":"2025-10-02T22:42:28.940638Z","shell.execute_reply":"2025-10-02T22:42:30.592935Z"}},"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-10-02T22:42:30.594984Z","iopub.execute_input":"2025-10-02T22:42:30.595617Z","iopub.status.idle":"2025-10-02T22:42:30.600890Z","shell.execute_reply.started":"2025-10-02T22:42:30.595577Z","shell.execute_reply":"2025-10-02T22:42:30.599844Z"}},"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-10-02T22:42:30.602108Z","iopub.execute_input":"2025-10-02T22:42:30.602682Z","iopub.status.idle":"2025-10-02T22:42:30.614075Z","shell.execute_reply.started":"2025-10-02T22:42:30.602641Z","shell.execute_reply":"2025-10-02T22:42:30.613363Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Define paths and device\ncheckpoint_path = \"/kaggle/working/swinv2_small_window16_256_epoch_19.pt\"\nmodel_class=5\n# Initialize and load the model (replace YourModel with your actual model class)\nmodel = load_model_from_checkpoint(checkpoint_path, model_class, device)\n\n# Assuming `dataloaders` is a dictionary with 'val' key containing the validation dataloader\n# Predict on validation set\ny_true, y_pred = predict_on_validation(model, val_loader, device)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-02T22:42:30.615172Z","iopub.execute_input":"2025-10-02T22:42:30.615519Z","iopub.status.idle":"2025-10-02T22:43:26.847324Z","shell.execute_reply.started":"2025-10-02T22:42:30.615483Z","shell.execute_reply":"2025-10-02T22:43:26.846169Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Generate Classification Report\nreport = classification_report(y_true, y_pred, digits=2)\nprint(\"\\nClassification Report:\\n\", report)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-02T22:43:26.848830Z","iopub.execute_input":"2025-10-02T22:43:26.849137Z","iopub.status.idle":"2025-10-02T22:43:26.872884Z","shell.execute_reply.started":"2025-10-02T22:43:26.849103Z","shell.execute_reply":"2025-10-02T22:43:26.872126Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\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=np.arange(cm.shape[0]), yticklabels=np.arange(cm.shape[0]))\nplt.xlabel('Predicted')\nplt.ylabel('True')\nplt.title('Confusion Matrix')\nplt.savefig('confusion_matrix_Swin 98.png', bbox_inches='tight')\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-02T22:43:26.873820Z","iopub.execute_input":"2025-10-02T22:43:26.874067Z","iopub.status.idle":"2025-10-02T22:43:27.434973Z","shell.execute_reply.started":"2025-10-02T22:43:26.874042Z","shell.execute_reply":"2025-10-02T22:43:27.434166Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Define the level-to-category mapping\nlevel_to_category = {\n    0: \"No_DR\",\n    1: \"Mild\",\n    2: \"Moderate\",\n    3: \"Severe\",\n    4: \"Proliferate_DR\"\n}\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-10-02T22:43:27.436303Z","iopub.execute_input":"2025-10-02T22:43:27.436982Z","iopub.status.idle":"2025-10-02T22:43:27.443402Z","shell.execute_reply.started":"2025-10-02T22:43:27.436937Z","shell.execute_reply":"2025-10-02T22:43:27.442499Z"}},"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-10-02T22:43:27.444420Z","iopub.execute_input":"2025-10-02T22:43:27.444678Z","iopub.status.idle":"2025-10-02T22:43:27.459128Z","shell.execute_reply.started":"2025-10-02T22:43:27.444654Z","shell.execute_reply":"2025-10-02T22:43:27.458408Z"}},"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)\nplt.savefig('Swin Table .png', bbox_inches='tight')\n\nplt.tight_layout()\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-02T22:43:27.460066Z","iopub.execute_input":"2025-10-02T22:43:27.460316Z","iopub.status.idle":"2025-10-02T22:43:27.843199Z","shell.execute_reply.started":"2025-10-02T22:43:27.460292Z","shell.execute_reply":"2025-10-02T22:43:27.842345Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch\nimport cv2\nimport numpy as np\nfrom torchvision import transforms as T\nfrom PIL import Image\nimport matplotlib.pyplot as plt\n\n# Define the preprocessing pipeline (same as during training)\ntrain_transforms_DeiT_base_patch16 = T.Compose([\n    T.ToTensor(),\n    T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n])\n\ndef process_external_image(image_path, transform=train_transforms_DeiT_base_patch16):\n    \"\"\"\n    Process an external image to match the model's expected input format.\n    \"\"\"\n    # Load the image\n    image = cv2.imread(image_path)\n    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)  # Convert to RGB\n\n    # Crop, resize, and apply CLAHE preprocessing\n    image_cropped = crop_image_from_gray(image)\n    image_resized = cv2.resize(image_cropped, (256, 256))\n\n    # Apply CLAHE enhancement (you can reuse the previous CLAHE code for this)\n    blue, green, red = cv2.split(image_resized)\n    clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))\n    blue_clahe = clahe.apply(blue)\n    green_clahe = clahe.apply(green)\n    red_clahe = clahe.apply(red)\n    result_image = cv2.merge([blue_clahe, green_clahe, red_clahe])\n\n    # Convert to PIL Image for transformation\n    pil_image = Image.fromarray(result_image)\n\n    # Apply the transform (normalization)\n    image_tensor = transform(pil_image)\n\n    # Add batch dimension\n    image_tensor = image_tensor.unsqueeze(0)\n    \n    return image_tensor\n\ndef predict_on_external_image(model, image_tensor, device):\n    \"\"\"\n    Predict the class label of an external image using the trained model.\n    \"\"\"\n    model.eval()  # Set model to evaluation mode\n    image_tensor = image_tensor.to(device)  # Move the image tensor to the device (GPU or CPU)\n\n    # Make prediction with the model\n    with torch.no_grad():\n        output = model(image_tensor)\n        _, predicted_label = torch.max(output, 1)  # Get the predicted label\n    \n    return predicted_label.item()\n\n# Example Usage:\nimage_path = \"/kaggle/input/diabetic-retinopathy-resized/resized_train/resized_train/10003_left.jpeg\"  # Replace with the path to the external image\n\n# Process the external image\nimage_tensor = process_external_image(image_path)\n\n# Predict the label\npredicted_label = predict_on_external_image(model, image_tensor, device)\n\n# Map the predicted label to category (based on your labels)\nlevel_to_category = {\n    0: \"No_DR\",\n    1: \"Mild\",\n    2: \"Moderate\",\n    3: \"Severe\",\n    4: \"Proliferate_DR\"\n}\n\n# Print the predicted category\nprint(f\"Predicted label: {level_to_category[predicted_label]}\")\n\n# Display the image\nimage = cv2.imread(image_path)\nimage_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\nplt.imshow(image_rgb)\nplt.title(f\"Predicted: {level_to_category[predicted_label]}\")\nplt.axis('off')  # Turn off axis\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-02T22:43:27.844746Z","iopub.execute_input":"2025-10-02T22:43:27.845089Z","iopub.status.idle":"2025-10-02T22:43:28.662198Z","shell.execute_reply.started":"2025-10-02T22:43:27.845053Z","shell.execute_reply":"2025-10-02T22:43:28.661357Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# End","metadata":{}},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}