{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":65542,"databundleVersionId":7217587,"sourceType":"competition"}],"dockerImageVersionId":30918,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch\nfrom torchvision import transforms, datasets\nfrom torch.utils.data import DataLoader, Subset\nimport numpy as np\nimport cv2\nfrom PIL import Image\n\n# Define a custom CLAHE transform to enhance contrast (domain-specific)\nclass CLAHETransform(object):\n    def __init__(self, clip_limit=2.0, tile_grid_size=(8,8)):\n        self.clip_limit = clip_limit\n        self.tile_grid_size = tile_grid_size\n\n    def __call__(self, img):\n        # Convert the PIL image to a numpy array\n        img_np = np.array(img)\n        # If image is grayscale (2D array), return original image\n        if len(img_np.shape) == 2:\n            return img\n        # Convert from RGB to LAB color space\n        lab = cv2.cvtColor(img_np, cv2.COLOR_RGB2LAB)\n        l, a, b = cv2.split(lab)\n        # Apply CLAHE to the L-channel\n        clahe = cv2.createCLAHE(clipLimit=self.clip_limit, tileGridSize=self.tile_grid_size)\n        cl = clahe.apply(l)\n        # Merge the CLAHE enhanced L-channel back with A and B channels\n        lab = cv2.merge((cl, a, b))\n        # Convert back to RGB color space\n        img_clahe = cv2.cvtColor(lab, cv2.COLOR_LAB2RGB)\n        return Image.fromarray(img_clahe)\n\n# Define training transformations with enhanced data augmentation\ntrain_transform = transforms.Compose([\n    CLAHETransform(clip_limit=2.0, tile_grid_size=(8,8)),  # Enhance contrast via CLAHE\n    transforms.RandomRotation(degrees=10),                 # Small rotations\n    transforms.RandomResizedCrop((224,224), scale=(0.8, 1.0)), # Slight zoom variation\n    transforms.RandomAffine(degrees=10, translate=(0.1, 0.1)), # Random translations & rotations\n    transforms.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.1, hue=0.05),  # Increased brightness/contrast jitter\n    transforms.RandomHorizontalFlip(p=0.5),                # Horizontal flipping if acceptable\n    transforms.ToTensor(),\n    transforms.Normalize(mean=[0.485, 0.456, 0.406],\n                         std=[0.229, 0.224, 0.225]),\n])\n\n# Define validation transformations without augmentation\nval_transform = transforms.Compose([\n    transforms.Resize((224,224)),         # Resize directly to final size\n    transforms.ToTensor(),\n    transforms.Normalize(mean=[0.485, 0.456, 0.406],\n                         std=[0.229, 0.224, 0.225]),\n])\n\n# Path to the dataset\ndataset_path = '/kaggle/input/congenital-heart-disease'\n\n# Create a full dataset to obtain class names and indices (without transform)\nfull_dataset = datasets.ImageFolder(dataset_path)\nprint(\"Classes:\", full_dataset.classes)\n\n# Get the total number of samples and create a list of indices\nnum_samples = len(full_dataset)\nindices = list(range(num_samples))\nnp.random.shuffle(indices)\n\n# Define the split size (80% training, 20% validation)\nsplit = int(0.8 * num_samples)\ntrain_indices = indices[:split]\nval_indices = indices[split:]\n\n# Create training and validation datasets with separate transforms using Subset\ntrain_dataset = Subset(datasets.ImageFolder(dataset_path, transform=train_transform), train_indices)\nval_dataset = Subset(datasets.ImageFolder(dataset_path, transform=val_transform), val_indices)\n\n# Create DataLoaders for training and validation\ntrain_loader = DataLoader(train_dataset, batch_size=32, shuffle=True, num_workers=2)\nval_loader = DataLoader(val_dataset, batch_size=32, shuffle=False, num_workers=2)\n\n# Check one batch from the training loader\nimages, labels = next(iter(train_loader))\nprint(\"Batch image shape:\", images.shape)\nprint(\"Batch labels:\", labels)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-11T21:03:59.846649Z","iopub.execute_input":"2025-03-11T21:03:59.847036Z","iopub.status.idle":"2025-03-11T21:04:07.135599Z","shell.execute_reply.started":"2025-03-11T21:03:59.847005Z","shell.execute_reply":"2025-03-11T21:04:07.134625Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import timm\nimport torch\nimport torch.nn as nn\n\n# Define the number of classes based on your dataset\nnum_classes = 4\n\n# Load the pre-trained ViT model from timm\nmodel = timm.create_model('vit_base_patch16_224', pretrained=True)\n\n# Replace the final classifier head with one that has the correct number of output classes\nmodel.head = nn.Linear(model.head.in_features, num_classes)\n\nprint(model)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nmodel = model.to(device)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-11T21:04:36.133267Z","iopub.execute_input":"2025-03-11T21:04:36.133639Z","iopub.status.idle":"2025-03-11T21:04:36.224492Z","shell.execute_reply.started":"2025-03-11T21:04:36.133609Z","shell.execute_reply":"2025-03-11T21:04:36.223572Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import math\nfrom tqdm.notebook import tqdm  # for progress bars in notebooks\nimport torch.optim as optim\n\n# Define the loss function and optimizer\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.Adam(model.parameters(), lr=1e-4)\n\nnum_epochs = 100       # Total number of epochs\nwarmup_epochs = 5     # Number of epochs for warm-up\n\n# Define a lambda function for the learning rate schedule:\n# For the first `warmup_epochs`, linearly increase the LR.\n# Then, apply cosine annealing from epoch `warmup_epochs` to `num_epochs`.\ndef lr_lambda(current_epoch):\n    if current_epoch < warmup_epochs:\n        # Linear warm-up\n        return float(current_epoch + 1) / warmup_epochs\n    else:\n        # Cosine annealing\n        return 0.5 * (1 + math.cos(math.pi * (current_epoch - warmup_epochs) / (num_epochs - warmup_epochs)))\n\nscheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lr_lambda)\n\nfor epoch in range(num_epochs):\n    model.train()  # Set model to training mode\n    running_loss = 0.0\n\n    # Create a tqdm progress bar for the training loop\n    pbar = tqdm(train_loader, desc=f\"Epoch {epoch+1}/{num_epochs}\")\n    for images, labels in pbar:\n        images, labels = images.to(device), labels.to(device)\n        \n        optimizer.zero_grad()          # Zero the parameter gradients\n        outputs = model(images)        # Forward pass\n        loss = criterion(outputs, labels)  # Compute loss\n        loss.backward()                # Backpropagation\n        optimizer.step()               # Update weights\n        \n        running_loss += loss.item() * images.size(0)\n        pbar.set_postfix({'loss': loss.item()})\n    \n    # Step the scheduler at the end of the epoch\n    scheduler.step()\n    \n    epoch_loss = running_loss / len(train_dataset)\n    \n    # Validation step\n    model.eval()  # Set model to evaluation mode\n    correct = 0\n    total = 0\n    with torch.no_grad():\n        for images, labels in val_loader:\n            images, labels = images.to(device), labels.to(device)\n            outputs = model(images)\n            _, predicted = torch.max(outputs, 1)\n            total += labels.size(0)\n            correct += (predicted == labels).sum().item()\n    \n    accuracy = 100 * correct / total\n    print(f\"Epoch [{epoch+1}/{num_epochs}], Loss: {epoch_loss:.4f}, Validation Accuracy: {accuracy:.2f}%\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-11T21:05:06.097161Z","iopub.execute_input":"2025-03-11T21:05:06.097529Z","iopub.status.idle":"2025-03-11T22:04:43.740094Z","shell.execute_reply.started":"2025-03-11T21:05:06.097498Z","shell.execute_reply":"2025-03-11T22:04:43.738935Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.metrics import accuracy_score, confusion_matrix, precision_score, recall_score, f1_score\n\n# Switch to evaluation mode\nmodel.eval()\n\nall_preds = []\nall_labels = []\n\n# Loop over the validation set\nwith torch.no_grad():\n    for images, labels in val_loader:\n        images, labels = images.to(device), labels.to(device)\n        outputs = model(images)\n        _, preds = torch.max(outputs, 1)\n        all_preds.extend(preds.cpu().numpy())\n        all_labels.extend(labels.cpu().numpy())\n\n# Convert lists to arrays for metric computation\ny_true = all_labels\ny_pred = all_preds\n\n# Compute metrics\naccuracy = accuracy_score(y_true, y_pred)\ncm = confusion_matrix(y_true, y_pred)\nprecision = precision_score(y_true, y_pred, average='macro')\nrecall = recall_score(y_true, y_pred, average='macro')\nf1 = f1_score(y_true, y_pred, average='macro')\n\nprint(\"Accuracy:\", accuracy)\nprint(\"Confusion Matrix:\\n\", cm)\nprint(\"Precision:\", precision)\nprint(\"Recall:\", recall)\nprint(\"F1 Score:\", f1)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-11T22:12:35.697532Z","iopub.execute_input":"2025-03-11T22:12:35.697930Z","iopub.status.idle":"2025-03-11T22:12:38.681866Z","shell.execute_reply.started":"2025-03-11T22:12:35.697895Z","shell.execute_reply":"2025-03-11T22:12:38.680859Z"}},"outputs":[],"execution_count":null}]}