{"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 /kaggle/input/rsna-2023-whl/{pydicom-2.4.2-py3-none-any.whl,pylibjpeg-1.4.0-py3-none-any.whl,einops-0.6.1-py3-none-any.whl}","metadata":{"execution":{"iopub.status.busy":"2023-08-29T05:07:30.923335Z","iopub.execute_input":"2023-08-29T05:07:30.923825Z","iopub.status.idle":"2023-08-29T05:08:06.679633Z","shell.execute_reply.started":"2023-08-29T05:07:30.923779Z","shell.execute_reply":"2023-08-29T05:08:06.678451Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport os\nimport pydicom\nimport cv2\n# import einops","metadata":{"execution":{"iopub.status.busy":"2023-08-29T05:08:06.68268Z","iopub.execute_input":"2023-08-29T05:08:06.683094Z","iopub.status.idle":"2023-08-29T05:08:06.998738Z","shell.execute_reply.started":"2023-08-29T05:08:06.683031Z","shell.execute_reply":"2023-08-29T05:08:06.99779Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# define a fucntion to read dicom file and return it's pixel\ndef read_dicom(dicom_file):\n    try:\n        dcm = pydicom.dcmread(dicom_file) # read dciom files\n\n        pixel_array = dcm.pixel_array\n\n        if dcm.PixelRepresentation == 1:\n            bit_shift = dcm.BitsAllocated - dcm.BitsStored\n            dtype = pixel_array.dtype \n            pixel_array = (pixel_array << bit_shift).astype(dtype) >>  bit_shift\n    #         pixel_array = pydicom.pixel_data_handlers.util.apply_modality_lut(new_array, dcm)\n\n        intercept = float(dcm.RescaleIntercept)\n        slope = float(dcm.RescaleSlope)\n        center = int(dcm.WindowCenter)\n        width = int(dcm.WindowWidth)\n        low = center - width / 2\n        high = center + width / 2    \n\n        pixel_array = (pixel_array * slope) + intercept\n        pixel_array = np.clip(pixel_array, low, high)\n        pixel_array = (pixel_array - pixel_array.min()) / (pixel_array.max() - pixel_array.min() + 1e-6)\n\n        if dcm.PhotometricInterpretation == \"MONOCHROME1\":\n            pixel_array = 1 - pixel_array\n\n        return (pixel_array * 255).astype(np.uint8)\n    except:\n        return np.zeros((384, 384)).astype(np.uint8)","metadata":{"execution":{"iopub.status.busy":"2023-08-29T05:08:07.00035Z","iopub.execute_input":"2023-08-29T05:08:07.000705Z","iopub.status.idle":"2023-08-29T05:08:07.009784Z","shell.execute_reply.started":"2023-08-29T05:08:07.00067Z","shell.execute_reply":"2023-08-29T05:08:07.008911Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import sys\nimport timm\nfrom torch import nn\n# from model import FeatureExtractor\n\nN_EVAL = 28","metadata":{"execution":{"iopub.status.busy":"2023-08-29T05:08:07.012967Z","iopub.execute_input":"2023-08-29T05:08:07.013745Z","iopub.status.idle":"2023-08-29T05:08:11.483059Z","shell.execute_reply.started":"2023-08-29T05:08:07.013712Z","shell.execute_reply":"2023-08-29T05:08:11.482099Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\nfrom torch import nn\nimport timm\nimport torch.nn.functional as F\nfrom timm.layers.adaptive_avgmax_pool import SelectAdaptivePool2d\n\nclass FeatureExtractor(nn.Module):\n    def __init__(self, back_bone, device_id):\n        super().__init__()\n        self.model = timm.create_model(back_bone, pretrained=False, num_classes=2)\n        self.IMAGENET_DEFAULT_MEAN = torch.tensor([0.485, 0.456, 0.406]).to(device_id)\n        self.IMAGENET_DEFAULT_STD = torch.tensor([0.229, 0.224, 0.225]).to(device_id)\n\n        self.global_pool = SelectAdaptivePool2d(\n            pool_type=\"avg\",\n            flatten=True\n        )\n\n    def forward(self, x):\n        x = x.transpose(1, 2).transpose(1, 3).contiguous()\n        x = x/255.0\n        x = (x - self.IMAGENET_DEFAULT_MEAN[None,:, None, None])/self.IMAGENET_DEFAULT_STD[None,:, None, None]\n        x = self.model(x)\n        return x\n    \n    def forward_features(self, x):\n        x = x.transpose(1, 2).transpose(1, 3).contiguous()\n        x = x/255.0\n        x = (x - self.IMAGENET_DEFAULT_MEAN[None,:, None, None])/self.IMAGENET_DEFAULT_STD[None,:, None, None]\n        x = self.model.forward_features(x)\n        x = self.global_pool(x)\n        return x","metadata":{"execution":{"iopub.status.busy":"2023-08-29T05:08:11.48465Z","iopub.execute_input":"2023-08-29T05:08:11.485021Z","iopub.status.idle":"2023-08-29T05:08:11.495697Z","shell.execute_reply.started":"2023-08-29T05:08:11.484983Z","shell.execute_reply":"2023-08-29T05:08:11.494717Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def load_old_weight(model, weight_path):\n    pretrained_dict = torch.load(weight_path)\n    model_dict = model.state_dict()\n    pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict and v.size() == model_dict[k].size()}\n    model.load_state_dict(pretrained_dict)\n    return model\n\ndef extract_feature_worker(q_in, q_out):\n    bowel_model_paths = [\"/kaggle/input/rsnatraumaextractor/checkpoint_f1_best_ema.pt\"]\n    bowel_models = []\n    for bowel_model_path in bowel_model_paths:\n        bowel_model = FeatureExtractor(\"convnext_small.fb_in22k_ft_in1k_384\", \"cuda:0\")\n        bowel_model = load_old_weight(bowel_model, bowel_model_path)\n        bowel_model.to(\"cuda:0\")\n        bowel_model.eval()\n        bowel_models.append(bowel_model)\n    \n    extravasation_model_paths = [\"/kaggle/input/rsnatraumaextractor/extravasation_extractor.pt\"]\n    extravasation_models = []\n    for extravasation_model_path in extravasation_model_paths:\n        extravasation_model = FeatureExtractor(\"convnext_small.fb_in22k_ft_in1k_384\", \"cuda:0\")\n        extravasation_model = load_old_weight(extravasation_model, extravasation_model_path)\n        extravasation_model.to(\"cuda:0\")\n        extravasation_model.eval()\n        extravasation_models.append(extravasation_model)\n        \n    with torch.no_grad():\n        while True:\n            batch_queue = q_in.get()\n            if batch_queue is None:\n                q_out.put(None, block=True, timeout=None)\n                break\n\n            patient_id = batch_queue[\"patient_id\"]\n            series = batch_queue[\"series\"]\n            image_size = batch_queue[\"image_size\"]\n            \n            batch = torch.Tensor(np.array(batch_queue[\"batch\"]))\n#             print(\"Features: \", batch.shape)\n            batch = batch.to(\"cuda:0\").float()\n            bowel_ensemble_features = []\n            extravasation_ensemble_features = []\n            for i in range(len(bowel_models)):\n                bowel_features = bowel_models[i].forward_features(batch)\n                bowel_ensemble_features.append(bowel_features)\n            bowel_ensemble_features = torch.cat(bowel_ensemble_features, 1).detach().cpu().numpy()\n            for i in range(len(extravasation_models)):\n                extravasation_features = extravasation_models[i].forward_features(batch)\n                extravasation_ensemble_features.append(extravasation_features)\n            extravasation_ensemble_features = torch.cat(extravasation_ensemble_features, 1).detach().cpu().numpy()\n#             if patient_id == \"10004\" and series == \"51033\":\n#                 print(extravasation_ensemble_features[27])\n            features_queue = {\"patient_id\": patient_id, \"series\": series, \"image_size\": image_size, \n                              \"bowel_features\": bowel_ensemble_features, \"extravasation_features\": extravasation_ensemble_features}\n            q_out.put(features_queue, block=True, timeout=None)","metadata":{"execution":{"iopub.status.busy":"2023-08-29T05:08:11.497509Z","iopub.execute_input":"2023-08-29T05:08:11.497835Z","iopub.status.idle":"2023-08-29T05:08:11.514498Z","shell.execute_reply.started":"2023-08-29T05:08:11.497804Z","shell.execute_reply":"2023-08-29T05:08:11.513483Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!mkdir /kaggle/working/squeezeformer\n!cp -r /kaggle/input/squuezeformer/* /kaggle/working/squeezeformer","metadata":{"execution":{"iopub.status.busy":"2023-08-29T05:08:11.515718Z","iopub.execute_input":"2023-08-29T05:08:11.516674Z","iopub.status.idle":"2023-08-29T05:08:13.461089Z","shell.execute_reply.started":"2023-08-29T05:08:11.516642Z","shell.execute_reply":"2023-08-29T05:08:13.459797Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import sys\nfrom squeezeformer.model import Squeezeformer\nclass Predictor(nn.Module):\n    def __init__(self, device_id):\n        super().__init__()\n        self.n_features = 768\n        self.n_eval = 28\n        self.device_id = device_id\n        \n        self.encoder = Squeezeformer(\n            num_classes=2,\n            input_dim=self.n_features,\n        )\n        self.fc = nn.Linear(8, 2)\n\n    def forward(self, x):\n        input_lengths = torch.full((x.shape[0], ), self.n_eval).to(self.device_id)\n        outputs, output_lengths = self.encoder(x, input_lengths)\n        outputs = outputs.reshape((x.shape[0], -1))\n        outputs = self.fc(outputs)\n        return outputs","metadata":{"execution":{"iopub.status.busy":"2023-08-29T05:08:13.465005Z","iopub.execute_input":"2023-08-29T05:08:13.465843Z","iopub.status.idle":"2023-08-29T05:08:13.484457Z","shell.execute_reply.started":"2023-08-29T05:08:13.465799Z","shell.execute_reply":"2023-08-29T05:08:13.48357Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def preprocess_predictor(features):\n    total_features = features.shape[0]\n    series_stack = np.zeros((N_EVAL, 768)).astype(\"float32\")\n    step = N_EVAL // total_features\n    n_remain = N_EVAL - total_features*step\n    k = 0\n    t = 0\n    while k < N_EVAL:\n        if n_remain > 0:\n            for j in range(step + 1):\n                series_stack[k] = features[t]\n                k += 1\n            t += 1\n            n_remain -= 1\n        else:\n            for j in range(step):\n                series_stack[k] = features[t]\n                k += 1\n            t += 1\n    return series_stack\n\ndef load_models(model_paths):\n    models = []\n    for model_path in model_paths:\n        model = Predictor(\"cuda:0\")\n        model = load_old_weight(model, model_path)\n        model = model.cuda()\n        model.eval()\n        models.append(model)\n    return models\n\ndef predict(models, series_stack):\n    batch = torch.Tensor(series_stack).to(\"cuda:0\").float()\n    batch = torch.unsqueeze(batch, 0)\n    ensemble_probs = torch.zeros((batch.shape[0], 2)).cuda()\n    for i in range(len(models)):\n        logits = models[i](batch)\n        probs = torch.nn.Softmax(dim=1)(logits)\n        ensemble_probs += probs\n    ensemble_probs /= len(models)\n    ensemble_probs = ensemble_probs.detach().cpu().numpy()\n    \n    return ensemble_probs[0]\n\ndef predict_worker(q_in, d):\n    bowel_model_paths = [\"/kaggle/input/rsnatraumapredictor/fold0.pt\",\n                  \"/kaggle/input/rsnatraumapredictor/fold1.pt\",\n                  \"/kaggle/input/rsnatraumapredictor/fold2.pt\",\n                  \"/kaggle/input/rsnatraumapredictor/fold3.pt\"]\n    bowel_models = load_models(bowel_model_paths)\n    extravasation_model_paths = [\"/kaggle/input/rsnatraumapredictor/extravasation_fold0.pt\",\n                                \"/kaggle/input/rsnatraumapredictor/extravasation_fold1.pt\",\n                                \"/kaggle/input/rsnatraumapredictor/extravasation_fold2.pt\",\n                                \"/kaggle/input/rsnatraumapredictor/extravasation_fold3.pt\"]\n    extravasation_models = load_models(extravasation_model_paths)\n    with torch.no_grad():\n        while True:\n            batch_queue = q_in.get()\n            if batch_queue is None:\n                break\n            patient_id = str(batch_queue[\"patient_id\"])\n            series = batch_queue[\"series\"]\n            image_size = batch_queue[\"image_size\"]\n            bowel_features = np.array(batch_queue[\"bowel_features\"])\n            extravasation_features = np.array(batch_queue[\"extravasation_features\"])\n\n            bowel_series_stack = preprocess_predictor(bowel_features)\n            extravasation_series_stack = preprocess_predictor(extravasation_features)\n        \n            bowel_ensemble_probs = predict(bowel_models, bowel_series_stack)\n            extravasation_ensemble_probs = predict(extravasation_models, extravasation_series_stack)\n           \n            ensemble_probs = np.concatenate([bowel_ensemble_probs, extravasation_ensemble_probs])\n#             if patient_id == \"10004\":\n#                 print(ensemble_probs)\n            d[patient_id] = d[patient_id] + ensemble_probs","metadata":{"execution":{"iopub.status.busy":"2023-08-29T05:08:13.48587Z","iopub.execute_input":"2023-08-29T05:08:13.48626Z","iopub.status.idle":"2023-08-29T05:08:13.501977Z","shell.execute_reply.started":"2023-08-29T05:08:13.486226Z","shell.execute_reply":"2023-08-29T05:08:13.501089Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def dcm_to_png(images, i, step, number_of_train_images, size):\n    if i == number_of_train_images - 2:\n        file_0 = images[i]\n        file_1 = images[i+1]\n        file_2 = images[i+1]\n    elif i == number_of_train_images - 1:\n        file_0 = images[i]\n        file_1 = images[i]\n        file_2 = images[i]\n    else:\n        file_0 = images[i]\n        file_1 = images[i+1]\n        file_2 = images[i+2]\n\n    dicom_pixel_0 = read_dicom(dicom_file=file_0) # read dicom image pixels\n    dicom_pixel_1 = read_dicom(dicom_file=file_1)\n    dicom_pixel_2 = read_dicom(dicom_file=file_2)\n    \n    resized_img_0 = cv2.resize(np.expand_dims(dicom_pixel_0, 2),dsize=(size,size)) # resize it to specific size\n    resized_img_1 = cv2.resize(np.expand_dims(dicom_pixel_1, 2),dsize=(size,size)) # resize it to specific size\n    resized_img_2 = cv2.resize(np.expand_dims(dicom_pixel_2, 2),dsize=(size,size)) # resize it to specific size\n    resized_img_25d = np.stack([resized_img_2, resized_img_1, resized_img_0], axis=2)\n    \n    return resized_img_25d","metadata":{"execution":{"iopub.status.busy":"2023-08-29T05:08:13.505149Z","iopub.execute_input":"2023-08-29T05:08:13.505432Z","iopub.status.idle":"2023-08-29T05:08:13.517138Z","shell.execute_reply.started":"2023-08-29T05:08:13.505407Z","shell.execute_reply":"2023-08-29T05:08:13.516183Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"DEBUG = False\nif DEBUG == True:\n    test_path = \"/kaggle/input/rsna-2023-abdominal-trauma-detection/train_images\"\nelse:\n    test_path = \"/kaggle/input/rsna-2023-abdominal-trauma-detection/test_images\"\n\ndef read_worker(q_in_extract_feature, patient_id_list):\n    for patient_id in patient_id_list:\n        patient_path = os.path.join(test_path, patient_id)\n        for series in os.listdir(patient_path):\n            series_path = os.path.join(patient_path, series)\n            images = os.listdir(series_path)\n            images = [imagename.replace('.dcm', '') for imagename in images]\n            images = list(map(int, images))\n            images = sorted(images)\n            \n            image_paths = []\n            for imagename in images:\n                image_path = os.path.join(series_path, str(imagename) + \".dcm\")\n                image_paths.append(image_path)\n#             if patient_id == \"10004\":\n#                 print(image_paths)\n            total_images = len(image_paths)\n            step = (total_images//3) // N_EVAL*3\n            \n            if step == 0:\n                step = 1\n            series_batch = []\n            for image_size in IMAGE_SIZES:\n                series_batch.append([])\n#             print(patient_id, image_paths)\n            for j, image_size in enumerate(IMAGE_SIZES):\n                c = 0\n                for i in range(0, total_images, step):\n                    series_batch[j].append(dcm_to_png(image_paths, i, step, total_images, image_size))\n#                     if patient_id == \"10004\" and series == \"51033\" and \"1124.dcm\" in image_paths[i]:\n# #                         print(series, image_paths[i])\n# #                         and series == \"51033\" and \"1124.jpg\" in image_paths[i]:\n#                         print(\"HEHE: \", c)\n                    c += 1\n                    if c >= N_EVAL:\n                        break\n            series_batch = np.array(series_batch)\n#             print(\"HEHE: \", series_batch.shape)\n            \n            for j, image_size in enumerate(IMAGE_SIZES):\n                batch_queue = {\"patient_id\": patient_id, \"series\": series, \"image_size\": image_size, \"batch\": series_batch[j]}\n                q_in_extract_feature.put(batch_queue, block=True, timeout=None)","metadata":{"execution":{"iopub.status.busy":"2023-08-29T05:08:13.518688Z","iopub.execute_input":"2023-08-29T05:08:13.519109Z","iopub.status.idle":"2023-08-29T05:08:13.531296Z","shell.execute_reply.started":"2023-08-29T05:08:13.519077Z","shell.execute_reply":"2023-08-29T05:08:13.530356Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nimport multiprocessing as mp\nfrom joblib import Parallel, delayed\n\nfrom multiprocessing import Process, Queue, Manager, Lock\nimport pandas as pd\nimport glob\n\n\nq_in_extract_feature = Queue(maxsize=10)\nq_out_extract_feature = Queue(maxsize=10)\nmanager = Manager()\nd = manager.dict()\nq = Queue()\n\nif DEBUG == True:\n    val_df = pd.read_csv(\"/kaggle/input/rsnatraumapredictor/val_extravasation_fold0.csv\")\n    patient_id_list = []\n    labels = []\n    for index, row in val_df.iterrows():\n        if row[\"extravasation_injury\"] == 1:\n            patient_id_list.append(str(row[\"patient_id\"]))\n            labels.append(1)\n        else:\n            patient_id_list.append(str(row[\"patient_id\"]))\n            labels.append(0)\nelse:\n    patient_id_list = os.listdir(test_path)\n    # patient_id_list = [10065, 10917, 10929, 11335, 11925, 12332, 12951, 12958, 13403, 13719, 13741, 15876, 18697, 19742, 19763, 19914, 20951, 27196, 29407, 32011, 32442, 32541, 33, 35022, 35331, 38427, 40754, 4093, 41050, 42266, 43, 43059, 4353, 45303, 51520, 53348, 53395, 53475, 53581, 53908, 54183, 54371, 54525, 55888, 56441, 56690, 56981, 57563, 57887, 58236, 58465, 58863, 60744, 61399, 61742, 61834, 63113, 63665, 64194, 65456, 7482, 7642, 820, 8684]\n    # patient_id_list = [10004]\n    patient_id_list = list(map(str, patient_id_list))\n\n\nfor patient_id in patient_id_list:\n    d[patient_id] = np.zeros((4, ))\n\nextract_feature_process = Process(target=extract_feature_worker, args=(q_in_extract_feature, q_out_extract_feature, ))\nextract_feature_process.start()\n\npredict_process = Process(target=predict_worker, args=(q_out_extract_feature, d, ))\npredict_process.start()\n\nIMAGE_SIZES = [384]\n\ntotal_patient = len(patient_id_list)\nread_0_process = Process(target=read_worker, args=(q_in_extract_feature, patient_id_list[:total_patient//3], ))\nread_1_process = Process(target=read_worker, args=(q_in_extract_feature, patient_id_list[total_patient//3:2*total_patient//3], ))\nread_2_process = Process(target=read_worker, args=(q_in_extract_feature, patient_id_list[2*total_patient//3:], ))\nread_0_process.start()\nread_1_process.start()\nread_2_process.start()\n\nread_0_process.join()\nread_1_process.join()\nread_2_process.join()\nq_in_extract_feature.put(None, block=True, timeout=None)\n\nextract_feature_process.join()\npredict_process.join()\n\nfor patient_id in patient_id_list:\n    patient_path = os.path.join(test_path, patient_id)\n    num_series = len(os.listdir(patient_path))\n    d[patient_id] = d[patient_id] / (num_series*len(IMAGE_SIZES))\n\n# print(d)","metadata":{"execution":{"iopub.status.busy":"2023-08-29T05:09:06.635224Z","iopub.execute_input":"2023-08-29T05:09:06.635592Z","iopub.status.idle":"2023-08-29T05:11:41.820175Z","shell.execute_reply.started":"2023-08-29T05:09:06.635561Z","shell.execute_reply":"2023-08-29T05:11:41.818804Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn import metrics\n# EVAL\nif DEBUG == True:\n    sample_weight = []\n    probs = []\n    for patient_id in patient_id_list:\n        v = d[patient_id]\n        probs.append((v[2], v[3]))\n    probs = np.array(probs)\n    for i in range(len(labels)):\n        if(labels[i] == 0):\n            sample_weight.append(1)\n        else:\n            sample_weight.append(6)\n    logloss = metrics.log_loss(labels, probs, sample_weight=sample_weight)\n    print(\"Eval log loss: \", logloss)","metadata":{"execution":{"iopub.status.busy":"2023-08-29T05:08:33.832847Z","iopub.execute_input":"2023-08-29T05:08:33.833277Z","iopub.status.idle":"2023-08-29T05:08:33.839209Z","shell.execute_reply.started":"2023-08-29T05:08:33.833226Z","shell.execute_reply":"2023-08-29T05:08:33.837965Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# print(d)\n# print(d['26501'])\n# print(d['32627'])\n# print(d['33834'])\n# print(d['43024'])\n# print(d['29128'])","metadata":{"execution":{"iopub.status.busy":"2023-08-29T05:08:33.841134Z","iopub.execute_input":"2023-08-29T05:08:33.841834Z","iopub.status.idle":"2023-08-29T05:08:33.851001Z","shell.execute_reply.started":"2023-08-29T05:08:33.8418Z","shell.execute_reply":"2023-08-29T05:08:33.849959Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Only requires the training target data. \nsf_1 = 6\nsf_2 = 4\nsf_4 = 6\nsf_6 = 14\n\n# Group by different sample weights\nscale_by_1 = ['bowel_injury']\nscale_by_2 = ['kidney_low','liver_low','spleen_low']\nscale_by_4 = ['kidney_high','liver_high','spleen_high']\nscale_by_6 = ['extravasation_injury']\n\ny_train = pd.read_csv('/kaggle/input/rsna-2023-abdominal-trauma-detection/train.csv')\n# List of Targets\nInjuries = ['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# Load submission template \nsubmission = pd.read_csv('/kaggle/input/rsna-2023-abdominal-trauma-detection/sample_submission.csv')\n\n# Set output to mean of training data\nsubmission[Injuries] = y_train[Injuries].mean().tolist()\nbowel_healthy_results = []\nbowel_injury_results = []\nextravasation_healthy_results = []\nextravasation_injury_results = []\nfor index, row in submission.iterrows():\n    patient_id = str(int(row[\"patient_id\"]))\n    v = d[patient_id]\n    if v[1] >= 0.7:\n        bowel_healthy_results.append(0)\n        bowel_injury_results.append(1)\n    else:\n        bowel_healthy_results.append(v[0])\n        bowel_injury_results.append(v[1])\n    extravasation_healthy_results.append(v[2])\n    extravasation_injury_results.append(v[3])\nsubmission['bowel_healthy'] = bowel_healthy_results\nsubmission['bowel_injury'] = bowel_injury_results\nsubmission['extravasation_healthy'] = extravasation_healthy_results\nsubmission['extravasation_injury'] = extravasation_injury_results\n\n# Scale each category by desired scale factor\n# submission[scale_by_1] *=sf_1\nsubmission[scale_by_2] *=sf_2\nsubmission[scale_by_4] *=sf_4\nsubmission[scale_by_6] *=sf_6","metadata":{"execution":{"iopub.status.busy":"2023-08-29T05:08:33.852864Z","iopub.execute_input":"2023-08-29T05:08:33.853738Z","iopub.status.idle":"2023-08-29T05:08:34.552902Z","shell.execute_reply.started":"2023-08-29T05:08:33.853653Z","shell.execute_reply":"2023-08-29T05:08:34.551333Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission.to_csv('submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2023-08-29T05:08:34.553926Z","iopub.status.idle":"2023-08-29T05:08:34.554598Z","shell.execute_reply.started":"2023-08-29T05:08:34.554342Z","shell.execute_reply":"2023-08-29T05:08:34.55437Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission.head()","metadata":{"execution":{"iopub.status.busy":"2023-08-29T05:08:34.556667Z","iopub.status.idle":"2023-08-29T05:08:34.557145Z","shell.execute_reply.started":"2023-08-29T05:08:34.556892Z","shell.execute_reply":"2023-08-29T05:08:34.556913Z"},"trusted":true},"execution_count":null,"outputs":[]}],"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"}}