{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"tpu1vmV38","dataSources":[{"sourceId":52254,"databundleVersionId":6863140,"sourceType":"competition"},{"sourceId":6523471,"sourceType":"datasetVersion","datasetId":3771357},{"sourceId":6524344,"sourceType":"datasetVersion","datasetId":3771912},{"sourceId":7015603,"sourceType":"datasetVersion","datasetId":4033648},{"sourceId":7140484,"sourceType":"datasetVersion","datasetId":4121195},{"sourceId":7140790,"sourceType":"datasetVersion","datasetId":4121410}],"dockerImageVersionId":30587,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"!pip install nibabel","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-01-04T17:29:45.541404Z","iopub.execute_input":"2024-01-04T17:29:45.541751Z","iopub.status.idle":"2024-01-04T17:29:48.808603Z","shell.execute_reply.started":"2024-01-04T17:29:45.541722Z","shell.execute_reply":"2024-01-04T17:29:48.807483Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\nimport torch.nn as nn\nimport torch_xla.core.xla_model as xm\nimport torch_xla.distributed.parallel_loader as pl\nimport torch_xla.distributed.xla_multiprocessing as xmp\n\nimport torch\nimport torch.nn.functional as F\nimport torch_xla.core.xla_model as xm\nfrom torch.nn import Transformer\n\ndef xla_linear(input, weight, bias=None):\n    if isinstance(input, torch.Tensor) and input.device.type == 'xla':\n#         print(\"input\", input.shape)\n#         print(\"************************************************************************\")\n#         print(\"weight\", weight)\n#         print(\"$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\")\n#         print(\"bias\", bias)\n#         return torch.nn.functional.linear(input, weight, bias)\n        return torch.matmul(input.to(xm.xla_device()), weight.to(xm.xla_device()).t()) + bias.to(xm.xla_device())\n    else:\n        input_xla = input.to(xm.xla_device())\n        weight_xla = weight.to(xm.xla_device())\n        if bias is not None:\n            bias_xla = bias.to(xm.xla_device())\n        else:\n            bias_xla = None\n#         return torch.nn.functional.linear(input_xla, weight_xla, bias_xla)\n        return torch.matmul(input_xla, weight_xla.t()) + bias_xla\n    \n# Override the torch.nn.functional.linear function with the XLA version\n# F.linear = xla_linear\n\ndef xla_layer_norm(input, normalized_shape, weight=None, bias=None, eps=1e-5):\n    if input.device.type == 'xla':\n        # Calculate the mean and variance along the last dimension\n        mean = input.mean(dim=-1, keepdim=True)\n        var = input.var(dim=-1, unbiased=False, keepdim=True)\n        \n        # Reshape weight and bias to match the shape of input\n        if weight is not None:\n            weight = weight.view(*input.shape[-len(normalized_shape):])\n        if bias is not None:\n            bias = bias.view(*input.shape[-len(normalized_shape):])\n        \n        # Normalize the input\n        input = (input - mean) / torch.sqrt(var + eps)\n        \n        # Apply weight and bias\n        if weight is not None:\n            input = input * weight\n        if bias is not None:\n            input = input + bias\n        print(input.shape)\n        return input\n    else:\n        # Fall back to PyTorch's layer normalization\n        return F.layer_norm(input, normalized_shape, weight, bias, eps)\n\n# Override the torch.nn.functional.layer_norm function with the XLA version\n# F.layer_norm = xla_layer_norm\n\ninput_shape = (128, 128, 128)  # Depth x Height x Width\nnum_classes = 14  # Number of classes for classification\n\nclass Transformer3DClassifier(nn.Module):\n    def __init__(self, input_shape, num_classes, num_layers=6, d_model=16, nhead=8, dim_feedforward=2048, dropout=0.1):\n        super(Transformer3DClassifier, self).__init__()\n        \n        # Initialize d_model\n        self.d_model = d_model\n        \n        # Calculate the input size for the transformer\n        d_in = input_shape[0] * input_shape[1] * input_shape[2]  # Depth x Height x Width\n        self.embedding = nn.Linear(d_in, d_model)\n        \n        self.transformer = Transformer(\n            d_model=d_model,\n            nhead=nhead,\n            num_encoder_layers=num_layers,\n            dim_feedforward=dim_feedforward,\n            dropout=dropout\n        )\n        \n        self.fc = nn.Linear(d_model, num_classes)\n   \n\n    def forward(self, x):\n        # Flatten the input and apply linear embedding\n        x = x.view(x.size(0), -1)\n        print(\"Before embedding x.shape is \", x.shape)\n        x = self.embedding(x)\n        print(\"After embedding x.shape is \", x.shape)\n        \n        # Reshape to add a third dimension (seq_len)\n        x = x.unsqueeze(0)\n        print(\"x shape after unsqueeze\", x.shape)\n        # Create a dummy target tensor (you can adjust its size if needed)\n        tgt = torch.zeros(1, x.size(1), self.d_model).to(x.device)\n        print(\"tgt shape\", tgt.shape)\n        \n        # Transformer encoder\n        output = self.transformer(x, tgt)\n        print(\"Output shape after transformer\", output.shape)\n\n        # Remove the added dimension\n#         output = output.squeeze(0)\n#         print(\"Output shape after squeeze\", output.shape)\n        \n#         # Global average pooling\n#         output = output.mean(dim=1)\n#         print(\"Output shape after global average pooling\", output.shape)\n\n        # Classification layer\n        logits = self.fc(output)\n        \n        # Add batch dimension to logits\n        logits = logits.unsqueeze(0)\n        \n        \n        return logits\n\n# Define XLA tensors for input and hidden layer sizes\n# input_size = torch.tensor(32, device=xm.xla_device())\ninput_size = 32 # Adjust the dimensions as needed\nhidden_size = 16  # Adjust the dimensions as needed\n# hidden_size = torch.tensor(16, device=xm.xla_device())\n\nclass Custom3DViTModelTPU(nn.Module):\n    def __init__(self, in_channels, num_classes, num_classes_segmentation, batch_size):\n        super(Custom3DViTModelTPU, self).__init__()\n        self.batch_size = batch_size\n        self.num_classes = num_classes\n        \n#         self.vit_backbone = VisionTransformer3DBackboneTPU(\n#             in_channels=in_channels,\n#             embedding_dim=32,  # Adjust the embedding dimension as needed\n#             num_heads=2,       # Number of attention heads\n#             num_layers=2       # Number of transformer layers\n#         )\n        \n        self.vit_backbone = Transformer3DClassifier(\n            input_shape,\n            num_classes\n        )\n\n        self.classification_head = nn.Sequential(\n#             nn.Linear(batch_size, 16),\n#             nn.ReLU(inplace=True),\n#             nn.Linear(16, num_classes),\n#             nn.Sigmoid()\n            nn.Linear(self.vit_backbone.d_model, num_classes)\n        )\n\n        self.segmentation_head = nn.Sequential(\n            nn.Conv3d(1, num_classes_segmentation, kernel_size=1),\n            nn.Sigmoid()\n        )\n#     def print_weights(self):\n#         for name, param in self.named_parameters():\n#             print(f\"Layer: {name}, Size: {param.size()}\")\n#             print(param)\n\n    def forward(self, x, segmentation_mask):\n        print(\"x shape and segmentation_mask shape\", x.shape, segmentation_mask.shape)\n        \n        # Move input tensors to XLA devices\n        x = x.to(xm.xla_device())\n        segmentation_mask = segmentation_mask.to(xm.xla_device())\n\n        features = self.vit_backbone(x)\n        features = features.to(xm.xla_device())\n        print(\"features shape\", features.shape)\n        \n        #classification_output = self.classification_head(features)\n        # Reshape it to (32, 10)\n        classification_output = features.view(self.batch_size, self.num_classes)\n        \n        print(\"classification_output\", classification_output.shape)\n        segmentation_output = self.segmentation_head(x)\n        print(\"segmentation output\", segmentation_output.shape)\n\n#         # Resize segmentation_output to match the shape of segmentation_mask\n        segmentation_output = nn.functional.interpolate(segmentation_output, size=segmentation_mask.shape[2:], mode='trilinear')\n\n        segmentation_output = segmentation_output * segmentation_mask\n\n        return classification_output, segmentation_output\n\nbatch_size = 32\n\n# Move the entire model to XLA devices\ndef get_model():\n    return Custom3DViTModelTPU(3, 14, 5, batch_size)\n\n# Modify the run function to accept the process index\ndef run(index):\n    print(\"^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\")\n#     l_in = torch.randn(10, device=xm.xla_device())\n#     linear = torch.nn.Linear(10, 20).to(xm.xla_device())\n#     l_out = linear(l_in)\n#     print(l_out)\n    \n    model = get_model()\n#     model.print_weights()\n    model = model.to(xm.xla_device())\n    print(\">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\")\n    # Create sample input tensors (modify this according to your data)\n    batch_images = torch.randn(32, 1, 128, 128, 128)  # Example input shape\n    batch_segmentation_masks = torch.randn(32, 1, 128, 128, 128)  # Example mask shape\n\n    batch_images = batch_images.to(xm.xla_device())  # Move input tensors to XLA device\n    batch_segmentation_masks = batch_segmentation_masks.to(xm.xla_device())\n    print(\"*****************************************************************************\")\n\n    # Forward pass\n    classification_outputs, segmentation_outputs = model(batch_images, batch_segmentation_masks)\n    \n# # Use XLA multiprocessing to distribute across TPUs\nif __name__ == '__main__':\n     xmp.spawn(run, nprocs=1, start_method='fork')\n","metadata":{"execution":{"iopub.status.busy":"2024-01-04T17:29:48.810645Z","iopub.execute_input":"2024-01-04T17:29:48.810924Z","iopub.status.idle":"2024-01-04T17:29:55.600879Z","shell.execute_reply.started":"2024-01-04T17:29:48.810895Z","shell.execute_reply":"2024-01-04T17:29:55.600061Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport pandas as pd\nimport numpy as np\nimport nibabel as nib\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch_xla.core.xla_model as xm\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms\nfrom sklearn.metrics import accuracy_score, precision_recall_fscore_support, roc_auc_score\nfrom sklearn.model_selection import train_test_split\nfrom torchvision import models\nfrom scipy.ndimage import zoom\nimport torch.nn.functional as F\nfrom PIL import Image\n\n# Create a function to move data to the XLA device\ndef move_data_to_xla(data):\n    return data.to(torch.float32).to(device)\n\nclass CustomDataset(Dataset):\n    def __init__(self, image_paths, mask_paths, labels, transform=None):\n        self.image_paths = image_paths\n        self.mask_paths = mask_paths\n        self.labels = labels\n        self.transform = transform\n\n    def __len__(self):\n        return len(self.image_paths)\n\n    def __getitem__(self, idx):\n        image_path = self.image_paths[idx]\n        mask_path = self.mask_paths[idx]\n\n        # Load the 3D NIfTI image using nibabel\n        image = nib.load(image_path).get_fdata()\n#         print(image.shape)\n#         print(\"Data shape *********:\", image.dtype)\n\n        # Load the segmentation mask if available\n        segmentation_mask = None\n        if pd.notna(mask_path):\n            segmentation_mask = nib.load(mask_path)\n            segmentation_mask_data = segmentation_mask.get_fdata()\n            resized_data = resize_nifti(segmentation_mask_data, desired_shape)\n            segmentation_mask_data_affine = segmentation_mask.affine\n            resized_affine = segmentation_mask_data_affine\n            segmentation_mask = nib.Nifti1Image(resized_data, affine=resized_affine).get_fdata()\n\n        # Apply transformations if provided to the image\n        if self.transform:\n            image = self.transform(image)\n\n        # Apply transformations if provided to the segmentation mask\n        if segmentation_mask is not None and self.transform:\n            segmentation_mask = self.transform(segmentation_mask)\n        else:\n            segmentation_mask = torch.zeros_like(image)\n\n        label = torch.tensor(self.labels[idx], dtype=torch.float32)\n        \n        return image, segmentation_mask, label\n\nimport torch\nimport torch.nn as nn\nimport torchvision.models as models\n\n# Function to resize NIfTI data\ndef resize_nifti(nifti_data, target_shape):\n    factors = (target_shape[0] / nifti_data.shape[0],\n               target_shape[1] / nifti_data.shape[1],\n               target_shape[2] / nifti_data.shape[2])\n    resized_data = zoom(nifti_data, factors, order=3)  # Cubic interpolation (higher quality)\n    return resized_data\n\n# Paths and settings\nsegmentation_dir = '/kaggle/input/rsna-2023-abdominal-trauma-detection/segmentations'  # Update with the correct path\ncsv_file = '/kaggle/input/abdominal-trauma-nii-csv/abdominal_trauma_nii.csv'  # Update with the correct path\nbatch_size = 32\nnum_workers = 4  # Number of CPU cores to use for data loading\nnum_classes = 14  # Number of classes\nnum_classes_segmentation = 1  # Number of classes\ndesired_shape = (128, 128, 128)\n# device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\ndevice = xm.xla_device()\nprint(device)\n\n# Define transformations if needed\ntransform = transforms.Compose([\n    transforms.ToTensor(),  # Convert to tensor\n    # Add more transformations if necessary\n])\n\n# Load the CSV file\ndata = pd.read_csv(csv_file).head(4480)\n\n# Filter rows where the 'mask_path' column is not empty\n#data = data[pd.notna(data['mask_path'])]\n\n# Remove the extra space from the column name\ndata.columns = data.columns.str.strip()\n\n# Assuming 'data' is your DataFrame\ndata_length = len(data)\nprint(\"Length of DataFrame:\", data_length)\n# print(data)\n# print(data.index)\n\n# Split the data into training, validation, and test sets\ntrain_data, temp_data = train_test_split(data, test_size=0.2, random_state=42)\nval_data, test_data = train_test_split(temp_data, test_size=0.5, random_state=42)\n\n# Set the display option to show all rows\npd.set_option('display.max_rows', None)\n\nindex_values = train_data.index.values\n\n# chunk_size = 200  # You can adjust the chunk size\n# for i in range(0, len(index_values), chunk_size):\n#     print(index_values[i:i+chunk_size])\n\n# Reset the display option to its default value (if needed)\npd.reset_option('display.max_rows')\n\n# Extract file paths and labels from the data\ntrain_paths = train_data['file_path'].values\ntrain_mask_paths = train_data['mask_path'].values\ntrain_labels = train_data[['bowel_healthy','bowel_injury','extravasation_healthy','extravasation_injury','kidney_healthy','kidney_low','kidney_high','liver_healthy','liver_low','liver_high','spleen_healthy','spleen_low','spleen_high','any_injury']].values\n\nval_paths = val_data['file_path'].values\nval_mask_paths = val_data['mask_path'].values\nval_labels = val_data[['bowel_healthy','bowel_injury','extravasation_healthy','extravasation_injury','kidney_healthy','kidney_low','kidney_high','liver_healthy','liver_low','liver_high','spleen_healthy','spleen_low','spleen_high','any_injury']].values\n\ntest_paths = test_data['file_path'].values\ntest_mask_paths = test_data['mask_path'].values\ntest_labels = test_data[['bowel_healthy','bowel_injury','extravasation_healthy','extravasation_injury','kidney_healthy','kidney_low','kidney_high','liver_healthy','liver_low','liver_high','spleen_healthy','spleen_low','spleen_high','any_injury']].values\n\n# Instantiate the datasets\ntrain_dataset = CustomDataset(train_paths, train_mask_paths, train_labels, transform=transform)\nprint('len of train_dataset', len(train_dataset))\nval_dataset = CustomDataset(val_paths, val_mask_paths, val_labels, transform=transform)\ntest_dataset = CustomDataset(test_paths, test_mask_paths, test_labels, transform=transform)\n\n# Instantiate the data loaders\ntrain_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=num_workers, drop_last=True)\nprint('train_loader', len(train_loader))\n# train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=False, num_workers=num_workers)\nval_loader = DataLoader(val_dataset, batch_size=batch_size, shuffle=False, num_workers=num_workers)\ntest_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False, num_workers=num_workers)\nprint(train_loader)\n# print(\"Indices:\", train_loader.index)  # Print the indices\n        \n# Instantiate the model with the appropriate number of classes for both classification and segmentation\nin_channels = 1  # Input channels (e.g., for grayscale images or volumes)\nnum_classes_classification = 14  # Number of classes for classification\nnum_classes_segmentation = 1    # Number of classes for segmentation (change this according to your task)\nmodel = Custom3DViTModelTPU(in_channels, num_classes_classification, \n                            num_classes_segmentation, batch_size)\n# Count the number of parameters\ntotal_params = sum(p.numel() for p in model.parameters())\nprint(f\"Total Trainable Parameters: {total_params}\")\n#model = model.to(device)\n# model = get_model()\nmodel = model.to(xm.xla_device())\n# Define loss function and optimizer\ncriterion = nn.BCELoss()  # Binary Cross-Entropy loss\noptimizer = optim.Adam(model.parameters(), lr=0.001)\n\n# Training loop\nnum_epochs = 20\nepoch_count=0\nfor epoch in range(num_epochs):\n    model.train()\n    running_loss = 0.0\n    correct_train = 0\n    total_train = 0\n    \n    for batch_images, batch_segmentation_masks, batch_labels in train_loader:\n        optimizer.zero_grad()\n        xm.mark_step()\n        # Move data to the GPU if available\n        batch_images = batch_images.to(torch.float32).to(device)\n        batch_segmentation_masks = batch_segmentation_masks.to(torch.float32).to(device)\n        batch_labels = batch_labels.to(torch.float32).to(device)\n\n        # Assuming batch_images has shape (batch_size, num_frames, num_channels, height, width)\n        batch_images = batch_images.unsqueeze(1)  # Add a singleton dimension for channels\n        batch_segmentation_masks = batch_segmentation_masks.unsqueeze(1)\n        print(\"batch_images shape and batch_segmentation_masks shape\", \n              batch_images.shape, batch_segmentation_masks.shape)\n        print(\"batch number: \",epoch_count)\n        epoch_count=epoch_count+1\n        \n#         model = model.to(device)\n        # Move data to the XLA device\n        \n        batch_images = batch_images.to(torch.float32)  # Convert to float32 if not already\n        batch_segmentation_masks = batch_segmentation_masks.to(torch.float32)  # Convert to float32 if not already\n\n        batch_images = move_data_to_xla(batch_images)\n        batch_segmentation_masks = move_data_to_xla(batch_segmentation_masks)\n        batch_labels = move_data_to_xla(batch_labels)\n        \n        \n\n        # Forward pass\n        classification_outputs, segmentation_outputs = model(batch_images, batch_segmentation_masks)\n        print(\"..........................................................\")\n        \n        # Apply sigmoid activation to the classification outputs\n        classification_outputs = torch.sigmoid(classification_outputs)\n        \n        print(\"classification_outputs.shape, batch_labels shape\", \n              classification_outputs.shape, batch_labels.shape)\n        \n        \n        # Calculate binary cross-entropy loss for each class separately\n        losses = []\n        for class_index in range(num_classes_classification):\n            class_labels = batch_labels[:, class_index]  # Select labels for the current class\n            class_outputs = classification_outputs[:, class_index]  # Select model outputs for the current class\n            class_loss = criterion(class_outputs, class_labels)\n#             print(class_loss)\n            losses.append(class_loss)\n\n        # Calculate the total loss as the sum of individual class losses\n        print(sum(losses),\"sum of losses\")\n        total_loss = sum(losses)/num_classes_classification\n        print(\"total classification loss\",total_loss)\n\n        # Check if segmentation mask is available\n        if batch_segmentation_masks is not None:\n            # Ensure that both input and target tensors are of type torch.float32\n            batch_segmentation_masks = batch_segmentation_masks.to(torch.float32)\n            \n            # Apply sigmoid activation to segmentation_outputs\n            segmentation_outputs = torch.sigmoid(segmentation_outputs)\n            segmentation_outputs = segmentation_outputs.to(torch.float32)\n\n            # Calculate segmentation loss\n            segmentation_loss = criterion(segmentation_outputs, batch_segmentation_masks)\n            print(segmentation_loss)\n            total_loss += segmentation_loss\n            \n\n        running_loss += total_loss.item()\n        running_loss=running_loss/2\n        print(running_loss,\"running_loss\")\n        \n        # Calculate accuracy for each class separately\n        accuracies = []\n        for class_index in range(num_classes_classification):\n            class_labels = batch_labels[:, class_index]  # Select labels for the current class\n            class_outputs = classification_outputs[:, class_index]  # Select model outputs for the current class\n            \n            # Calculate binary predictions based on a threshold (e.g., 0.5)\n            predicted = (class_outputs > 0.5).float()\n            \n            class_accuracy = accuracy_score(class_labels.cpu(), predicted.cpu())\n            accuracies.append(class_accuracy)\n        \n        # Calculate overall accuracy\n        batch_accuracy = sum(accuracies) / num_classes_classification\n        correct_train += batch_accuracy\n        total_train += 1\n        print(\"batch accuracy: \",batch_accuracy)\n        print(\"batch loss: \",running_loss)\n        \n        # Backpropagation and optimization\n        total_loss.backward()\n        xm.mark_step()\n        optimizer.step()\n\n    # Calculate and print average training accuracy and loss\n    avg_train_accuracy = correct_train / len(train_loader)\n    avg_train_loss = running_loss / len(train_loader)\n    \n    print(f\"Epoch [{epoch+1}/{num_epochs}]\")\n    print(f\"Train Accuracy: {avg_train_accuracy:.4f} | Train Loss: {avg_train_loss:.4f}\")\n        # Validation loop\n    model.eval()\n    total_val_loss = 0.0\n    correct_val = 0\n    total_val = 0\n\n    with torch.no_grad():\n        for batch_images, batch_segmentation_masks, batch_labels in val_loader:\n            batch_images = batch_images.to(torch.float32).to(device)\n            batch_segmentation_masks = batch_segmentation_masks.to(torch.float32).to(device)\n            batch_labels = batch_labels.to(torch.float32).to(device)\n            \n            batch_images = batch_images.unsqueeze(1)  # Add a singleton dimension for channels\n            batch_segmentation_masks = batch_segmentation_masks.unsqueeze(1)\n            print(\"batch_images shape \", \n              batch_images.shape)\n            \n        \n            # Forward pass\n            classification_outputs, segmentation_outputs = model(batch_images, batch_segmentation_masks)\n            \n            # Apply sigmoid activation to the classification outputs\n            classification_outputs = torch.sigmoid(classification_outputs)\n\n            # Calculate binary cross-entropy loss for each class separately\n            losses = []\n            for class_index in range(num_classes_classification):\n                class_labels = batch_labels[:, class_index]\n                class_outputs = classification_outputs[:, class_index]\n                class_loss = criterion(class_outputs, class_labels)\n                losses.append(class_loss)\n\n            total_loss = sum(losses)/num_classes_classification\n\n            # Check if segmentation mask is available\n            if batch_segmentation_masks is not None:\n                batch_segmentation_masks = batch_segmentation_masks.to(torch.float64)\n                \n                # Apply sigmoid activation to segmentation_outputs\n                segmentation_outputs = torch.sigmoid(segmentation_outputs)\n                segmentation_outputs = segmentation_outputs.to(torch.float64)\n                \n                segmentation_loss = criterion(segmentation_outputs, batch_segmentation_masks)\n                total_loss = total_loss + segmentation_loss\n            \n            total_val_loss += total_loss.item()\n            total_val_loss=total_val_loss/2\n\n            # Calculate accuracy for each class separately\n            accuracies = []\n            for class_index in range(num_classes_classification):\n                class_labels = batch_labels[:, class_index]\n                class_outputs = classification_outputs[:, class_index]\n                \n                # Calculate binary predictions based on a threshold (e.g., 0.5)\n                predicted = (class_outputs > 0.5).float()\n\n                class_accuracy = accuracy_score(class_labels.cpu(), predicted.cpu())\n                accuracies.append(class_accuracy)\n            \n            batch_accuracy = sum(accuracies) / num_classes_classification\n            correct_val += batch_accuracy\n            total_val += batch_labels.size(0)\n\n    val_accuracy = correct_val / len(val_loader)\n    avg_val_loss = total_val_loss / len(val_loader)\n\n    print(f\"Validation Accuracy: {val_accuracy:.4f} | Validation Loss: {avg_val_loss:.4f}\")\ntorch.save(model, 'vit_abdominal.pth')\n# Test loop\nmodel.eval()\ntotal_correct = 0\ntotal_samples = 0\n# Initialize lists to store per-class metrics\nprecision_list = []\nrecall_list = []\nf1_list = []\n\nwith torch.no_grad():\n    for batch_images, batch_segmentation_masks, batch_labels in test_loader:\n        batch_images = batch_images.to(torch.float32).to(device)\n        batch_segmentation_masks = batch_segmentation_masks.to(torch.float32).to(device)\n        batch_labels = batch_labels.to(torch.float32).to(device)\n        \n        batch_images = batch_images.unsqueeze(1)\n        batch_segmentation_masks = batch_segmentation_masks.unsqueeze(1)\n\n        # Move your model to the TPU device\n        model = model.to(device)\n\n        # Inside your training loop or forward pass\n        batch_images = batch_images.to(device)\n        batch_segmentation_masks = batch_segmentation_masks.to(device)\n\n        # Forward pass\n        classification_outputs, segmentation_outputs = model(batch_images, batch_segmentation_masks)\n        \n        # Apply sigmoid activation to the classification outputs\n        classification_outputs = torch.sigmoid(classification_outputs)\n            \n        # Initialize batch-level variables for accuracy calculation\n        batch_correct = 0\n        batch_samples = batch_labels.size(0)\n        \n        for class_index in range(num_classes_classification):\n            class_labels = batch_labels[:, class_index]\n            class_outputs = classification_outputs[:, class_index]\n            \n            # Calculate binary predictions based on a threshold (e.g., 0.5)\n            predicted = (class_outputs > 0.5).float()\n                \n            class_accuracy = accuracy_score(class_labels.cpu(), predicted.cpu())\n            batch_correct += class_accuracy\n            \n            # Calculate precision, recall, and F1-score for the current class\n            precision, recall, f1, _ = precision_recall_fscore_support(\n                class_labels.cpu(), predicted.cpu(), average='binary')\n            \n            precision_list.append(precision)\n            recall_list.append(recall)\n            f1_list.append(f1)\n\n        # Accumulate batch-level accuracy\n        total_correct += batch_correct/num_classes_classification\n        total_samples += batch_samples\n    \n    test_accuracy = total_correct / len(test_loader)\n    print(f\"Test Accuracy: {test_accuracy:.4f}\")\n\n    # Calculate average precision, recall, and F1-score across all classes\n    avg_precision = sum(precision_list) / total_samples\n    avg_recall = sum(recall_list) / num_classes_classification\n    avg_f1 = sum(f1_list) / num_classes_classification\n","metadata":{"execution":{"iopub.status.busy":"2024-01-04T17:29:55.6039Z","iopub.execute_input":"2024-01-04T17:29:55.604463Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# !pip install scikit-image\n# !pip install pydicom\n# !pip install --upgrade pydicom\n# !pip install pylibjpeg-libjpeg\n# !pip install pydicom[gdcm]\n# !pip install pydicom[pylibjpeg]\n# !pip install pydicom\n# !pip install pylibjpeg pylibjpeg-libjpeg pydicom[pylibjpeg]\n# !pip install --upgrade pydicom\n# import pydicom.config\n# pydicom.config.pixel_data_handlers = ['numpy']\n# #!pip install --upgrade pip\n# #!pip install torch-xla\n# #!pip install torch_xla.dataloader \n# #!pip install cloud-tpu-client\n# #!pip install torch-xla","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# import torch.nn as nn\n# import torch.optim as optim\n# import torchvision.transforms as transforms\n# from torch.utils.data import DataLoader, Dataset\n# import numpy as np\n# import pandas as pd\n# from sklearn.utils.class_weight import compute_class_weight\n# from sklearn.model_selection import train_test_split\n# import pydicom\n# from skimage.transform import resize as sk_resize\n# def resize(image, size):\n#     pil_image = Image.fromarray(image)\n#     resized_image = pil_image.resize(size)\n#     return np.array(resized_image)\n\n# import torch\n# import torch.nn as nn\n# import torch.nn.functional as F\n\n# import torchvision.transforms.functional as F\n# import torch_xla\n# import torch_xla.core.xla_model as xm\n# import torch_xla.distributed.xla_multiprocessing as xmp\n# import torch_xla.distributed.parallel_loader as xla_parallel\n# import torch_xla.distributed.data_parallel as dp\n# import torch_xla.utils.utils as xu\n# import torch_xla.debug.metrics as met\n# from torch_xla.distributed.parallel_loader import ParallelLoader\n\n\n\n\n# # Define a smaller ShuffleNetSE model\n\n    \n# class ShuffleNetBlockSE(nn.Module):\n#     def __init__(self, in_channels, out_channels, stride, groups):\n#         super(ShuffleNetBlockSE, self).__init__()\n#         self.stride = stride\n#         self.groups = groups\n#         mid_channels = out_channels // 8\n        \n#         self.conv1 = nn.Conv2d(in_channels, mid_channels, kernel_size=1, bias=False)\n#         self.bn1 = nn.BatchNorm2d(mid_channels)\n#         self.conv2 = nn.Conv2d(mid_channels, mid_channels, kernel_size=3, stride=stride, padding=1, groups=groups, bias=False)\n#         self.bn2 = nn.BatchNorm2d(mid_channels)\n#         self.conv3 = nn.Conv2d(mid_channels, out_channels, kernel_size=1, bias=False)\n#         self.bn3 = nn.BatchNorm2d(out_channels)\n        \n#         self.relu = nn.ReLU(inplace=True)\n#         self.se = SEBlock(out_channels)\n        \n#         if stride != 1 or in_channels != out_channels:\n#             self.shortcut = nn.Sequential(\n#                 nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride, bias=False),\n#                 nn.BatchNorm2d(out_channels)\n#             )\n#         else:\n#             self.shortcut = nn.Sequential()\n            \n#     def forward(self, x):\n#         out = self.conv1(x)\n#         out = self.bn1(out)\n#         out = self.relu(out)\n        \n#         out = self.conv2(out)\n#         out = self.bn2(out)\n#         out = self.relu(out)\n        \n#         out = self.conv3(out)\n#         out = self.bn3(out)\n        \n#         out = self.se(out)\n        \n#         shortcut = self.shortcut(x)\n        \n#         out += shortcut\n#         out = self.relu(out)\n        \n#         return out\n\n\n# class SEBlock(nn.Module):\n#     def __init__(self, channel):\n#         super(SEBlock, self).__init__()\n#         self.squeeze = nn.AdaptiveAvgPool2d(1)\n#         self.excitation = nn.Sequential(\n#             nn.Linear(channel, channel // 16),\n#             nn.ReLU(inplace=True),\n#             nn.Linear(channel // 16, channel),\n#             nn.Sigmoid()\n#         )\n        \n#     def forward(self, x):\n#         out = self.squeeze(x)\n#         out = out.view(out.size(0), -1)\n#         out = self.excitation(out)\n#         out = out.view(out.size(0), out.size(1), 1, 1)\n#         return x * out\n\n# # Define ShuffleNetBlockSE and SEBlock classes as you did in your code\n# class ShuffleNetSE(nn.Module):\n#     def __init__(self, num_classes=2, groups=3):\n#         super(ShuffleNetSE, self).__init__()\n#         self.conv1 = nn.Sequential(\n#             nn.Conv2d(3, 24, kernel_size=3, stride=2, padding=1),\n#             nn.BatchNorm2d(24),\n#             nn.ReLU(inplace=True)\n#         )\n#         self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n#         self.stages = nn.Sequential(\n#             ShuffleNetBlockSE(24, 120, stride=2, groups=groups),\n#             # ShuffleNetBlockSE(120, 240, stride=2, groups=groups),\n#         )\n#         self.global_avgpool = nn.AdaptiveAvgPool2d(1)\n#         self.fc = nn.Linear(120, num_classes)\n        \n#     def forward(self, x):\n#         out = self.conv1(x)\n#         out = self.maxpool(out)\n#         out = self.stages(out)\n#         out = self.global_avgpool(out)\n#         out = torch.flatten(out, 1)\n#         out = self.fc(out)\n#         return out\n    \n\n#     def _make_stages(self):\n#         stages = []\n#         for i in range(len(self.stage_repeats)):\n#             stage = self._make_stage(i)\n#             stages.append(stage)\n#         return nn.Sequential(*stages)\n\n#     def _make_stage(self, stage_idx):\n#         layers = []\n#         repeat = self.stage_repeats[stage_idx]\n#         in_channels = self.stage_out_channels[stage_idx]\n#         out_channels = self.stage_out_channels[stage_idx + 1]\n#         for i in range(repeat):\n#             layers.append(ShuffleNetBlockSE(in_channels, out_channels, self.groups))\n#             in_channels = out_channels\n#         return nn.Sequential(*layers)\n    \n# shufflenet_se_model = ShuffleNetSE(num_classes=2, groups=3)\n    \n\n\n# # Load and preprocess data from CSV\n# data = pd.read_csv('/kaggle/input/laya-sample/train_file_paths_few_images (1).csv')\n# data = data.head(10)# Replace with your actual CSV file path\n\n# # Split data into train, validation, and test sets\n# train_data, temp_data = train_test_split(data, test_size=0.3, random_state=42)\n# val_data, test_data = train_test_split(temp_data, test_size=0.5, random_state=42)\n\n# # Extract file paths and labels from the data\n# train_paths = train_data['file_path'].values\n# train_labels = train_data['cancer'].values\n\n# val_paths = val_data['file_path'].values\n# val_labels = val_data['cancer'].values\n\n# test_paths = test_data['file_path'].values\n# test_labels = test_data['cancer'].values\n\n# # Define a custom dataset\n# class CustomDataset(Dataset):\n#     def __init__(self, data_paths, labels, transform=None, target_size=(128, 128)):\n#         self.data_paths = data_paths\n#         self.labels = labels\n#         self.transform = transform\n#         self.target_size = target_size\n\n#     def _len_(self):\n#         return len(self.data_paths)\n\n#     def _getitem_(self, idx):\n#         dicom_path = self.data_paths[idx]\n        \n#         # Read DICOM file using pydicom\n#         dicom_data = pydicom.dcmread(dicom_path)\n#         image = dicom_data.pixel_array.astype(np.float32)\n#         image = image / np.max(image)  # Normalize to [0, 1]\n        \n#         # Resize the image using skimage.transform.resize\n#         resized_image = sk_resize(image, self.target_size, mode='reflect')\n        \n#         # Convert single-channel resized image to RGB\n#         resized_image_rgb = np.stack((resized_image,) * 3, axis=-1)\n        \n#         label = self.labels[idx]\n\n#         if self.transform:\n#             resized_image_rgb = self.transform(resized_image_rgb)\n\n#         return resized_image_rgb, label\n\n# # Define data transforms\n# transform = transforms.Compose([\n#     transforms.ToTensor(),\n# ])\n\n# # Common target size for the resized images\n# common_image_size = (128, 128)\n# #device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n# devices = xm.xla_device(n=0)\n\n\n# # Training loop\n\n\n\n\n# train_dataset = CustomDataset(train_paths, train_labels, transform=transform)\n# val_dataset = CustomDataset(val_paths, val_labels, transform=transform)\n# test_dataset = CustomDataset(test_paths, test_labels, transform=transform)\n\n# batch_size = 32\n\n\n# # Create DataLoaders\n# train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)\n# val_loader = DataLoader(val_dataset, batch_size=batch_size)\n# test_loader = DataLoader(test_dataset, batch_size=batch_size)\n\n\n# # Calculate class weights for handling class imbalance\n# class_weights = compute_class_weight('balanced', classes=np.unique(train_labels), y=train_labels)\n# class_weights = torch.tensor(class_weights, dtype=torch.float32, device=devices)\n\n# #class_weights = torch.tensor(class_weights, dtype=torch.float32, device=devices)\n\n\n# # Make sure class_weights is a tensor with shape (num_classes,)\n# class_weights = class_weights.unsqueeze(0) if len(class_weights.shape) == 1 else class_weights\n# class_weights = class_weights.squeeze()  # Remove the unnecessary dimension\n\n# # Calculate class weights for handling class imbalance\n# #class_weights = compute_class_weight('balanced', classes=np.unique(train_labels), y=train_labels)\n# #class_weights = torch.tensor(class_weights, dtype=torch.float32, device=devices[0])\n# # Make sure class_weights is a tensor with shape (num_classes,)\n# #class_weights = class_weights.unsqueeze(0) if len(class_weights.shape) == 1 else class_weights\n\n\n# # Instantiate the smaller ShuffleNetSE model\n# num_classes = 2\n# shufflenet_se_model = ShuffleNetSE(num_classes)\n\n# # Define loss function and optimizer\n# #criterion = nn.CrossEntropyLoss(weight=class_weights)\n# #optimizer = optim.Adam(shufflenet_se_model.parameters(), lr=0.001)\n\n# # Convert the model's parameters to the desired data type and move to the device\n# #shufflenet_se_model.to(torch.float32)\n# #shufflenet_se_model.to(device)\n# shufflenet_se_model = ShuffleNetSE(num_classes=2, groups=3)\n# shufflenet_se_model = shufflenet_se_model.to(devices)\n# criterion = nn.CrossEntropyLoss(weight=class_weights)\n\n# # Define an XLA-compatible optimizer\n# optimizer = optim.Adam(shufflenet_se_model.parameters(), lr=0.001)\n# shufflenet_se_model = shufflenet_se_model.to(xm.xla_device())\n\n\n# num_epochs = 1  # Adjust the number of epochs as needed\n\n# for epoch in range(num_epochs):\n#     shufflenet_se_model.train()\n#     train_loss = 0.0\n#     correct_train = 0\n#     total_train = 0\n    \n#     for batch_images, batch_labels in train_loader:\n#         optimizer.zero_grad()\n#         batch_images = batch_images.to(xm.xla_device())  # Convert the input to the TPU device\n#         batch_labels = batch_labels.to(xm.xla_device())  # Convert the labels to the TPU device\n#         outputs = shufflenet_se_model(batch_images)\n        \n#         loss = criterion(outputs, batch_labels)\n#         loss.backward()\n#         optimizer.step()\n\n#         # Compute accuracy\n#         _, predicted = torch.max(outputs, 1)\n#         total_train += batch_labels.size(0)\n#         correct_train += (predicted == batch_labels).sum().item()\n\n#         train_loss += loss.item()\n\n#     train_accuracy = correct_train / total_train\n#     train_loss /= len(train_loader)\n\n#     print(f\"Epoch [{epoch+1}/{num_epochs}]\")\n#     print(f\"Train Accuracy: {train_accuracy:.4f} | Train Loss: {train_loss:.4f}\")\n    \n#     # Validation loop\n#     shufflenet_se_model.eval()\n#     total_correct_val = 0\n#     total_samples_val = 0\n#     running_val_loss = 0.0\n    \n#     with torch.no_grad():\n#         for batch_images, batch_labels in val_loader:\n#             batch_images = batch_images.to(xm.xla_device())\n#             batch_labels = batch_labels.to(xm.xla_device())\n#             outputs = shufflenet_se_model(batch_images)\n            \n#             loss = criterion(outputs, batch_labels)\n#             running_val_loss += loss.item()\n            \n#             _, predicted = torch.max(outputs, 1)\n#             total_correct_val += (predicted == batch_labels).sum().item()\n#             total_samples_val += batch_labels.size(0)\n            \n#         val_accuracy = total_correct_val / total_samples_val\n#         val_loss = running_val_loss / len(val_loader)\n        \n#         print(f\"Epoch [{epoch+1}/{num_epochs}]\")\n#         print(f\"Validation Accuracy: {val_accuracy:.4f} | Validation Loss: {val_loss:.4f}\")\n        \n#          # Testing loop\n# shufflenet_se_model.eval()\n# with torch.no_grad():\n#     total_correct_test = 0\n#     total_samples_test = 0\n#     running_test_loss = 0.0\n    \n#     for batch_images, batch_labels in test_loader:\n#         batch_images = batch_images.to(xm.xla_device())\n#         batch_labels = batch_labels.to(xm.xla_device())\n        \n#         outputs = shufflenet_se_model(batch_images)\n#         loss = criterion(outputs, batch_labels)\n#         running_test_loss += loss.item()\n        \n#         _, predicted = torch.max(outputs, 1)\n#         total_correct_test += (predicted == batch_labels).sum().item()\n#         total_samples_test += batch_labels.size(0)\n        \n#     test_accuracy = total_correct_test / total_samples_test\n#     test_loss = running_test_loss / len(test_loader)\n    \n#     print(f\"Test Accuracy: {test_accuracy:.4f} | Test Loss: {test_loss:.4f}\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import nibabel as nib\nimport matplotlib.pyplot as plt\n\ndef display_nifti_image(nifti_path):\n    # Load the NIfTI file\n    nifti_img = nib.load(nifti_path)\n\n    # Get the NIfTI data array\n    img_data = nifti_img.get_fdata()\n\n    # Display the image (assuming 3D, you may need to adjust for 4D or other dimensions)\n    plt.imshow(img_data[:, :, img_data.shape[2] // 2], cmap='gray')\n    plt.title('NIfTI Image')\n    plt.show()\n\n# Replace 'your_file.nii' with the path to your NIfTI file\nnifti_file_path = '/kaggle/input/abdominal-trauma-nii-dataset/output-1/10217_16066.nii'\ndisplay_nifti_image(nifti_file_path)\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\nimport nibabel as nib\nfrom torchvision.transforms import functional as F\nfrom PIL import Image\nimport numpy as np\n\n# Load the trained model\nmodel = Custom3DViTModelTPU(3, 14, 5, 32)\nmodel.load_state_dict(torch.load('/kaggle/input/sample-model-weight-abdominal/vit_abdominal.pth'))\nmodel.eval()\n\n# Load and preprocess a single image\nimage_path = '/kaggle/input/abdominal-trauma-nii-dataset/output-6/output_nii_images/60007_64124.nii'  # Replace with the actual path to your image\nimg_data = nib.load(image_path).get_fdata()\nimg_tensor = torch.unsqueeze(torch.tensor(img_data, dtype=torch.float32), dim=0)\n\n# Assuming the image size is 224x224, you may need to adjust this based on your model input size\nimg_tensor = F.resize(img_tensor, (128,128))\nimg_tensor = F.to_tensor(img_tensor)\n\n# Make prediction\nwith torch.no_grad():\n    model_output = model(img_tensor.unsqueeze(0))  # Add batch dimension\n\n# Convert logits to probabilities using sigmoid activation\nprobabilities = torch.sigmoid(model_output)\n\n# Convert the tensor to a NumPy array\nprobabilities_np = probabilities.cpu().numpy()\n\n# Print predictions\nclass_names = ['bowel_healthy', 'bowel_injury', 'extravasation_healthy', 'extravasation_injury',\n               'kidney_healthy', 'kidney_low', 'kidney_high', 'liver_healthy', 'liver_low', 'liver_high',\n               'spleen_healthy', 'spleen_low', 'spleen_high', 'any_injury']\n\nfor class_name, probability in zip(class_names, probabilities_np.squeeze()):\n    print(f'{class_name}: {probability:.4f}')\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}