{"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":212035308,"sourceType":"kernelVersion"}],"dockerImageVersionId":30804,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"id":"a22a2354-a956-4986-96b8-40841562c01e","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":{}},{"id":"85a4844c-42f9-4f9f-a4c2-b804d8f7896c","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":{}},{"id":"e5a2ea4a-b8ae-4b7a-a040-b80ba7640d4e","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":{}},{"id":"786edc9a-fdcd-4c02-83f0-0e7dc02fdfb6","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":"2024-12-12T12:03:05.461164Z","iopub.execute_input":"2024-12-12T12:03:05.461882Z","iopub.status.idle":"2024-12-12T12:03:05.468344Z","shell.execute_reply.started":"2024-12-12T12:03:05.461849Z","shell.execute_reply":"2024-12-12T12:03:05.467440Z"}},"outputs":[],"execution_count":null},{"id":"6c076b03-baff-4511-9cb3-d3dd8723a162","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":{}},{"id":"977683ce-66cb-4553-873c-e66538c5f03f","cell_type":"code","source":"train= pd.read_csv('../input/aptos2019-blindness-detection/train.csv')\ntest= pd.read_csv('../input/aptos2019-blindness-detection/test.csv')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-09T08:51:43.714116Z","iopub.execute_input":"2024-12-09T08:51:43.714623Z","iopub.status.idle":"2024-12-09T08:51:43.744858Z","shell.execute_reply.started":"2024-12-09T08:51:43.714592Z","shell.execute_reply":"2024-12-09T08:51:43.744244Z"}},"outputs":[],"execution_count":null},{"id":"bb92a1ec-41d3-4127-bd5e-fd71c5afc091","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":"2024-12-09T08:51:44.865418Z","iopub.execute_input":"2024-12-09T08:51:44.865765Z","iopub.status.idle":"2024-12-09T08:51:44.880741Z","shell.execute_reply.started":"2024-12-09T08:51:44.865736Z","shell.execute_reply":"2024-12-09T08:51:44.879963Z"}},"outputs":[],"execution_count":null},{"id":"aa91f950-44c5-42fc-9adc-9b142b6c9393","cell_type":"code","source":"f, ax = plt.subplots(figsize=(14, 8.7))\nax = sns.countplot(x=\"diagnosis\", data=train, palette=\"GnBu_d\")\nsns.despine()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-09T06:44:58.114814Z","iopub.execute_input":"2024-12-09T06:44:58.115367Z","iopub.status.idle":"2024-12-09T06:44:58.311055Z","shell.execute_reply.started":"2024-12-09T06:44:58.115334Z","shell.execute_reply":"2024-12-09T06:44:58.310155Z"}},"outputs":[],"execution_count":null},{"id":"074b2b73-7c9f-478c-b60b-0728b3edfc82","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['id_code'][:15]:  # Assuming 'train' contains the dataset\n    img = cv2.imread(f\"../input/aptos2019-blindness-detection/train_images/{img_name}.png\")[..., [2, 1, 0]]  # Reading the image\n    \n    # Getting the label (class) for the image\n    label = train[train['id_code'] == img_name]['diagnosis'].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":"2024-12-09T06:45:01.388472Z","iopub.execute_input":"2024-12-09T06:45:01.389271Z","iopub.status.idle":"2024-12-09T06:45:13.199677Z","shell.execute_reply.started":"2024-12-09T06:45:01.389228Z","shell.execute_reply":"2024-12-09T06:45:13.198395Z"}},"outputs":[],"execution_count":null},{"id":"f4a060f8-f194-411d-bdc4-a26ef9fcb4c1","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":{}},{"id":"5acd36d0-65bf-4027-a2e2-604dc8728061","cell_type":"code","source":"DATA_DIR = \"../input/aptos2019-blindness-detection/\"\nTRAIN_DIR = \"../input/aptos2019-blindness-detection/train_images\"\nCSV_PATH = \"../input/aptos2019-blindness-detection/train.csv\"\nMODEL_PATH = \"./kaggle/working/\"\nLEARNING_RATE = 1e-4\nTRAIN_BATCH_SIZE = 32\nVALID_BATCH_SIZE = 32\nIMG_WIDTH= 256\nIMG_HEIGHT= 256\nTRAIN_SPLIT = 0.8\nNUM_WORKERS = 2\nUSE_AMP = True\nEPOCHS=10","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-12T12:00:28.217164Z","iopub.execute_input":"2024-12-12T12:00:28.217830Z","iopub.status.idle":"2024-12-12T12:00:28.222595Z","shell.execute_reply.started":"2024-12-12T12:00:28.217796Z","shell.execute_reply":"2024-12-12T12:00:28.221672Z"}},"outputs":[],"execution_count":null},{"id":"9e63acce-dbc2-4913-a165-ad50b3a82260","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":"2024-12-12T12:00:28.861962Z","iopub.execute_input":"2024-12-12T12:00:28.862334Z","iopub.status.idle":"2024-12-12T12:00:28.868405Z","shell.execute_reply.started":"2024-12-12T12:00:28.862306Z","shell.execute_reply":"2024-12-12T12:00:28.867528Z"}},"outputs":[],"execution_count":null},{"id":"efc15bff-e2ee-43d0-953d-9a546e0c8c93","cell_type":"code","source":"train_trasforms_DeiT_base_patch16= T.Compose([\n    T.ConvertImageDtype(torch.float32),\n    T.Resize((IMG_WIDTH, IMG_HEIGHT)),\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":"2024-12-12T12:00:29.893802Z","iopub.execute_input":"2024-12-12T12:00:29.894162Z","iopub.status.idle":"2024-12-12T12:00:29.909445Z","shell.execute_reply.started":"2024-12-12T12:00:29.894131Z","shell.execute_reply":"2024-12-12T12:00:29.908416Z"}},"outputs":[],"execution_count":null},{"id":"95d455c6-8aa2-49c9-8ee2-c0bf7e795ae2","cell_type":"markdown","source":"### Helper Functions and Utilities for Training and Evaluation","metadata":{}},{"id":"80fafa8c-9ce4-4816-9232-3f90f4f19b78","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":"2024-12-12T12:00:31.915319Z","iopub.execute_input":"2024-12-12T12:00:31.915680Z","iopub.status.idle":"2024-12-12T12:00:31.926261Z","shell.execute_reply.started":"2024-12-12T12:00:31.915650Z","shell.execute_reply":"2024-12-12T12:00:31.925262Z"}},"outputs":[],"execution_count":null},{"id":"d53c1a23-7c0b-44b3-9d27-4b8761f6dfde","cell_type":"code","source":"print(torch.cuda.is_available())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-12T12:00:32.622964Z","iopub.execute_input":"2024-12-12T12:00:32.623339Z","iopub.status.idle":"2024-12-12T12:00:32.627922Z","shell.execute_reply.started":"2024-12-12T12:00:32.623310Z","shell.execute_reply":"2024-12-12T12:00:32.627053Z"}},"outputs":[],"execution_count":null},{"id":"e5fdd3b9-ec2c-4402-90f4-ce38d762a638","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":{}},{"id":"cd5d1ec1-8754-41b0-a9c6-bbf149a95170","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":{}},{"id":"59bb7824-9780-44a1-ac6b-186b5ff29817","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":"2024-12-09T08:52:01.050655Z","iopub.execute_input":"2024-12-09T08:52:01.051032Z","iopub.status.idle":"2024-12-09T08:52:01.062580Z","shell.execute_reply.started":"2024-12-09T08:52:01.050999Z","shell.execute_reply":"2024-12-09T08:52:01.061694Z"}},"outputs":[],"execution_count":null},{"id":"f03c375a-1b8c-44bf-9d92-c2604466e708","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":"2024-12-09T08:52:02.018294Z","iopub.execute_input":"2024-12-09T08:52:02.018876Z","iopub.status.idle":"2024-12-09T08:52:02.028331Z","shell.execute_reply.started":"2024-12-09T08:52:02.018844Z","shell.execute_reply":"2024-12-09T08:52:02.027488Z"}},"outputs":[],"execution_count":null},{"id":"387296ce-e9ca-4108-9bb9-ab643b27979e","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":{}},{"id":"d9689408-5757-4d91-b775-3a95fcd01de1","cell_type":"code","source":"\nMODEL_NAME = \"swinv2_small_window16_256\"\nMODEL_SAVE=  \"/kaggle/working/fastvit_s12.Csv\"\nseed_everything(42)\nset_debug_apis(False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-12T12:00:38.050629Z","iopub.execute_input":"2024-12-12T12:00:38.050955Z","iopub.status.idle":"2024-12-12T12:00:38.056309Z","shell.execute_reply.started":"2024-12-12T12:00:38.050930Z","shell.execute_reply":"2024-12-12T12:00:38.055415Z"}},"outputs":[],"execution_count":null},{"id":"81fe6d56-6b9d-48f3-8f9e-cf0b4018b97b","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":"2024-12-12T12:00:38.472314Z","iopub.execute_input":"2024-12-12T12:00:38.472652Z","iopub.status.idle":"2024-12-12T12:00:39.558195Z","shell.execute_reply.started":"2024-12-12T12:00:38.472622Z","shell.execute_reply":"2024-12-12T12:00:39.557245Z"}},"outputs":[],"execution_count":null},{"id":"dd10e0bd-647e-41c4-b08d-11db919f8b7d","cell_type":"code","source":"# Initialize lists to store metrics\ntrain_loss = []\ntrain_top1_acc = []\nval_loss = []\nval_top1_acc = []\n\n# Record start time\nstart_time = time.time()\n\nfor epoch in tqdm(range(EPOCHS)):\n    train_metrics = train_step(model, train_loader, criterion, device, optimizer, scaler=scaler)\n    train_loss.append(train_metrics[\"loss\"])\n    print(f\"Training loss = {train_metrics['loss']}\")\n    train_top1_acc.append(train_metrics[\"top1\"])\n\n    val_metrics = val_step(model, val_loader, criterion, device)\n    val_loss.append(val_metrics[\"loss\"])\n    print(f\"Validation loss = {val_metrics['loss']}\")\n    val_top1_acc.append(val_metrics[\"top1\"])\n    \n    # Save model checkpoint\n    checkpoint_path = f\"{MODEL_NAME}_{epoch}.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\"Total 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_top1_acc\": train_top1_acc,\n    \"val_loss\": val_loss,\n    \"val_top1_acc\": val_top1_acc,\n})\n\n# Save the DataFrame to CSV\nmetrics_df.to_csv(MODEL_SAVE, index=False)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-09T08:52:29.356129Z","iopub.execute_input":"2024-12-09T08:52:29.356469Z","iopub.status.idle":"2024-12-09T10:02:13.689721Z","shell.execute_reply.started":"2024-12-09T08:52:29.356437Z","shell.execute_reply":"2024-12-09T10:02:13.688662Z"}},"outputs":[],"execution_count":null},{"id":"cdd6e8de-e714-4b5a-95ae-51f125ac29fb","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":{}},{"id":"9a904b98-ccbc-46c9-aadd-1bff0b9fdcbe","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":"2024-12-11T22:52:33.326476Z","iopub.execute_input":"2024-12-11T22:52:33.326847Z","iopub.status.idle":"2024-12-11T22:52:35.275187Z","shell.execute_reply.started":"2024-12-11T22:52:33.326818Z","shell.execute_reply":"2024-12-11T22:52:35.273980Z"}},"outputs":[],"execution_count":null},{"id":"84d71d63-9781-4c4d-b105-2487abea3584","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":"2024-12-12T12:00:48.291432Z","iopub.execute_input":"2024-12-12T12:00:48.292074Z","iopub.status.idle":"2024-12-12T12:00:48.296259Z","shell.execute_reply.started":"2024-12-12T12:00:48.292040Z","shell.execute_reply":"2024-12-12T12:00:48.295463Z"}},"outputs":[],"execution_count":null},{"id":"3af0d9cc-526a-45ab-a64b-d4494b9e3f14","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":"2024-12-12T12:00:49.277262Z","iopub.execute_input":"2024-12-12T12:00:49.277690Z","iopub.status.idle":"2024-12-12T12:00:49.283479Z","shell.execute_reply.started":"2024-12-12T12:00:49.277640Z","shell.execute_reply":"2024-12-12T12:00:49.282441Z"}},"outputs":[],"execution_count":null},{"id":"a38c4711-b8d1-4a7c-b1f6-df69b049be6a","cell_type":"code","source":"# Define paths and device\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\")\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)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-12T12:00:50.311927Z","iopub.execute_input":"2024-12-12T12:00:50.312311Z","iopub.status.idle":"2024-12-12T12:01:56.979097Z","shell.execute_reply.started":"2024-12-12T12:00:50.312280Z","shell.execute_reply":"2024-12-12T12:01:56.978092Z"}},"outputs":[],"execution_count":null},{"id":"9f70f2fd-d000-4262-957f-994d758ec5fd","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":"2024-12-12T12:03:16.263051Z","iopub.execute_input":"2024-12-12T12:03:16.263373Z","iopub.status.idle":"2024-12-12T12:03:16.279419Z","shell.execute_reply.started":"2024-12-12T12:03:16.263347Z","shell.execute_reply":"2024-12-12T12:03:16.278393Z"}},"outputs":[],"execution_count":null},{"id":"f13649e9-bd06-4ac2-91b7-d191be136a25","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":"2024-12-12T12:17:05.309626Z","iopub.execute_input":"2024-12-12T12:17:05.310433Z","iopub.status.idle":"2024-12-12T12:17:05.721048Z","shell.execute_reply.started":"2024-12-12T12:17:05.310399Z","shell.execute_reply":"2024-12-12T12:17:05.720168Z"}},"outputs":[],"execution_count":null},{"id":"0430539e-18b3-4367-8fcc-36ef39d4b587","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":"2024-12-12T12:06:45.657117Z","iopub.execute_input":"2024-12-12T12:06:45.657826Z","iopub.status.idle":"2024-12-12T12:06:45.664307Z","shell.execute_reply.started":"2024-12-12T12:06:45.657794Z","shell.execute_reply":"2024-12-12T12:06:45.663221Z"}},"outputs":[],"execution_count":null},{"id":"9964b85c-b580-436f-a4a7-e3e3c94b89f7","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":"2024-12-12T12:06:46.501258Z","iopub.execute_input":"2024-12-12T12:06:46.501909Z","iopub.status.idle":"2024-12-12T12:06:46.507237Z","shell.execute_reply.started":"2024-12-12T12:06:46.501852Z","shell.execute_reply":"2024-12-12T12:06:46.506362Z"}},"outputs":[],"execution_count":null},{"id":"04bc1825-0a07-4d46-887d-2437af774f96","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":"2024-12-12T12:09:31.670899Z","iopub.execute_input":"2024-12-12T12:09:31.671280Z","iopub.status.idle":"2024-12-12T12:09:31.853268Z","shell.execute_reply.started":"2024-12-12T12:09:31.671251Z","shell.execute_reply":"2024-12-12T12:09:31.852409Z"}},"outputs":[],"execution_count":null},{"id":"c6c4ae87-26f0-4f16-9e57-140e5c1d6cee","cell_type":"markdown","source":"# End","metadata":{}}]}