{"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.11.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":418031,"sourceType":"datasetVersion","datasetId":131128}],"dockerImageVersionId":31090,"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-07T23:24:46.333645Z","iopub.execute_input":"2025-10-07T23:24:46.333923Z","iopub.status.idle":"2025-10-07T23:24:58.356822Z","shell.execute_reply.started":"2025-10-07T23:24:46.3339Z","shell.execute_reply":"2025-10-07T23:24:58.35598Z"}},"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')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-07T23:24:58.358166Z","iopub.execute_input":"2025-10-07T23:24:58.358588Z","iopub.status.idle":"2025-10-07T23:24:58.394829Z","shell.execute_reply.started":"2025-10-07T23:24:58.358567Z","shell.execute_reply":"2025-10-07T23:24:58.394246Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print('Number of train samples: ', train.shape[0])\ndisplay(train.head())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-07T23:24:58.395595Z","iopub.execute_input":"2025-10-07T23:24:58.395825Z","iopub.status.idle":"2025-10-07T23:24:58.417105Z","shell.execute_reply.started":"2025-10-07T23:24:58.395807Z","shell.execute_reply":"2025-10-07T23:24:58.41652Z"}},"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-07T23:24:58.419012Z","iopub.execute_input":"2025-10-07T23:24:58.419478Z","iopub.status.idle":"2025-10-07T23:24:58.638472Z","shell.execute_reply.started":"2025-10-07T23:24:58.41946Z","shell.execute_reply":"2025-10-07T23:24:58.637734Z"}},"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-07T23:24:58.639245Z","iopub.execute_input":"2025-10-07T23:24:58.639487Z","iopub.status.idle":"2025-10-07T23:25:05.004094Z","shell.execute_reply.started":"2025-10-07T23:24:58.639469Z","shell.execute_reply":"2025-10-07T23:25:05.003302Z"}},"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-07T23:25:05.005053Z","iopub.execute_input":"2025-10-07T23:25:05.00533Z","iopub.status.idle":"2025-10-07T23:25:05.011683Z","shell.execute_reply.started":"2025-10-07T23:25:05.005309Z","shell.execute_reply":"2025-10-07T23:25:05.011052Z"}},"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\n# Function to process a single image with Gaussian Blur\ndef process_image(row):\n    sample_image_id = row['image']\n    sample_image_file = sample_image_id + '.jpeg'\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 out gray background\n        image_cropped = crop_image_from_gray(image)\n\n        # Resize to 256x256\n        image_resized = cv2.resize(image_cropped, (256, 256))\n\n        # ✅ Apply Gaussian Blur\n        blurred_image = cv2.addWeighted(image_resized, 4, \n                                        cv2.GaussianBlur(image_resized, (0, 0), 10), -4, 128)\n\n        # Save the processed image\n        output_path = os.path.join(output_dir, sample_image_file)\n        cv2.imwrite(output_path, blurred_image)\n       \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-07T23:25:05.012409Z","iopub.execute_input":"2025-10-07T23:25:05.012646Z","iopub.status.idle":"2025-10-07T23:32:40.892318Z","shell.execute_reply.started":"2025-10-07T23:25:05.012627Z","shell.execute_reply":"2025-10-07T23:32:40.891644Z"}},"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-07T23:32:40.893143Z","iopub.execute_input":"2025-10-07T23:32:40.89342Z","iopub.status.idle":"2025-10-07T23:32:44.105008Z","shell.execute_reply.started":"2025-10-07T23:32:40.893397Z","shell.execute_reply":"2025-10-07T23:32:44.104188Z"}},"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-07T23:32:44.106035Z","iopub.execute_input":"2025-10-07T23:32:44.106275Z","iopub.status.idle":"2025-10-07T23:32:44.110383Z","shell.execute_reply.started":"2025-10-07T23:32:44.106246Z","shell.execute_reply":"2025-10-07T23:32:44.109663Z"}},"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-07T23:32:44.112791Z","iopub.execute_input":"2025-10-07T23:32:44.113008Z","iopub.status.idle":"2025-10-07T23:32:44.123345Z","shell.execute_reply.started":"2025-10-07T23:32:44.112992Z","shell.execute_reply":"2025-10-07T23:32:44.122368Z"}},"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(train_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)\n\nfrom collections import Counter\n\n# Hitung distribusi label di train\ntrain_labels = [train_dataset[i][1].item() for i in range(len(train_dataset))]\nval_labels   = [val_dataset[i][1].item() for i in range(len(val_dataset))]\n\nprint(\"Distribusi label di TRAIN:\")\nprint(Counter(train_labels))\n\nprint(\"\\nDistribusi label di VAL:\")\nprint(Counter(val_labels))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-07T23:32:44.124171Z","iopub.execute_input":"2025-10-07T23:32:44.124359Z","iopub.status.idle":"2025-10-07T23:33:39.551555Z","shell.execute_reply.started":"2025-10-07T23:32:44.124344Z","shell.execute_reply":"2025-10-07T23:33:39.55082Z"}},"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-07T23:33:39.552556Z","iopub.execute_input":"2025-10-07T23:33:39.552796Z","iopub.status.idle":"2025-10-07T23:33:39.559782Z","shell.execute_reply.started":"2025-10-07T23:33:39.552777Z","shell.execute_reply":"2025-10-07T23:33:39.559092Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(torch.cuda.is_available())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-07T23:33:39.560558Z","iopub.execute_input":"2025-10-07T23:33:39.561232Z","iopub.status.idle":"2025-10-07T23:33:39.636816Z","shell.execute_reply.started":"2025-10-07T23:33:39.561213Z","shell.execute_reply":"2025-10-07T23:33:39.635986Z"}},"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-07T23:33:39.637553Z","iopub.execute_input":"2025-10-07T23:33:39.637764Z","iopub.status.idle":"2025-10-07T23:33:39.655523Z","shell.execute_reply.started":"2025-10-07T23:33:39.637749Z","shell.execute_reply":"2025-10-07T23:33:39.654653Z"}},"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.Csv\"\nseed_everything(42)\nset_debug_apis(False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-07T23:33:39.656327Z","iopub.execute_input":"2025-10-07T23:33:39.656585Z","iopub.status.idle":"2025-10-07T23:33:39.676155Z","shell.execute_reply.started":"2025-10-07T23:33:39.656561Z","shell.execute_reply":"2025-10-07T23:33:39.675536Z"}},"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-07T23:33:39.67684Z","iopub.execute_input":"2025-10-07T23:33:39.677115Z","iopub.status.idle":"2025-10-07T23:33:39.681127Z","shell.execute_reply.started":"2025-10-07T23:33:39.677095Z","shell.execute_reply":"2025-10-07T23:33:39.680419Z"}},"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-07T23:33:39.68205Z","iopub.execute_input":"2025-10-07T23:33:39.682276Z","iopub.status.idle":"2025-10-07T23:33:39.705335Z","shell.execute_reply.started":"2025-10-07T23:33:39.682261Z","shell.execute_reply":"2025-10-07T23:33:39.704807Z"}},"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-07T23:33:39.705957Z","iopub.execute_input":"2025-10-07T23:33:39.706208Z","iopub.status.idle":"2025-10-07T23:33:44.195327Z","shell.execute_reply.started":"2025-10-07T23:33:39.70619Z","shell.execute_reply":"2025-10-07T23:33:44.194469Z"}},"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 = []\n\n# Record start time\nstart_time = time.time()\n\n# Total number of batches for training and validation\ntrain_batches = len(train_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    # 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\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})\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-07T23:33:44.196274Z","iopub.execute_input":"2025-10-07T23:33:44.19656Z","iopub.status.idle":"2025-10-08T04:57:38.903229Z","shell.execute_reply.started":"2025-10-07T23:33:44.196529Z","shell.execute_reply":"2025-10-08T04:57:38.902293Z"}},"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')\nplt.title(\"Training 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')\nplt.title(\"Training 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-08T04:57:38.904476Z","iopub.execute_input":"2025-10-08T04:57:38.904867Z","iopub.status.idle":"2025-10-08T04:57:40.749562Z","shell.execute_reply.started":"2025-10-08T04:57:38.904838Z","shell.execute_reply":"2025-10-08T04:57:40.748762Z"}},"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-08T04:57:40.750481Z","iopub.execute_input":"2025-10-08T04:57:40.750783Z","iopub.status.idle":"2025-10-08T04:57:40.755154Z","shell.execute_reply.started":"2025-10-08T04:57:40.750762Z","shell.execute_reply":"2025-10-08T04:57:40.754484Z"}},"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-08T04:57:40.755956Z","iopub.execute_input":"2025-10-08T04:57:40.756262Z","iopub.status.idle":"2025-10-08T04:57:40.769346Z","shell.execute_reply.started":"2025-10-08T04:57:40.756232Z","shell.execute_reply":"2025-10-08T04:57:40.768734Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Define paths and device\ncheckpoint_path = \"/kaggle/working/swinv2_small_window16_256_epoch_25.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-08T04:57:40.770121Z","iopub.execute_input":"2025-10-08T04:57:40.77035Z","iopub.status.idle":"2025-10-08T04:58:38.073558Z","shell.execute_reply.started":"2025-10-08T04:57:40.770333Z","shell.execute_reply":"2025-10-08T04:58:38.072639Z"}},"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-08T04:58:38.074655Z","iopub.execute_input":"2025-10-08T04:58:38.074941Z","iopub.status.idle":"2025-10-08T04:58:38.098568Z","shell.execute_reply.started":"2025-10-08T04:58:38.074915Z","shell.execute_reply":"2025-10-08T04:58:38.097901Z"}},"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-08T04:58:38.099486Z","iopub.execute_input":"2025-10-08T04:58:38.099753Z","iopub.status.idle":"2025-10-08T04:58:38.65992Z","shell.execute_reply.started":"2025-10-08T04:58:38.099728Z","shell.execute_reply":"2025-10-08T04:58:38.659071Z"}},"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-08T04:58:38.660827Z","iopub.execute_input":"2025-10-08T04:58:38.661051Z","iopub.status.idle":"2025-10-08T04:58:38.667488Z","shell.execute_reply.started":"2025-10-08T04:58:38.661031Z","shell.execute_reply":"2025-10-08T04:58:38.666805Z"}},"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-08T04:58:38.668166Z","iopub.execute_input":"2025-10-08T04:58:38.668352Z","iopub.status.idle":"2025-10-08T04:58:38.686955Z","shell.execute_reply.started":"2025-10-08T04:58:38.668336Z","shell.execute_reply":"2025-10-08T04:58:38.68596Z"}},"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-08T04:58:38.691366Z","iopub.execute_input":"2025-10-08T04:58:38.691594Z","iopub.status.idle":"2025-10-08T04:58:39.093941Z","shell.execute_reply.started":"2025-10-08T04:58:38.691577Z","shell.execute_reply":"2025-10-08T04:58:39.093011Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# End","metadata":{}}]}