{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":36363,"databundleVersionId":4050810,"sourceType":"competition"},{"sourceId":6403207,"sourceType":"datasetVersion","datasetId":3692048},{"sourceId":6665364,"sourceType":"datasetVersion","datasetId":3846147},{"sourceId":6742187,"sourceType":"datasetVersion","datasetId":3882647},{"sourceId":6874921,"sourceType":"datasetVersion","datasetId":3950522},{"sourceId":6908217,"sourceType":"datasetVersion","datasetId":3967453},{"sourceId":7659622,"sourceType":"datasetVersion","datasetId":3607309},{"sourceId":8257741,"sourceType":"datasetVersion","datasetId":4892743},{"sourceId":8257753,"sourceType":"datasetVersion","datasetId":4884964}],"dockerImageVersionId":30559,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"!pip install --upgrade pip --quiet\n!pip install nibabel --quiet\n!pip install torch torchvision torchaudio --quiet","metadata":{"execution":{"iopub.status.busy":"2024-05-10T23:58:16.594822Z","iopub.execute_input":"2024-05-10T23:58:16.595106Z","iopub.status.idle":"2024-05-10T23:59:07.075725Z","shell.execute_reply.started":"2024-05-10T23:58:16.595078Z","shell.execute_reply":"2024-05-10T23:59:07.074362Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install monai --quiet","metadata":{"execution":{"iopub.status.busy":"2024-05-10T23:59:38.692619Z","iopub.execute_input":"2024-05-10T23:59:38.693025Z","iopub.status.idle":"2024-05-10T23:59:52.696483Z","shell.execute_reply.started":"2024-05-10T23:59:38.692992Z","shell.execute_reply":"2024-05-10T23:59:52.695132Z"},"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\n# Constants and configuration settings\nsegmentation_dir = '/kaggle/input/rsna-2022-cervical-spine-fracture-detection/segmentations'\ncsv_file = '/kaggle/input/file-mask-path/train_file_mask_path.csv'\nbatch_size = 2\nnum_workers = 4\nnum_classes = 8\ndesired_shape = (128, 128, 128)\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\nfrom monai.networks.nets import efficientnet\nfrom monai.networks.nets import densenet, resnet, senet, autoencoder, attentionunet\nimport torch\n\nfrom tqdm import tqdm\nimport pickle\n\nimport warnings\n# Ignore all future warnings\nwarnings.simplefilter(action='ignore', category=FutureWarning)","metadata":{"_kg_hide-output":true,"execution":{"iopub.status.busy":"2024-05-11T00:00:29.623858Z","iopub.execute_input":"2024-05-11T00:00:29.624292Z","iopub.status.idle":"2024-05-11T00:01:18.20805Z","shell.execute_reply.started":"2024-05-11T00:00:29.624247Z","shell.execute_reply":"2024-05-11T00:01:18.207134Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"csv_file_path = '/kaggle/input/file-mask-path/train_file_mask_path.csv'\n\n# Load the CSV data using pandas\ndata_frame = pd.read_csv(csv_file_path)\n\n# Extract relevant information from the data\nimage_paths = data_frame['file_path'].values\nmask_paths = data_frame['mask_path'].values\nlabels = data_frame[['C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'patient_overall']].values\n","metadata":{"execution":{"iopub.status.busy":"2024-05-11T00:01:24.987954Z","iopub.execute_input":"2024-05-11T00:01:24.988951Z","iopub.status.idle":"2024-05-11T00:01:25.02576Z","shell.execute_reply.started":"2024-05-11T00:01:24.988897Z","shell.execute_reply":"2024-05-11T00:01:25.024913Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import nibabel as nib\nimport pandas as pd\nimport torch\nfrom torch.utils.data import Dataset\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        image = nib.load(image_path).get_fdata()\n        segmentation_mask = None\n\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        if self.transform:\n            image = self.transform(image)\n\n        if segmentation_mask is not None and self.transform:\n            \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","metadata":{"execution":{"iopub.status.busy":"2024-05-11T00:01:28.936482Z","iopub.execute_input":"2024-05-11T00:01:28.937252Z","iopub.status.idle":"2024-05-11T00:01:28.947226Z","shell.execute_reply.started":"2024-05-11T00:01:28.937206Z","shell.execute_reply":"2024-05-11T00:01:28.946282Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create an instance of the custom dataset\ndataset = CustomDataset(image_paths, mask_paths, labels, transform=None)\n\n# Define the index of the sample you want to access\nsample_index = 0  # You can change this to any index you're interested in\n\n# Access the image and mask paths for the specific sample\nimage_path = dataset.image_paths[sample_index]\nmask_path = dataset.mask_paths[sample_index]","metadata":{"execution":{"iopub.status.busy":"2024-05-11T00:01:33.150423Z","iopub.execute_input":"2024-05-11T00:01:33.150806Z","iopub.status.idle":"2024-05-11T00:01:33.156393Z","shell.execute_reply.started":"2024-05-11T00:01:33.150776Z","shell.execute_reply":"2024-05-11T00:01:33.155273Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\nimport torch.nn as nn\nimport torchvision.models as models\nfrom scipy.ndimage import zoom\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","metadata":{"execution":{"iopub.status.busy":"2024-05-11T00:01:35.876113Z","iopub.execute_input":"2024-05-11T00:01:35.876516Z","iopub.status.idle":"2024-05-11T00:01:35.883148Z","shell.execute_reply.started":"2024-05-11T00:01:35.87648Z","shell.execute_reply":"2024-05-11T00:01:35.881997Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom monai.networks.nets import Classifier\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        image_size = (128, 128, 128)  \n\n        image_size = (128)\n        num_channels = 1\n        num_classes = 8\n        channels = (16, 32, 64, 128)\n        strides = (2, 2, 2, 2)\n        self.backbone = Classifier(in_shape=(num_channels, image_size, image_size, image_size), classes=num_classes, channels=channels, strides=strides)\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\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        # Feature extraction with the backbone\n        features = self.backbone(x)\n\n        # Apply attention to features\n        features = features.view(features.size(0), 1, 1, 1, features.size(1))\n        attention_weights = self.attention(features)\n        attended_features = features * attention_weights\n\n        # Classification branch\n        classification_output = self.classification_head(attended_features)\n        \n        # Initialize segmentation_output as None\n        segmentation_output = None\n\n        # Check if segmentation_mask is None\n        if segmentation_mask is not None:\n            \n            # Segmentation branch\n            segmentation_output = self.segmentation_head(attended_features)\n            segmentation_output = F.interpolate(segmentation_output, size=segmentation_mask.shape[2:], mode='trilinear')\n            segmentation_output = segmentation_output * segmentation_mask\n            \n        else:\n            # No segmentation branch in the test phase\n            segmentation_mask = torch.zeros_like(x)\n\n        return classification_output, segmentation_output\n","metadata":{"execution":{"iopub.status.busy":"2024-05-11T00:01:37.809085Z","iopub.execute_input":"2024-05-11T00:01:37.809476Z","iopub.status.idle":"2024-05-11T00:01:37.824539Z","shell.execute_reply.started":"2024-05-11T00:01:37.809444Z","shell.execute_reply":"2024-05-11T00:01:37.823552Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"transform = transforms.Compose([\n    transforms.ToTensor(),  # Convert to tensor\n])","metadata":{"execution":{"iopub.status.busy":"2024-05-11T00:01:39.924138Z","iopub.execute_input":"2024-05-11T00:01:39.925243Z","iopub.status.idle":"2024-05-11T00:01:39.930408Z","shell.execute_reply.started":"2024-05-11T00:01:39.925189Z","shell.execute_reply":"2024-05-11T00:01:39.929281Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\n\n# Load the CSV file\ndata = pd.read_csv(csv_file)\ndata_length = len(data)\nprint(\"Length of DataFrame:\", data_length)\n\n# Remove leading and trailing whitespaces from column names\ndata.columns = data.columns.str.strip()\n\n\ntrain_data = pd.read_csv('/kaggle/input/data-divided/exp_train.csv')\ntest_data = pd.read_csv('/kaggle/input/data-divided/exp_test.csv')\nval_data = pd.read_csv('/kaggle/input/data-divided/exp_val.csv')\n\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', 'patient_overall']].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', 'patient_overall']].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', 'patient_overall']].values\n\nprint(\"Length of train_data:\", len(train_data))\nprint(\"Length of val_data:\", len(val_data))\nprint(\"Length of test_data:\", len(test_data))\n\n","metadata":{"execution":{"iopub.status.busy":"2024-05-11T00:01:42.092092Z","iopub.execute_input":"2024-05-11T00:01:42.092999Z","iopub.status.idle":"2024-05-11T00:01:42.149817Z","shell.execute_reply.started":"2024-05-11T00:01:42.092961Z","shell.execute_reply":"2024-05-11T00:01:42.148876Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Instantiate the datasets\ntrain_dataset = CustomDataset(train_paths, train_mask_paths, train_labels, transform=transform)\nval_dataset = CustomDataset(val_paths, val_mask_paths, val_labels, transform=transform)\ntest_dataset = CustomDataset(test_paths, test_mask_paths, test_labels, transform=transform)","metadata":{"execution":{"iopub.status.busy":"2024-05-11T00:01:45.446152Z","iopub.execute_input":"2024-05-11T00:01:45.446518Z","iopub.status.idle":"2024-05-11T00:01:45.452141Z","shell.execute_reply.started":"2024-05-11T00:01:45.446489Z","shell.execute_reply":"2024-05-11T00:01:45.450969Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Instantiate the data loaders\ntrain_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=num_workers, drop_last=True)\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)","metadata":{"execution":{"iopub.status.busy":"2024-05-11T00:01:48.449358Z","iopub.execute_input":"2024-05-11T00:01:48.450371Z","iopub.status.idle":"2024-05-11T00:01:48.45609Z","shell.execute_reply.started":"2024-05-11T00:01:48.450331Z","shell.execute_reply":"2024-05-11T00:01:48.454892Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Instantiate the model with the appropriate number of classes for both classification and segmentation\nnum_classes_classification = 8  \nnum_classes_segmentation = 1    \nmodel = MultiLabel3DAttentionModel(num_classes_classification, num_classes_segmentation)\nprint(model)","metadata":{"execution":{"iopub.status.busy":"2024-05-11T00:01:50.614763Z","iopub.execute_input":"2024-05-11T00:01:50.615165Z","iopub.status.idle":"2024-05-11T00:01:50.666831Z","shell.execute_reply.started":"2024-05-11T00:01:50.615129Z","shell.execute_reply":"2024-05-11T00:01:50.665854Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tqdm import tqdm\nimport pickle \nimport random","metadata":{"execution":{"iopub.status.busy":"2024-05-11T00:01:58.255458Z","iopub.execute_input":"2024-05-11T00:01:58.256161Z","iopub.status.idle":"2024-05-11T00:01:58.260637Z","shell.execute_reply.started":"2024-05-11T00:01:58.256122Z","shell.execute_reply":"2024-05-11T00:01:58.25961Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\n\ndef focal_loss(predicted, label, weights, gamma=2, epsilon=1e-7):\n    # Calculate the probability of the positive class (pt) for each sample and class\n    pt = torch.where(label == 1, predicted, 1 - predicted)\n    \n    # Calculate the loss components for each class\n    loss = -weights * ((1 - pt) ** gamma) * torch.log(pt + epsilon)\n\n    # Sum the loss components for each class\n    final_loss = torch.sum(loss, dim=1) / torch.sum(weights, dim=1)\n    \n    return final_loss.mean()\n","metadata":{"execution":{"iopub.status.busy":"2024-05-11T00:02:00.643763Z","iopub.execute_input":"2024-05-11T00:02:00.644162Z","iopub.status.idle":"2024-05-11T00:02:00.650978Z","shell.execute_reply.started":"2024-05-11T00:02:00.644126Z","shell.execute_reply":"2024-05-11T00:02:00.649782Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\n\ndef binary_cross_entropy_loss(segmentation_outputs, batch_segmentation_masks):\n    batch_segmentation_masks = batch_segmentation_masks.to(torch.float32)\n    segmentation_outputs = segmentation_outputs.to(torch.float32)\n\n    # Create an instance of BCELoss\n    criterion = nn.BCELoss()\n\n    # Compute the BCE loss\n    loss = criterion(segmentation_outputs, batch_segmentation_masks)\n    \n    # Clamp the loss to ensure it's within the range [0, 1]\n    loss = torch.clamp(loss, min=0, max=1)\n\n    return loss\n\nimport torch\n\ndef weighted_cross_entropy(predicted, label, weights):\n    num_samples = predicted.shape[0]\n    \n    # Calculate element-wise losses\n    losses = weights * (-label * torch.log(predicted) - (1 - label) * torch.log(1 - predicted))\n    \n    # Sum the total_loss for all inputs and divide by the sum of weights\n    total_loss = torch.sum(losses, dim=1) / torch.sum(weights, dim=1)\n    \n    # Sum the total_loss for all inputs and divide by the number of samples\n    final_loss = torch.sum(total_loss) / num_samples\n    \n    # Clamp the final_loss to ensure it's within the range [0, 1]\n    final_loss = torch.clamp(final_loss, min=0, max=1)\n\n    return final_loss","metadata":{"execution":{"iopub.status.busy":"2024-05-11T00:02:03.007744Z","iopub.execute_input":"2024-05-11T00:02:03.008126Z","iopub.status.idle":"2024-05-11T00:02:03.017154Z","shell.execute_reply.started":"2024-05-11T00:02:03.008098Z","shell.execute_reply":"2024-05-11T00:02:03.016131Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport pickle\nfrom tqdm import tqdm\n\n# Function to calculate weights based on class labels\ndef weight_calculate(class_labels):\n    weights = []\n    total_weight = 0\n    count = 1\n\n    for label in class_labels:\n        if count % 8 == 0:\n            if label == 0:\n                weights.append(7)\n                total_weight += 7\n            else:\n                weights.append(14)\n                total_weight += 14\n        else:\n            if label == 0:\n                weights.append(1)\n                total_weight += 1\n            else:\n                weights.append(2)\n                total_weight += 2\n        count += 1\n\n    return torch.tensor(weights, dtype=torch.float32)\n\ndef cervical_spine_fracture_detection(num_epochs=10, initial_epoch=0, ran_once=False, model_path='sample.pth', history_path='sample_history.pkl'):\n\n    if ran_once:\n        # Load the existing model if ran_once is True\n        model = MultiLabel3DAttentionModel(num_classes_classification, num_classes_segmentation)\n        model.load_state_dict(torch.load(model_path))\n        model = model.to(device)\n\n        # Load the existing metrics history for plotting\n        with open(history_path, 'rb') as f:\n            metrics_history = pickle.load(f)\n\n        val_loss_history = metrics_history['val_loss_history']\n        val_acc_history = metrics_history['val_acc_history']\n        train_loss_history = metrics_history['train_loss_history']\n        train_acc_history = metrics_history['train_acc_history']\n    else:\n        # Create a new model if ran_once is False\n        model = MultiLabel3DAttentionModel(num_classes_classification, num_classes_segmentation)\n        model.to(device)\n\n        # Initialize empty lists for metrics history\n        val_loss_history = []\n        val_acc_history = []\n        train_loss_history = []\n        train_acc_history = []\n        \n#     total_start=time.time()\n    optimizer = optim.Adam(model.parameters(), lr=0.001)\n    best_metric = -1\n    best_metric_epoch = -1\n    best_metrics_epochs_and_time = [[], [], []]\n    \n    for 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 tqdm(train_loader, desc=f\"Epoch {epoch+1+initial_epoch}/{num_epochs+initial_epoch} Training:\"):\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            batch_images = batch_images.unsqueeze(1)  # Add a singleton dimension for channels\n            batch_segmentation_masks = batch_segmentation_masks.unsqueeze(1)\n\n            newbatch_images = batch_images\n            newbatch_segmentation_masks = batch_segmentation_masks\n\n            classification_outputs, segmentation_outputs = model(newbatch_images, newbatch_segmentation_masks)\n\n            # Apply sigmoid activation to the classification outputs\n            classification_outputs = torch.sigmoid(classification_outputs)\n\n            # Calculate weights for each sample based on class labels\n            weights = torch.stack([weight_calculate(labels) for labels in batch_labels]).to(device)\n\n            # Calculate binary cross-entropy loss with weights\n            weighted_loss = weighted_cross_entropy(classification_outputs, batch_labels, weights)\n\n            # Check if segmentation mask is available\n            if newbatch_segmentation_masks is not None and (newbatch_segmentation_masks != 0).any():\n                # Ensure that both input and target tensors are of type torch.float32\n                newbatch_segmentation_masks = newbatch_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 = binary_cross_entropy_loss(segmentation_outputs, newbatch_segmentation_masks)\n\n                # Add segmentation loss to the weighted loss\n                weighted_loss += segmentation_loss\n\n            running_loss += weighted_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            # 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            weighted_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        train_acc_history.append(avg_train_accuracy)\n        train_loss_history.append(avg_train_loss)\n\n        print(f\"Epoch [{epoch + initial_epoch + 1}/{num_epochs + initial_epoch}]\")\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 tqdm(train_loader, desc=f\"Epoch {epoch+1+initial_epoch}/{num_epochs+initial_epoch} Training:\"):\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                batch_images = batch_images.unsqueeze(1)  # Add a singleton dimension for channels\n                batch_segmentation_masks = batch_segmentation_masks.unsqueeze(1)\n\n                newbatch_images = batch_images\n                newbatch_segmentation_masks = batch_segmentation_masks\n\n                classification_outputs, segmentation_outputs = model(newbatch_images, newbatch_segmentation_masks)\n                \n                # Apply sigmoid activation to the classification outputs\n                classification_outputs = torch.sigmoid(classification_outputs)\n\n                # Calculate weights for each sample based on class labels\n                weights = torch.stack([weight_calculate(labels) for labels in batch_labels]).to(device)\n\n                # Calculate binary cross-entropy loss with weights\n                weighted_loss = weighted_cross_entropy(classification_outputs, batch_labels, weights)\n\n                # Check if segmentation mask is available\n                if newbatch_segmentation_masks is not None and (newbatch_segmentation_masks != 0).any():\n                    # Ensure that both input and target tensors are of type torch.float32\n                    newbatch_segmentation_masks = newbatch_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 = binary_cross_entropy_loss(segmentation_outputs, newbatch_segmentation_masks)\n\n                    # Add segmentation loss to the weighted loss\n                    weighted_loss += segmentation_loss\n\n                total_val_loss += weighted_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 += 1\n\n        val_accuracy = correct_val / total_val\n        avg_val_loss = total_val_loss / len(val_loader)\n        val_loss_history.append(avg_val_loss)\n        val_acc_history.append(val_accuracy)\n\n        print(f\"Epoch [{epoch + 1 + initial_epoch}/{num_epochs + initial_epoch}]\")\n        print(f\"Validation Accuracy: {val_accuracy:.4f} | Validation Loss: {avg_val_loss:.4f}\")\n        \n        if val_accuracy > best_metric:\n            best_metric = val_accuracy\n            best_metric_epoch = epoch + 1\n            torch.save(model.state_dict(), f\"best_model_Classifier_wcel{epoch + 1 + initial_epoch}.pth\")\n        else:\n        # Check if validation loss has improved\n        # Reset the count since there was an improvement\n            if (epoch + 1 + initial_epoch) % 5 == 0:\n                torch.save(model.state_dict(), f\"Classifier_wcel{epoch + 1 + initial_epoch}.pth\")\n\n            # Save the lists of metrics to a file for later plotting\n        metrics_history = {\n            'val_loss_history': val_loss_history,\n            'val_acc_history': val_acc_history,\n            'train_loss_history': train_loss_history,\n            'train_acc_history': train_acc_history,\n        }\n\n        with open(f\"Classifier_wcel_metrics_history.pkl\", 'wb') as f:\n            # This will be a single file, containing all the history\n            pickle.dump(metrics_history, f)\n","metadata":{"execution":{"iopub.status.busy":"2024-05-11T00:02:05.272015Z","iopub.execute_input":"2024-05-11T00:02:05.272413Z","iopub.status.idle":"2024-05-11T00:02:05.308994Z","shell.execute_reply.started":"2024-05-11T00:02:05.27238Z","shell.execute_reply":"2024-05-11T00:02:05.308137Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cervical_spine_fracture_detection(num_epochs=50, initial_epoch=120, ran_once=True, model_path='/kaggle/input/classifier-final/best_model_Classifier_wcel71.pth',history_path='/kaggle/input/classifier-final/Classifier_wcel_metrics_history.pkl')","metadata":{"execution":{"iopub.status.busy":"2024-05-11T00:02:13.73891Z","iopub.execute_input":"2024-05-11T00:02:13.73939Z","iopub.status.idle":"2024-05-11T00:25:26.622293Z","shell.execute_reply.started":"2024-05-11T00:02:13.739352Z","shell.execute_reply":"2024-05-11T00:25:26.617508Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pickle\nimport matplotlib.pyplot as plt\n\n# history_path = '/kaggle/input/train-run-1/metrics_history.pkl'\nhistory_path = '/kaggle/input/classifier-final/Classifier_wcel_metrics_history.pkl'\n\n# Load the metrics history from the saved file\nwith open(history_path, 'rb') as f:\n    metrics_history = pickle.load(f)\n\n# Extract the lists of metrics\ntrain_accuracies = metrics_history['train_acc_history']\nval_accuracies = metrics_history['val_acc_history']\ntrain_losses = metrics_history['train_loss_history']\nval_losses = metrics_history['val_loss_history']\n\n# Create a list of epoch numbers for the x-axis\nepochs = list(range(1, len(train_accuracies) + 1))\n\n# Plot training and validation accuracies\nplt.figure(figsize=(12, 5))\nplt.subplot(1, 2, 1)\nplt.plot(epochs, train_accuracies, label='Train Accuracy', marker='o')\nplt.plot(epochs, val_accuracies, label='Validation Accuracy', marker='o')\nplt.xlabel('Epoch')\nplt.ylabel('Accuracy')\nplt.title('Training and Validation Accuracies')\nplt.legend()\n\n# Plot training and validation losses\nplt.subplot(1, 2, 2)\nplt.plot(epochs, train_losses, label='Train Loss', marker='o')\nplt.plot(epochs, val_losses, label='Validation Loss', marker='o')\nplt.xlabel('Epoch')\nplt.ylabel('Loss')\nplt.title('Training and Validation Losses')\nplt.legend()\n\nplt.tight_layout()\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-04-29T02:26:36.161545Z","iopub.execute_input":"2024-04-29T02:26:36.161878Z","iopub.status.idle":"2024-04-29T02:26:36.864302Z","shell.execute_reply.started":"2024-04-29T02:26:36.161847Z","shell.execute_reply":"2024-04-29T02:26:36.863335Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tqdm import tqdm\nimport torch\nimport pandas as pd\nfrom torch.utils.data import DataLoader\nfrom sklearn.metrics import accuracy_score\n\n# Define your test data loader here\ntest_data = pd.read_csv('/kaggle/input/data-divided/exp_test.csv')\n# Placeholder for DataLoader and model creation to suit your actual use case\ntest_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False, num_workers=num_workers)\n\n# Instantiate your model\nmodel = MultiLabel3DAttentionModel(num_classes_classification, num_classes_segmentation)\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nmodel.to(device)\n\n# Load the saved model checkpoint\nmodel.load_state_dict(torch.load('/kaggle/input/classifier-final/best_model_Classifier_wcel71.pth'))\n\n# Switch to evaluation mode\nmodel.eval()\n\n# Initialize variables for calculating test loss and accuracy\ntest_loss = 0.0\ncorrect_test = 0\ntotal_test = 0\nall_labels = []\nall_predictions = []\n\nwith torch.no_grad():\n    for batch_images, batch_segmentation_masks, batch_labels in tqdm(test_loader, desc=\"Evaluating\", leave=False):\n        # Move data to the GPU if available\n        batch_images = batch_images.to(device, dtype=torch.float32)\n        batch_labels = batch_labels.to(device, dtype=torch.float32)\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# Assuming batch_images has shape (batch_size, num_frames, num_channels, height, width)\n#                 batch_images = batch_images.repeat(4, 3, 1, 1, 1)  # Repeat the single channel three times\n#                 batch_segmentation_masks = batch_segmentation_masks.repeat(4, 3, 1, 1, 1)\n\n#                 newbatch_images = batch_images[:, :3, ...].contiguous()\n#                 newbatch_segmentation_masks = batch_segmentation_masks[:, :3, ...].contiguous()\n        newbatch_images = batch_images\n#         newbatch_segmentation_masks = batch_segmentation_masks\n\n        # Forward pass\n        classification_outputs, _ = model(newbatch_images, None)  # No need for segmentation in the test phase\n\n        # Apply sigmoid activation to the classification outputs\n        classification_outputs = torch.sigmoid(classification_outputs)\n        weights = torch.stack([weight_calculate(labels) for labels in batch_labels]).to(device)\n\n        # Calculate test loss using your defined criterion (focal_loss)\n        weighted_loss = weighted_cross_entropy(classification_outputs, batch_labels, weights)\n        test_loss += weighted_loss.item()\n\n        # Calculate accuracy for each class separately (similar to training)\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        # Calculate overall accuracy for this batch\n        batch_accuracy = sum(accuracies) / num_classes_classification\n        correct_test += batch_accuracy\n        total_test += 1\n\n# Calculate and print average test accuracy and loss\navg_test_accuracy = correct_test / total_test\navg_test_loss = test_loss / len(test_loader)\nprint(\"Test Accuracy: {:.4f} | Test Loss: {:.4f}\".format(avg_test_accuracy, avg_test_loss))\n","metadata":{"execution":{"iopub.status.busy":"2024-04-29T02:23:38.083054Z","iopub.execute_input":"2024-04-29T02:23:38.083572Z","iopub.status.idle":"2024-04-29T02:25:19.903847Z","shell.execute_reply.started":"2024-04-29T02:23:38.083537Z","shell.execute_reply":"2024-04-29T02:25:19.902523Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tqdm import tqdm\nimport torch\nimport pandas as pd\nimport numpy as np\n\n# Define your test data loader here\ntest_data = pd.read_csv('/kaggle/input/data-divided/exp_test.csv')\n\ntest_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False, num_workers=num_workers)\n\n# Instantiate your model\nmodel = MultiLabel3DAttentionModel((num_classes_classification), num_classes_segmentation)\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nmodel.to(device)\n\n# Load the saved model checkpoint\nmodel.load_state_dict(torch.load('/kaggle/input/classifier-final/best_model_Classifier_wcel71.pth'))\n\n# Switch to evaluation mode\nmodel.eval()\n\nall_actual_labels = []\nall_predicted_labels = []\n\nwith torch.no_grad():\n    for batch_images, batch_segmentation_masks, batch_labels in tqdm(test_loader):\n        # Move data to the GPU if available\n        batch_images = batch_images.to(device, dtype=torch.float32)\n        batch_labels = batch_labels.to(device, dtype=torch.float32)\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# Assuming batch_images has shape (batch_size, num_frames, num_channels, height, width)\n#                 batch_images = batch_images.repeat(4, 3, 1, 1, 1)  # Repeat the single channel three times\n#                 batch_segmentation_masks = batch_segmentation_masks.repeat(4, 3, 1, 1, 1)\n\n#                 newbatch_images = batch_images[:, :3, ...].contiguous()\n#                 newbatch_segmentation_masks = batch_segmentation_masks[:, :3, ...].contiguous()\n        newbatch_images = batch_images\n#         newbatch_segmentation_masks = batch_segmentation_masks\n\n        # Forward pass\n        classification_outputs, _ = model(newbatch_images, None)  # No need for segmentation in the test phase\n\n        # Apply sigmoid activation to the classification outputs\n        classification_outputs = torch.sigmoid(classification_outputs)\n\n        # Append actual and predicted labels for this batch\n        all_actual_labels.append(batch_labels.cpu().numpy())\n#         print(all_actual_labels)\n        all_predicted_labels.append(classification_outputs.cpu().numpy())\n#         print(all_predicted_labels)\n\n# Concatenate all actual and predicted labels\nall_actual_labels = np.concatenate(all_actual_labels, axis=0)\n# print(all_actual_labels)\nall_predicted_labels = np.concatenate(all_predicted_labels, axis=0)\n# print(all_predicted_labels)\n\n\n# Now, you can use all_actual_labels and all_predicted_labels to calculate various metrics:\n# e.g., precision, recall, F1-score, hamming loss, etc.\nfrom sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n\n# Assuming you have all_actual_labels and all_predicted_labels as numpy arrays\n\n# Calculate accuracy\n# Calculate precision, recall, and F1 score\n\nprecision = precision_score(all_actual_labels, (all_predicted_labels > 0.5).astype(int), average='micro')\nrecall = recall_score(all_actual_labels, (all_predicted_labels > 0.5).astype(int), average='micro')\nf1 = f1_score(all_actual_labels, (all_predicted_labels > 0.5).astype(int), average='micro')\n\nprint(\"Precision: {:.4f}\".format(precision))\nprint(\"Recall: {:.4f}\".format(recall))\nprint(\"F1 Score: {:.4f}\".format(f1))","metadata":{"execution":{"iopub.status.busy":"2024-04-29T02:25:19.905876Z","iopub.execute_input":"2024-04-29T02:25:19.906241Z","iopub.status.idle":"2024-04-29T02:26:36.158347Z","shell.execute_reply.started":"2024-04-29T02:25:19.906205Z","shell.execute_reply":"2024-04-29T02:26:36.157236Z"},"trusted":true},"execution_count":null,"outputs":[]}]}