{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"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-09-21T14:59:29.651645Z","iopub.execute_input":"2023-09-21T14:59:29.652011Z","iopub.status.idle":"2023-09-21T14:59:36.387343Z","shell.execute_reply.started":"2023-09-21T14:59:29.651982Z","shell.execute_reply":"2023-09-21T14:59:36.385889Z"},"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\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\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\nclass MultiLabel3DAttentionModel(nn.Module):\n    def __init__(self, num_classes, num_classes_segmentation):\n        super(MultiLabel3DAttentionModel, self).__init__()\n\n        # Load a pre-trained ResNet3D backbone\n        self.backbone = models.video.r3d_18(pretrained=True)\n        \n               \n        # Modify the stem to accept the correct input channels (128)\n        self.backbone.stem[0] = nn.Sequential(\n            nn.Conv3d(1, 64, kernel_size=(3, 7, 7), stride=(1, 2, 2), padding=(1, 3, 3)),\n            nn.BatchNorm3d(64),\n            nn.ReLU(inplace=True))\n\n        # Attention block\n        self.attention = nn.Sequential(\n            nn.Conv3d(1, 128, kernel_size=1),\n            nn.ReLU(inplace=True),\n            nn.Conv3d(128, 1, kernel_size=1),\n            nn.Sigmoid()\n        )\n        \n        # Classification head\n        self.classification_head = nn.Sequential(\n            nn.AdaptiveAvgPool3d(1),\n            nn.Flatten(),\n            nn.Linear(1, 64),\n            nn.ReLU(inplace=True),\n            nn.Linear(64, num_classes),\n            nn.Sigmoid()\n        )\n        \n        # Segmentation head\n        self.segmentation_head = nn.Sequential(\n            nn.Conv3d(1, 128, kernel_size=1),\n            nn.ReLU(inplace=True),\n            nn.Conv3d(128, num_classes_segmentation, kernel_size=1),\n            nn.Sigmoid()\n        )\n        \n    def forward(self, x, segmentation_mask):\n        #print( '...............', x.dtype, segmentation_mask.dtype)\n        print(\"X shape\", x.shape)\n        \n\n        features = self.backbone(x)\n        print(\"features shape\", features.shape)\n        # Apply attention to features\n        # Assuming features has shape [batch_size, num_features]\n        # Reshape features to [batch_size, 1, 1, 1, num_features]\n        features = features.view(features.size(0), 1, 1, 1, features.size(1))\n        \n        attention_weights = self.attention(features)\n        \n        print('attention_weights shape', attention_weights.shape)\n        attended_features = features * attention_weights\n        print('attended_features', attended_features.shape)\n        \n        # Classification branch\n        classification_output = self.classification_head(attended_features)\n        \n        # Reshape attended_features to match segmentation_mask's shape along dimensions 2, 3, and 4\n        #attended_features = attended_features.expand(-1, -1, 128, 128, 128)\n\n        print('segmentation_mask', segmentation_mask.shape)\n        \n        # Segmentation branch\n        # Reshape attended_features to match segmentation_mask's shape along dimensions 2, 3, and 4\n        #attended_features = attended_features.expand(-1, -1, segmentation_mask.size(2), segmentation_mask.size(3), segmentation_mask.size(4))\n        \n        #segmentation_output = self.segmentation_head(attended_features) * segmentation_mask\n        \n        # Modify the segmentation head to handle the different number of channels\n        segmentation_output = self.segmentation_head(attended_features)\n         # You can use interpolation or other methods to match the shape.\n        segmentation_output = F.interpolate(segmentation_output, size=segmentation_mask.shape[2:], mode='trilinear')\n        \n        print('segmentation_output', segmentation_output.shape)\n        \n        segmentation_output = segmentation_output * segmentation_mask  # Element-wise multiplication\n        \n        \n        return classification_output, segmentation_output\n\n# Paths and settings\nsegmentation_dir = '/kaggle/input/rsna-2022-cervical-spine-fracture-detection/segmentations'  # Update with the correct path\ncsv_file = '/kaggle/input/cervical-csv/train_file_mask_path_2 (1).csv'\n  # Update with the correct path\nbatch_size = 16\nnum_workers = 4  # Number of CPU cores to use for data loading\nnum_classes = 7  # Number of classes\ndesired_shape = (128, 128, 128)\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\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)\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[['C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7']].values\n\nval_paths = val_data['file_path'].values\nval_mask_paths = val_data['mask_path'].values\nval_labels = val_data[['C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7']].values\n\ntest_paths = test_data['file_path'].values\ntest_mask_paths = test_data['mask_path'].values\ntest_labels = test_data[['C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7']].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\nnum_classes_classification = 7  # Number of classes for classification\nnum_classes_segmentation = 1    # Number of classes for segmentation (change this according to your task)\nmodel = MultiLabel3DAttentionModel(num_classes_classification, num_classes_segmentation)\n\n\n# Define loss function and optimizer\ncriterion = nn.BCELoss()  # Binary Cross-Entropy loss\noptimizer = optim.Adam(model.parameters(), lr=0.001)\n\n# def print_parameter_data_types(module):\n#     for name, param in module.named_parameters():\n#         print(f\"Parameter: {name}, Data Type: {param.dtype}\")\n\n# # Call the function to print data types of parameters in the backbone module\n# print_parameter_data_types(model.backbone)\n\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    \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\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]  # 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        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        \n        # Backpropagation and optimization\n        total_loss.backward()\n        optimizer.step()\n\n    # Calculate and print average training accuracy and loss\n    avg_train_accuracy = correct_train / total_train\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            batch_images = batch_images.unsqueeze(1)\n            batch_segmentation_masks = batch_segmentation_masks.unsqueeze(1)\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        # 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 = correct_test / 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-09-21T14:59:36.390545Z","iopub.execute_input":"2023-09-21T14:59:36.391074Z","iopub.status.idle":"2023-09-21T16:09:00.545389Z","shell.execute_reply.started":"2023-09-21T14:59:36.391014Z","shell.execute_reply":"2023-09-21T16:09:00.543763Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}