{"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":"none","dataSources":[{"sourceId":52254,"databundleVersionId":6863140,"sourceType":"competition"},{"sourceId":6523471,"sourceType":"datasetVersion","datasetId":3771357},{"sourceId":6524344,"sourceType":"datasetVersion","datasetId":3771912}],"dockerImageVersionId":30674,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"pip install git+https://github.com/ZFTurbo/timm_3d","metadata":{"execution":{"iopub.status.busy":"2024-03-31T09:48:16.825365Z","iopub.execute_input":"2024-03-31T09:48:16.825966Z","iopub.status.idle":"2024-03-31T09:48:20.326824Z","shell.execute_reply.started":"2024-03-31T09:48:16.825934Z","shell.execute_reply":"2024-03-31T09:48:20.325336Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pip install timm-3d\n","metadata":{"execution":{"iopub.status.busy":"2024-03-31T09:48:20.331006Z","iopub.execute_input":"2024-03-31T09:48:20.331367Z","iopub.status.idle":"2024-03-31T09:48:33.769044Z","shell.execute_reply.started":"2024-03-31T09:48:20.331333Z","shell.execute_reply":"2024-03-31T09:48:33.767828Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\nfrom torchvision import transforms  # For data preprocessing (if needed)\nfrom timm_3d import create_model  # Assuming timm_3d is installed\n","metadata":{"execution":{"iopub.status.busy":"2024-03-31T09:48:33.770747Z","iopub.execute_input":"2024-03-31T09:48:33.771182Z","iopub.status.idle":"2024-03-31T09:48:41.133915Z","shell.execute_reply.started":"2024-03-31T09:48:33.771149Z","shell.execute_reply":"2024-03-31T09:48:41.133049Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import timm_3d\nimport torch\nimport torch.nn as nn\n\n# Create a VGG model (for example, using VGG11 architecture)\nvgg_model = create_model('densenet121', pretrained=True, num_classes=14)\n\n# Modify the last fully connected layer for 14 output classes\nnum_classes = 14\n\n\n# Shape of input (B, C, H, W, D). B - batch size, C - channels, H - height, W - width, D - depth\ninput_data = torch.randn(8, 3, 128, 128, 128)  # Adjust input shape as needed\noutput = vgg_model(input_data)\nprint(output)\n","metadata":{"execution":{"iopub.status.busy":"2024-03-31T09:48:41.135761Z","iopub.execute_input":"2024-03-31T09:48:41.136088Z","iopub.status.idle":"2024-03-31T09:56:09.460503Z","shell.execute_reply.started":"2024-03-31T09:48:41.136062Z","shell.execute_reply":"2024-03-31T09:56:09.459572Z"},"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\nimport numpy as np\nfrom sklearn import metrics\nfrom sklearn.metrics import precision_recall_fscore_support\nfrom sklearn.model_selection import train_test_split\nfrom scipy.ndimage import zoom\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import accuracy_score, precision_score\n# Create a function to move data to the device\ndef move_data_to_device(data, device):\n    return data.to(torch.float32).to(device)\n\nclass CustomDataset(Dataset):\n    def __init__(self, image_paths, labels, transform=None):\n        self.image_paths = image_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\n        # Load the 3D NIfTI image using nibabel\n        image = nib.load(image_path).get_fdata()\n\n        # Apply transformations if provided to the image\n        if self.transform:\n            image = self.transform(image)\n\n        label = torch.tensor(self.labels[idx], dtype=torch.float32)\n        \n        return image, label\n\nimport torch.nn.functional as F\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\ncsv_file = '/kaggle/input/abdominal-trauma-nii-csv/abdominal_trauma_nii.csv'  # Update with the correct path\nbatch_size = 4\nnum_workers = 4  # Number of CPU cores to use for data loading\nnum_classes = 14  # 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).head(4480)\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 is:\", data_length)\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# 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_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# print(\"train paths\", train_paths)\n\n\nval_paths = val_data['file_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# print(val_paths)\n\n\ntest_paths = test_data['file_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# print(test_paths)\n\n\n# Instantiate the datasets\ntrain_dataset = CustomDataset(train_paths, train_labels, transform=transform)\nprint('len of train_dataset', len(train_dataset))\nval_dataset = CustomDataset(val_paths, val_labels, transform=transform)\ntest_dataset = CustomDataset(test_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))\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\n# Instantiate the model with the appropriate number of classes for classification\nin_channels = 3  # Input channels (e.g., for grayscale images or volumes)\nnum_classes_classification = 14  # Number of classes for classification\nmodel_class = create_model('vgg11', pretrained=True, num_classes=num_classes_classification)\n\n# Count the number of parameters\ntotal_params_class = sum(p.numel() for p in model_class.parameters())\nprint(f\"Total Trainable Parameters for Classification: {total_params_class}\")\n\n# Define loss function and optimizer\nclass_criterion = nn.CrossEntropyLoss()  # Binary Cross-Entropy loss for classification\nclass_optimizer = optim.Adam(model_class.parameters(), lr=0.001)\n\n# Training loop\n# Training loop\nclass_labels = ['bowel', 'extravasation', 'kidney', 'liver', 'spleen', 'any_injury']\nclass WeightedCrossEntropyLoss(nn.Module):\n    def __init__(self, weight=None):\n        super().__init__()\n        self.weight = weight\n\n    def forward(self, input, target):\n        return nn.functional.cross_entropy(input, target, weight=self.weight)\n\n# Calculate weights based on class frequencies (example)\nclass_counts = train_data[['bowel_healthy', 'bowel_injury', 'extravasation_healthy',\n                          'extravasation_injury', 'kidney_healthy', 'kidney_low',\n                          'kidney_high', 'liver_healthy', 'liver_low', 'liver_high',\n                          'spleen_healthy', 'spleen_low', 'spleen_high', 'any_injury']].sum(axis=0)\n\nweights = 1 / torch.tensor(class_counts, dtype=torch.float)\n\n# Instantiate the loss function\ncriterion = class_criterion = nn.CrossEntropyLoss()\n# Load checkpoint if available\ncheckpoint_path = '/kaggle/input/hybrid250epoch/denseNet_epoch_50 (1).pth'  # Provide the path to your checkpoint\nif os.path.exists(checkpoint_path):\n    checkpoint = torch.load(checkpoint_path)\n    model_state_dict = checkpoint['model_state_dict']\n    \n    # Filter out keys that are missing from the current model's state_dict\n    model_state_dict = {k: v for k, v in model_state_dict.items() if k in model_class.state_dict()}\n    \n    # Load the filtered state_dict\n    model_class.load_state_dict(model_state_dict, strict=False)\n    \n    # Create a new optimizer with the current configuration\n    class_optimizer = optim.Adam(model_class.parameters(), lr=0.001)  # Adjust the optimizer configuration as needed\n    \n    epoch = checkpoint['epoch']\n    loss = checkpoint['loss']\n    print(f\"Checkpoint loaded. Resuming from epoch {epoch}\")\n    print(\"loss from checkpoint is: \",loss)\n    print(\"epoch from checkpoint is: \",epoch)\n    \n\n# Training loop\nnum_epochs = 1\nfor epoch in range(num_epochs):\n    model_class.train()\n    running_loss = 0.0\n    correct_train = 0\n    total_train = 0\n    batch_number=0\n    all_predicted_labels = []\n    all_batch_labels = []\n    batch_loss=[]\n    model_class = model_class.to(device)\n    for batch_images, batch_labels in train_loader:\n        batch_number=batch_number+1\n        print(batch_number)\n        # Move data to the GPU if available\n        batch_images = batch_images.to(torch.float32).to(device)\n        batch_labels = batch_labels.to(torch.float32).to(device)\n        print(batch_labels.shape)\n#         print(batch_labels)\n\n        # Assuming batch_images has dimensions [batch_size, depth, height, width]\n        batch_size, depth, height, width = batch_images.size()\n\n        # Reshape the tensor to include the channel dimension\n        batch_images = batch_images.view(batch_size, 1, depth, height, width)\n\n        # Repeat the channel dimension 3 times\n        batch_images = batch_images.expand(batch_size, 3, depth, height, width)\n        batch_images = batch_images.to(device)\n        # Forward pass for classification\n        classification_outputs = model_class(batch_images)\n#         print(classification_outputs.shape, \"before sigmoid\")\n#         print(classification_outputs)\n        # Apply sigmoid activation to the classification outputs\n        batch_labels = batch_labels.to(classification_outputs.device)\n        # Calculate binary cross-entropy loss for each class separately\n        class_loss = criterion(classification_outputs, batch_labels)\n        \n        class_optimizer.zero_grad()\n        class_loss.backward()\n        class_optimizer.step()\n        \n        classification_outputs = torch.sigmoid(classification_outputs)\n#         print(classification_outputs.shape, \"after sigmoid\")\n#         print(classification_outputs)\n        \n        # Calculate accuracy and precision\n        predicted_labels = (classification_outputs > 0.5).float()\n#         print(\"predicted labels\",  predicted_labels)\n        all_predicted_labels.append(predicted_labels.cpu().numpy())\n        all_batch_labels.append(batch_labels.cpu().numpy())\n        y_true = batch_labels.flatten()\n        y_pred = predicted_labels.flatten()\n#         true_positives = (predicted_labels * batch_labels).sum(dim=0)\n#         false_positives = ((1 - batch_labels) * predicted_labels).sum(dim=0)\n#         false_negatives = (batch_labels * (1 - predicted_labels)).sum(dim=0)\n#         true_negatives = ((1 - batch_labels) * (1 - predicted_labels)).sum(dim=0)\n#         accuracy = (true_positives + true_negatives) / (true_positives + true_negatives + false_positives + false_negatives)\n#         precision = true_positives / (true_positives + false_positives)\n        \n        accuracy = metrics.accuracy_score(y_true, y_pred)\n        print(\"Batch Classification Loss:\", class_loss.item())\n        batch_loss.append(class_loss.item())\n#         print(\"precision\",precision)\n        print(\"Batch accuracy\",accuracy)\n    \n            # Flatten arrays for binary classification metrics\n    all_batch_labels = np.concatenate(all_batch_labels, axis=0)\n    all_predicted_labels = np.concatenate(all_predicted_labels, axis=0)\n    y_true = all_batch_labels.flatten()\n    y_pred = all_predicted_labels.flatten()\n   \n\n    precision = metrics.precision_score(y_true, y_pred, average='binary')\n    accuracy = metrics.accuracy_score(y_true, y_pred)\n    print(\"loss is :\", sum(batch_loss)/len(batch_loss))\n    print(\"Epoch\", epoch)\n    print(f'Precision: {precision:.4f}')\n    print(f'Accuracy: {accuracy:.4f}')\n    \n    \n    torch.save({\n            'epoch': epoch,\n            'model_state_dict': model_class.state_dict(),\n            'optimizer_state_dict': class_optimizer.state_dict(),\n            'loss': class_loss.item()\n            # Add any other information you want to save\n        }, f'/kaggle/working/denseNet_epoch_{epoch}.pth')\n\n#     Validation loop    \nwith torch.no_grad():\n        model_class.eval()\n        all_predicted_labels = []\n        all_batch_labels = []\n        model_class = model_class.to(device)\n        for batch_images, batch_labels in val_loader:\n            batch_images = batch_images.to(torch.float32).to(device)\n            batch_labels = batch_labels.to(torch.float32).to(device)\n\n            # Assuming batch_images has dimensions [batch_size, depth, height, width]\n            batch_size, depth, height, width = batch_images.size()\n\n            # Reshape the tensor to include the channel dimension\n            batch_images = batch_images.view(batch_size, 1, depth, height, width)\n\n            # Repeat the channel dimension 3 times\n            batch_images = batch_images.expand(batch_size, 3, depth, height, width)\n            batch_images = batch_images.to(device)\n            classification_outputs = model_class(batch_images)\n            classification_outputs = torch.sigmoid(classification_outputs)\n\n            predicted_labels = (classification_outputs > 0.5).float()\n\n            all_predicted_labels.append(predicted_labels.cpu().numpy())\n            all_batch_labels.append(batch_labels.cpu().numpy())\n        \n        # Flatten arrays for binary classification metrics\n        all_batch_labels = np.concatenate(all_batch_labels, axis=0)\n        all_predicted_labels = np.concatenate(all_predicted_labels, axis=0)\n\n        y_true = all_batch_labels.flatten()\n        y_pred = all_predicted_labels.flatten()\n\n        # Precision\n        precision = metrics.precision_score(y_true, y_pred, average='binary')\n\n\n        # Accuracy\n        accuracy = metrics.accuracy_score(y_true, y_pred)\n\n        \n        print(\"Validation Results: \")\n        print(f'Precision: {precision:.4f}')\n        print(f'Accuracy: {accuracy:.4f}')\n    # Testing loop\nwith torch.no_grad():\n        model_class.eval()\n        all_predicted_labels = []\n        all_batch_labels = []\n        model_class = model_class.to(device)\n        for batch_images, batch_labels in test_loader:\n            batch_images = batch_images.to(torch.float32).to(device)\n            batch_labels = batch_labels.to(torch.float32).to(device)\n\n            # Assuming batch_images has dimensions [batch_size, depth, height, width]\n            batch_size, depth, height, width = batch_images.size()\n\n            # Reshape the tensor to include the channel dimension\n            batch_images = batch_images.view(batch_size, 1, depth, height, width)\n    \n            # Repeat the channel dimension 3 times\n            batch_images = batch_images.expand(batch_size, 3, depth, height, width)\n            batch_images = batch_images.to(device)\n            classification_outputs = model_class(batch_images)\n            classification_outputs = torch.sigmoid(classification_outputs)\n\n            predicted_labels = (classification_outputs > 0.5).float()\n\n            all_predicted_labels.append(predicted_labels.cpu().numpy())\n            all_batch_labels.append(batch_labels.cpu().numpy())\n        \n        # Flatten arrays for binary classification metrics\n        all_batch_labels = np.concatenate(all_batch_labels, axis=0)\n        all_predicted_labels = np.concatenate(all_predicted_labels, axis=0)\n\n        y_true = all_batch_labels.flatten()\n        y_pred = all_predicted_labels.flatten()\n        print(\"y_true shape \",y_true.shape)\n        print(\"y_pred_shape\" ,y_pred.shape)\n        # Precision, Recall, F1 Score\n        precision = metrics.precision_score(y_true, y_pred, average='binary')\n        recall = metrics.recall_score(y_true, y_pred, average='binary')\n        f1_score = metrics.f1_score(y_true, y_pred, average='binary')\n\n        # Accuracy\n        accuracy = metrics.accuracy_score(y_true, y_pred)\n\n        # AUC\n        fpr, tpr, thresholds = metrics.roc_curve(y_true, y_pred)\n        auc = metrics.auc(fpr, tpr)\n        \n        print(\"Testing Results: \")\n        print(f'Precision: {precision:.4f}')\n        print(f'Recall: {recall:.4f}')\n        print(f'F1 Score: {f1_score:.4f}')\n        print(f'Accuracy: {accuracy:.4f}')\n        print(f'AUC: {auc:.4f}')\n        \n        # Reshape predictions for multilabel classification metrics\n        y_true_multilabel = all_batch_labels.T\n        y_pred_multilabel = all_predicted_labels.T\n        print(y_true_multilabel.shape)\n        print(y_pred_multilabel.shape)\n        y_true_1 = y_true_multilabel[:, -1]\n        y_pred_1 = y_pred_multilabel[:, -1]\n# Compute precision, recall, F1 score, and support for each class\n        precision, recall, f1_score, support = precision_recall_fscore_support(y_true_multilabel, y_pred_multilabel, average=None)\n\n# Print scores for each class\n        for i in range(num_classes):\n            class_accuracy = accuracy_score(y_true_multilabel[i, :], y_pred_multilabel[i, :])\n            class_precision = precision_score(y_true_multilabel[i, :], y_pred_multilabel[i, :])\n\n            print(f\"   Class {i + 1}:\")\n            print(f\"      Accuracy: {class_accuracy:.4f}\")\n            print(f\"      Precision: {class_precision:.4f}\")\n","metadata":{"execution":{"iopub.status.busy":"2024-03-31T09:56:09.462171Z","iopub.execute_input":"2024-03-31T09:56:09.462834Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}