{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.8.17","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"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":"2023-10-16T07:33:41.553615Z","iopub.execute_input":"2023-10-16T07:33:41.553955Z","iopub.status.idle":"2023-10-16T07:33:46.914687Z","shell.execute_reply.started":"2023-10-16T07:33:41.553926Z","shell.execute_reply":"2023-10-16T07:33:46.913376Z"},"trusted":true},"execution_count":2,"outputs":[{"name":"stdout","text":"Collecting nibabel\n  Downloading nibabel-5.1.0-py3-none-any.whl (3.3 MB)\n\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m3.3/3.3 MB\u001b[0m \u001b[31m29.3 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m00:01\u001b[0m00:01\u001b[0m\n\u001b[?25hRequirement already satisfied: packaging>=17 in /usr/local/lib/python3.8/site-packages (from nibabel) (23.1)\nRequirement already satisfied: numpy>=1.19 in /usr/local/lib/python3.8/site-packages (from nibabel) (1.23.5)\nRequirement already satisfied: importlib-resources>=1.3 in /usr/local/lib/python3.8/site-packages (from nibabel) (6.0.0)\nRequirement already satisfied: zipp>=3.1.0 in /usr/local/lib/python3.8/site-packages (from importlib-resources>=1.3->nibabel) (3.15.0)\nInstalling collected packages: nibabel\nSuccessfully installed nibabel-5.1.0\n\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n\u001b[0m\n\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m23.0.1\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m23.3\u001b[0m\n\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpip install --upgrade pip\u001b[0m\n","output_type":"stream"}]},{"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=32, 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    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\n    def forward(self, x, segmentation_mask):\n        print(\"in up loop 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# Move the entire model to XLA devices\ndef get_model():\n    return Custom3DViTModelTPU(3, 10, 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 = 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":"2023-10-16T07:34:15.620646Z","iopub.execute_input":"2023-10-16T07:34:15.621003Z","iopub.status.idle":"2023-10-16T07:34:57.849701Z","shell.execute_reply.started":"2023-10-16T07:34:15.620973Z","shell.execute_reply":"2023-10-16T07:34:57.848514Z"},"trusted":true},"execution_count":3,"outputs":[{"name":"stdout","text":"^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n","output_type":"stream"},{"name":"stderr","text":"E1016 07:34:49.242045205     382 oauth2_credentials.cc:236]            oauth_fetch: UNKNOWN:C-ares status is not ARES_SUCCESS qtype=A name=metadata.google.internal. is_balancer=0: Domain name not found {grpc_status:2, created_time:\"2023-10-16T07:34:49.242028134+00:00\"}\n","output_type":"stream"},{"name":"stdout","text":">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n*****************************************************************************\nin up loop x shape and segmentation_mask shape torch.Size([32, 1, 128, 128, 128]) torch.Size([32, 1, 128, 128, 128])\nBefore embedding x.shape is  torch.Size([32, 2097152])\nAfter embedding x.shape is  torch.Size([32, 32])\nx shape after unsqueeze torch.Size([1, 32, 32])\ntgt shape torch.Size([1, 32, 32])\nOutput shape after transformer torch.Size([1, 32, 32])\nfeatures shape torch.Size([1, 1, 32, 10])\nclassification_output torch.Size([32, 10])\nsegmentation output torch.Size([32, 5, 128, 128, 128])\n","output_type":"stream"}]},{"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\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(100)\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.3, 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 = 1\n\nfor epoch in range(num_epochs):\n    model.train()\n    running_loss = 0.0\n    correct_train = 0\n    total_train = 0\n    # Initialize a list to store class accuracies\n    accuracies = []\n    for batch_images, batch_segmentation_masks, batch_labels in train_loader:\n        optimizer.zero_grad()\n        \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(\"thsi is batch_images shape and batch_segmentation_masks shape\", \n              batch_images.shape, batch_segmentation_masks.shape)\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        # 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            losses.append(class_loss)\n\n        # Calculate the total loss as the sum of individual class losses\n        total_loss = sum(losses)\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            total_loss += segmentation_loss\n\n        running_loss += total_loss.item()\n        \n        # Calculate accuracy for each class separately\n        \n        \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            accuracies.append(class_accuracy)\n    \n#         # Calculate the overall accuracy for the batch\n#         batch_accuracy = sum(accuracies) / num_classes_classification\n#         correct_train += (batch_accuracy * len(batch_images))\n#         total_train += len(batch_images)\n\n        # Backpropagation and optimization (details not shown)\n\n    # Calculate and print average training accuracy and loss\n    avg_train_accuracy = sum(accuracies) / len(accuracies)\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\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\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)\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\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 / total_val\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}\")\n\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\n        total_samples += batch_samples\n    \n    test_accuracy = total_correct / total_samples\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) / num_classes_classification\n    avg_recall = sum(recall_list) / num_classes_classification\n    avg_f1 = sum(f1_list) / num_classes_classification\n\n    print(f\"Average Precision: {avg_precision:.4f}\")\n    print(f\"Average Recall: {avg_recall:.4f}\")\n    print(f\"Average F1 Score: {avg_f1:.4f}\")\n","metadata":{"execution":{"iopub.status.busy":"2023-10-16T07:35:39.131131Z","iopub.execute_input":"2023-10-16T07:35:39.131549Z"},"trusted":true},"execution_count":null,"outputs":[{"name":"stdout","text":"xla:0\nLength of DataFrame: 100\nlen of train_dataset 70\ntrain_loader 2\n<torch.utils.data.dataloader.DataLoader object at 0x7b1d255448e0>\nTotal Trainable Parameters: 68785726\n","output_type":"stream"}]}]}