{"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":"nvidiaTeslaT4","dataSources":[{"sourceId":52254,"databundleVersionId":6863140,"sourceType":"competition"},{"sourceId":6376425,"sourceType":"datasetVersion","datasetId":3674352},{"sourceId":7189970,"sourceType":"datasetVersion","datasetId":4141765},{"sourceId":7196952,"sourceType":"datasetVersion","datasetId":4123452}],"dockerImageVersionId":30626,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"!pip install nibabel numpy pydicom tqdm --no-index --find-links=file:///kaggle/input/packages","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-12-14T10:42:01.227769Z","iopub.execute_input":"2023-12-14T10:42:01.228361Z","iopub.status.idle":"2023-12-14T10:42:15.807062Z","shell.execute_reply.started":"2023-12-14T10:42:01.228315Z","shell.execute_reply":"2023-12-14T10:42:15.805576Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# !pip install pydicom==2.4.2\n# !pip install --upgrade nibabel\n# !pip install nibabel==3.2.1\n# !pip install nibabel numpy scipy","metadata":{"execution":{"iopub.status.busy":"2023-12-14T10:42:15.811292Z","iopub.execute_input":"2023-12-14T10:42:15.811779Z","iopub.status.idle":"2023-12-14T10:43:17.497783Z","shell.execute_reply.started":"2023-12-14T10:42:15.811738Z","shell.execute_reply":"2023-12-14T10:43:17.496216Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install torch --no-index --find-links=file:///kaggle/input/packages","metadata":{"execution":{"iopub.status.busy":"2023-12-14T10:43:17.499591Z","iopub.execute_input":"2023-12-14T10:43:17.500029Z","iopub.status.idle":"2023-12-14T10:43:32.202916Z","shell.execute_reply.started":"2023-12-14T10:43:17.499989Z","shell.execute_reply":"2023-12-14T10:43:32.201407Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# import os\n# import shutil\n# import pydicom\n# import nibabel as nib\n# import numpy as np\n# import zipfile\n# import pandas as pd\n# from scipy.ndimage import zoom\n# from sklearn.model_selection import train_test_split\n\n\n# # Function to resize NIfTI data\n# def 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# # Function to convert DICOM to resized NIfTI\n# def dicom_to_resized_nii(input_folder, output_folder, desired_shape,patientname):\n#     dicom_files = [os.path.join(input_folder, file) for file in os.listdir(input_folder) if file.endswith('.dcm')]\n\n#     if not dicom_files:\n#         return\n\n#     dicom_files.sort(key=lambda file: pydicom.dcmread(file).ImagePositionPatient[-1])\n\n#     ds = pydicom.dcmread(dicom_files[0])\n#     pixel_spacing = ds.PixelSpacing\n#     slice_thickness = ds.SliceThickness\n\n#     affine = np.eye(4)\n#     affine[0, 0] = pixel_spacing[1]\n#     affine[1, 1] = pixel_spacing[0]\n#     affine[2, 2] = slice_thickness\n\n#     volume = np.zeros((ds.Rows, ds.Columns, len(dicom_files)), dtype=ds.pixel_array.dtype)\n\n#     for i, dicom_file in enumerate(dicom_files):\n#         ds = pydicom.dcmread(dicom_file)\n#         volume[:, :, i] = ds.pixel_array\n\n#     nii_image = nib.Nifti1Image(volume, affine=affine)\n\n#     resized_data = resize_nifti(nii_image.get_fdata(), desired_shape)\n#     resized_affine = nii_image.affine\n\n#     resized_nii_image = nib.Nifti1Image(resized_data, affine=resized_affine)\n\n#     if not os.path.exists(output_folder):\n#         os.makedirs(output_folder)\n#     output_nii_path = os.path.join(output_folder, f\"{os.path.basename(patientname)}.nii.gz\")\n#     nib.save(resized_nii_image, output_nii_path)\n\n#     print(f\"Converted, resized, and saved {len(dicom_files)} DICOM slices to a resized NIfTI image: {output_nii_path}\")\n#     return os.path.basename(patientname)\n\n# root_folder = \"/kaggle/input/rsna-2023-abdominal-trauma-detection/test_images\"\n# output_folder = \"/kaggle/working/output_nii_images\"\n# desired_shape = (128,128,128)\n\n# # Load or create the CSV file\n# csv_file_path = \"/kaggle/input/abdominal-trauma-records-2/conversion_records.csv\"\n# if os.path.exists(csv_file_path):\n#     conversion_records = pd.read_csv(csv_file_path)\n#     # Save the updated CSV file to kaggle/working directory\n#     csv_file_path_new = \"/kaggle/working/conversion_records.csv\"\n#     conversion_records.to_csv(csv_file_path_new, index=False)\n# else:\n#     conversion_records = pd.DataFrame(columns=[\"patient_id\"])\n\n# # Loop through subfolders and convert DICOM to NIfTI\n# count = 0\n# for subfolder in os.listdir(root_folder):\n#     subfolder_path = os.path.join(root_folder, subfolder)\n    \n#     if os.path.isdir(subfolder_path):\n#         for onemore_subfolder in os.listdir(subfolder_path):\n#             onemore_subfolder_path = os.path.join(subfolder_path, onemore_subfolder)\n#             patient_id = subfolder+\"_\"+onemore_subfolder\n           \n\n#             if os.path.isdir(onemore_subfolder_path) and patient_id not in conversion_records[\"patient_id\"].values:\n#                     converted_patient_id = dicom_to_resized_nii(onemore_subfolder_path, output_folder, desired_shape,patient_id)\n#                     if converted_patient_id:\n#                         conversion_records.loc[len(conversion_records)] = [converted_patient_id]\n#                         count += 1\n#                         if count == 150:\n#                             break\n#             if count == 150:\n#                     break\n#         if count == 150:\n#                 break\n                        \n# # Save the updated CSV file\n# conversion_records.to_csv(csv_file_path_new, index=False)\n\n# # Create a ZIP file containing the converted NIfTI images\n# # zip_filename = \"/kaggle/working/output_nii_images.zip\"\n# # with zipfile.ZipFile(zip_filename, 'w', zipfile.ZIP_DEFLATED) as zipf:\n# #     for root, _, files in os.walk(output_folder):\n# #         for file in files:\n# #             file_path = os.path.join(root, file)\n# #             zipf.write(file_path, os.path.relpath(file_path, output_folder))\n# #             os.remove(file_path)  # Delete the file after adding to the ZIP folder\n\n# # # Close the ZIP file\n# # zipf.close()\n\n# print(\"ZIP file closed.\")\n\n# print(\"Conversion, resizing, CSV update, and ZIP creation completed.\")\n","metadata":{"execution":{"iopub.status.busy":"2023-12-14T10:43:32.206275Z","iopub.execute_input":"2023-12-14T10:43:32.206959Z","iopub.status.idle":"2023-12-14T10:43:39.10103Z","shell.execute_reply.started":"2023-12-14T10:43:32.206899Z","shell.execute_reply":"2023-12-14T10:43:39.099707Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# import pandas as pd\n# import torch\n# import os\n# from torch.utils.data import DataLoader\n# from tqdm import tqdm\n# import nibabel as nib  # Assuming you have NIfTI files and using nibabel to load them\n\n# device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n# # Create a DataFrame for predictions\n# columns = [\n#     \"patient_id\",\n#     \"bowel_healthy\", \"bowel_injury\",\n#     \"extravasation_healthy\", \"extravasation_injury\",\n#     \"kidney_healthy\", \"kidney_low\", \"kidney_high\",\n#     \"liver_healthy\", \"liver_low\", \"liver_high\",\n#     \"spleen_healthy\", \"spleen_low\", \"spleen_high\"\n# ]\n\n# submission_df = pd.DataFrame(columns=columns)\n\n# # Set the path to the test folder\n# test_folder = \"/kaggle/working/output_nii_images\"\n\n# # Load the model\n# # Load the model, specifying map_location='cpu'\n# model_path = '/kaggle/input/custom3dvit-model-weights/vit_abdominal (2).pth'\n# checkpoint = torch.load(model_path, map_location=torch.device('cpu'))\n\n# # Create an instance of the model class\n# model = get_model()\n\n# # If the checkpoint is an instance of the model, load it directly\n# if isinstance(checkpoint, Custom3DViTModel):\n#     model = checkpoint\n# else:\n#     # If the checkpoint includes the entire model, extract the state_dict\n#     if 'state_dict' in checkpoint:\n#         model.load_state_dict(checkpoint['state_dict'])\n#     else:\n#         model.load_state_dict(checkpoint)\n\n# # Make sure to set the model to evaluation mode after loading\n# model.eval()\n\n\n\n\n# # Iterate through the files in the test folder\n# for file_name in os.listdir(test_folder):\n#     if file_name.endswith(\".nii\"):\n#         file_path = os.path.join(test_folder, file_name)\n#         names = file_name.split(\"_\")\n#         patient_id = names[0]\n#         print(patient_id)\n#         # Load the NIfTI image using nibabel\n#         nifti_img = nib.load(file_path)\n#         img_data = nifti_img.get_fdata()\n\n#         # Preprocess the image data as needed (e.g., normalization)\n\n#         # Convert NumPy array to PyTorch tensor\n#         img_tensor = torch.from_numpy(img_data).unsqueeze(0).unsqueeze(0).float()\n\n#         # Assuming mask is a 3D NumPy array with size (128, 128, 128), create a PyTorch tensor\n#         mask_tensor = torch.zeros((1, 1, 128, 128, 128), dtype=torch.float32)\n\n#         with torch.no_grad():\n#             img_tensor = img_tensor.to(device)\n#             mask_tensor = mask_tensor.to(device)\n\n#             # Assuming model is your PyTorch model\n#             model_output = model(img_tensor, mask_tensor)\n\n#         # Convert logits to probabilities using sigmoid activation\n#         probabilities = torch.sigmoid(model_output).cpu().numpy().squeeze()\n        \n#         # Process the model output as needed (e.g., save results, post-processing)\n\n#         # Example: Save the result as a NIfTI file\n#         result_nifti = nib.Nifti1Image(probabilities, nifti_img.affine)\n#         result_file_path = os.path.join(\"/kaggle/working/results\", file_name.replace(\".nii\", \"_result.nii\"))\n#         nib.save(result_nifti, result_file_path)\n\n#         print(f\"Processed: {file_name}, Result saved to {result_file_path}\")\n\n#         # Append the predictions to the submission DataFrame\n#         submission_df = submission_df.append({\n#             \"patient_id\": patient_id,\n#             \"bowel_healthy\": probabilities[0],\n#             \"bowel_injury\": probabilities[1],\n#             \"extravasation_healthy\": probabilities[2],\n#             \"extravasation_injury\": probabilities[3],\n#             \"kidney_healthy\": probabilities[4],\n#             \"kidney_low\": probabilities[5],\n#             \"kidney_high\": probabilities[6],\n#             \"liver_healthy\": probabilities[7],\n#             \"liver_low\": probabilities[8],\n#             \"liver_high\": probabilities[9],\n#             \"spleen_healthy\": probabilities[10],\n#             \"spleen_low\": probabilities[11],\n#             \"spleen_high\": probabilities[12]\n#         }, ignore_index=True)\n\n# # Save the submission DataFrame to a CSV file\n# submission_file_path = \"/kaggle/working/submission.csv\"\n# submission_df.to_csv(submission_file_path, index=False)\n\n# print(f\"Submission file created: {submission_file_path}\")\n# #wokring one parital","metadata":{"execution":{"iopub.status.busy":"2023-12-14T10:43:39.104872Z","iopub.execute_input":"2023-12-14T10:43:39.106134Z","iopub.status.idle":"2023-12-14T10:43:39.791308Z","shell.execute_reply.started":"2023-12-14T10:43:39.10608Z","shell.execute_reply":"2023-12-14T10:43:39.790138Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn import Transformer\n\ndef linear(input, weight, bias=None):\n    if bias is not None:\n        return torch.matmul(input, weight.t()) + bias\n    else:\n        return torch.matmul(input, weight.t())\n\ndef layer_norm(input, normalized_shape, weight=None, bias=None, eps=1e-5):\n    mean = input.mean(dim=-1, keepdim=True)\n    var = input.var(dim=-1, unbiased=False, keepdim=True)\n    \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    input = (input - mean) / torch.sqrt(var + eps)\n    \n    if weight is not None:\n        input = input * weight\n    if bias is not None:\n        input = input + bias\n    \n    return input\n\nclass Transformer3DClassifier(nn.Module):\n    def __init__(self, input_shape, num_classes, num_layers=6, d_model=16, nhead=8, dim_feedforward=2048, dropout=0.1):\n        super(Transformer3DClassifier, self).__init__()\n        \n        self.d_model = d_model\n        d_in = input_shape[0] * input_shape[1] * input_shape[2]\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        x = x.view(x.size(0), -1)\n        x = self.embedding(x)\n        x = x.unsqueeze(0)\n        tgt = torch.zeros(1, x.size(1), self.d_model).to(x.device)\n        output = self.transformer(x, tgt)\n        logits = self.fc(output)\n        logits = logits.unsqueeze(0)\n        return logits\n\nclass Custom3DViTModel(nn.Module):\n    def __init__(self, in_channels, num_classes, num_classes_segmentation, batch_size):\n        super(Custom3DViTModel, self).__init__()\n        self.batch_size = batch_size\n        self.num_classes = num_classes\n        \n        self.vit_backbone = Transformer3DClassifier(\n            input_shape=(128, 128, 128),\n            num_classes=num_classes\n        )\n\n        self.classification_head = nn.Sequential(\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        x = x.to(device)\n        if segmentation_mask is not None:\n            segmentation_mask = segmentation_mask.to(device)\n\n        features = self.vit_backbone(x)\n        features = features.to(device)\n        print(features.size())\n        classification_output = features.view(-1, self.num_classes)\n        \n        segmentation_output = self.segmentation_head(x)\n        segmentation_output = nn.functional.interpolate(segmentation_output, size=segmentation_mask.shape[2:], mode='trilinear')\n        segmentation_output = segmentation_output * segmentation_mask\n\n        return classification_output, segmentation_output\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nbatch_size = 32\n\ndef get_model():\n    return Custom3DViTModel(3, 14, 5, batch_size)\n\ndef run(index):\n    model = get_model()\n    model = model.to(device)\n\n    batch_images = torch.randn(32, 1, 128, 128, 128)\n    batch_segmentation_masks = torch.randn(32, 1, 128, 128, 128)\n\n    batch_images = batch_images.to(device)\n    batch_segmentation_masks = batch_segmentation_masks.to(device)\n\n    classification_outputs, segmentation_outputs = model(batch_images, batch_segmentation_masks)\n\nif __name__ == '__main__':\n    run(0)","metadata":{"execution":{"iopub.status.busy":"2023-12-14T10:43:39.792681Z","iopub.execute_input":"2023-12-14T10:43:39.793019Z","iopub.status.idle":"2023-12-14T10:43:49.970911Z","shell.execute_reply.started":"2023-12-14T10:43:39.792989Z","shell.execute_reply":"2023-12-14T10:43:49.969854Z"},"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 scipy.ndimage import zoom\nimport pydicom\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# Function to convert DICOM to resized NIfTI\ndef dicom_to_resized_nii(input_folder, output_folder, desired_shape, patientname):\n    dicom_files = [os.path.join(input_folder, file) for file in os.listdir(input_folder) if file.endswith('.dcm')]\n\n    if not dicom_files:\n        return\n\n    dicom_files.sort(key=lambda file: pydicom.dcmread(file).ImagePositionPatient[-1])\n\n    ds = pydicom.dcmread(dicom_files[0])\n    pixel_spacing = ds.PixelSpacing\n    slice_thickness = ds.SliceThickness\n\n    affine = np.eye(4)\n    affine[0, 0] = pixel_spacing[1]\n    affine[1, 1] = pixel_spacing[0]\n    affine[2, 2] = slice_thickness\n\n    volume = np.zeros((ds.Rows, ds.Columns, len(dicom_files)), dtype=ds.pixel_array.dtype)\n\n    for i, dicom_file in enumerate(dicom_files):\n        ds = pydicom.dcmread(dicom_file)\n        volume[:, :, i] = ds.pixel_array\n\n    nii_image = nib.Nifti1Image(volume, affine=affine)\n\n    # Inside dicom_to_resized_nii function, after resizing\n    resized_data = resize_nifti(nii_image.get_fdata(), desired_shape)\n\n    # Check for NaN values and handle them\n    if np.isnan(resized_data).any():\n        resized_data[np.isnan(resized_data)] = 0\n\n    resized_affine = nii_image.affine\n\n    resized_nii_image = nib.Nifti1Image(resized_data, affine=resized_affine)\n\n    if not os.path.exists(output_folder):\n        os.makedirs(output_folder)\n    output_nii_path = os.path.join(output_folder, f\"{os.path.basename(patientname)}.nii.gz\")\n    nib.save(resized_nii_image, output_nii_path)\n\n    print(f\"Converted, resized, and saved {len(dicom_files)} DICOM slices to a resized NIfTI image: {output_nii_path}\")\n    return os.path.basename(patientname)\n\nroot_folder = \"/kaggle/input/rsna-2023-abdominal-trauma-detection/test_images\"\noutput_folder = \"/kaggle/working/output_nii_images\"\ndesired_shape = (128, 128, 128)\n\n# Load or create the CSV file\ncsv_file_path = \"/kaggle/input/abdominal-trauma-records-2/conversion_records.csv\"\nif os.path.exists(csv_file_path):\n    conversion_records = pd.read_csv(csv_file_path)\n    # Save the updated CSV file to kaggle/working directory\n    csv_file_path_new = \"/kaggle/working/conversion_records.csv\"\n    conversion_records.to_csv(csv_file_path_new, index=False)\nelse:\n    conversion_records = pd.DataFrame(columns=[\"patient_id\"])\n\n# Loop through subfolders and convert DICOM to NIfTI\nfor subfolder in os.listdir(root_folder):\n    subfolder_path = os.path.join(root_folder, subfolder)\n\n    if os.path.isdir(subfolder_path):\n        # Assuming each patient folder contains 2D DICOM slices\n        patient_name = dicom_to_resized_nii(subfolder_path, output_folder, desired_shape, subfolder)\n\n        if patient_name:\n            conversion_records.loc[len(conversion_records)] = [patient_name]\n\n# Save the updated CSV file\nconversion_records.to_csv(csv_file_path_new, index=False)\n\nprint(\"Conversion, resizing, CSV update, and ZIP creation completed.\")\n\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, transform=None):\n        self.image_paths = image_paths\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        return image\n\n# Assuming your model is already defined and loaded\n# model = ...\nmodel = torch.load('/kaggle/input/custom3dvit-model-weights/vit_abdominal (2).pth', map_location=device)\nmodel.eval()\n\n# Load the list of resized NIfTI paths\nnifti_paths = [os.path.join(output_folder, file) for file in os.listdir(output_folder) if file.endswith('.nii.gz')]\npatient_ids = [os.path.splitext(os.path.basename(file))[0].split('_')[0] for file in os.listdir(output_folder) if file.endswith('.nii.gz')]\n\n# Instantiate the test dataset\ntest_dataset = CustomDataset(nifti_paths, transform=None)  # You can add a transform if needed\n\n# Instantiate the data loader\nbatch_size = 1\nnum_workers = 4\ntest_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False, num_workers=num_workers)\n\n# Move the model to the device (e.g., GPU)\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nmodel = model.to(device)\n\n# Set the model to evaluation mode\nmodel.eval()\n\n# Loop through the test data and make predictions\npredictions = []\n\nwith torch.no_grad():\n    for batch_images in test_loader:\n        batch_images = batch_images.to(torch.float32).to(device)\n\n        # Check for NaN values and handle them\n        if torch.isnan(batch_images).any():\n            batch_images[torch.isnan(batch_images)] = 0\n        # Assuming batch_images has shape (batch_size, num_channels, height, width, depth)\n        batch_images = batch_images.unsqueeze(0)  # Add a singleton dimension for batch\n\n        # Create a dummy segmentation mask (assuming your model requires it)\n        dummy_segmentation_mask = torch.zeros_like(batch_images)\n\n        # Forward pass\n        outputs, _ = model(batch_images, dummy_segmentation_mask)\n\n        # Apply sigmoid activation to the outputs\n        outputs = torch.sigmoid(outputs)\n\n        # Convert to numpy array and append to predictions list\n        predictions.append(outputs.cpu().numpy())\n\n# Concatenate the predictions along the batch dimension\nall_predictions = np.concatenate(predictions, axis=0)\n# After making predictions\nif np.isnan(all_predictions).any():\n    all_predictions[np.isnan(all_predictions)] = 0\n\n# Print or use the predictions as needed\nprint(all_predictions)\n\nclass_names = [\"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\"]\npredictions_df = pd.DataFrame(data=all_predictions, columns=class_names)\n\npredictions_df = predictions_df.iloc[:, :-1]\npredictions_df.insert(0, \"patient_id\", patient_ids)\n\n# Save the DataFrame to a CSV file\ncsv_output_path = \"/kaggle/working/submission.csv\"\npredictions_df.to_csv(csv_output_path, index=False)\n\nprint(f\"Predictions saved to: {csv_output_path}\")\n","metadata":{"execution":{"iopub.status.busy":"2023-12-14T10:43:49.972662Z","iopub.execute_input":"2023-12-14T10:43:49.973009Z","iopub.status.idle":"2023-12-14T10:43:50.847003Z","shell.execute_reply.started":"2023-12-14T10:43:49.972978Z","shell.execute_reply":"2023-12-14T10:43:50.845436Z"},"trusted":true},"execution_count":null,"outputs":[]}]}