{"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":"gpu","dataSources":[{"sourceId":52254,"databundleVersionId":6863140,"sourceType":"competition"},{"sourceId":8013889,"sourceType":"datasetVersion","datasetId":4721340}],"dockerImageVersionId":30673,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import pandas as pd\nimport torch\nimport torch.nn as nn\nfrom torchvision import models","metadata":{"execution":{"iopub.status.busy":"2024-04-03T00:07:39.215904Z","iopub.execute_input":"2024-04-03T00:07:39.216236Z","iopub.status.idle":"2024-04-03T00:07:46.828067Z","shell.execute_reply.started":"2024-04-03T00:07:39.21621Z","shell.execute_reply":"2024-04-03T00:07:46.827193Z"},"trusted":true},"execution_count":1,"outputs":[]},{"cell_type":"code","source":"class CNNModel(nn.Module):\n    def __init__(self):\n        super().__init__()\n        \n        self.input = nn.Conv2d(4, 3, kernel_size=3) #USED\n        self.features = models.efficientnet_b0(pretrained=False).features #USED\n        self.avgpool = models.efficientnet_b0(pretrained=False).avgpool #USED\n        \n        self.bowel = nn.Linear(1280, 1) #USED\n        self.extravasation = nn.Linear(1280, 1) #USED\n        self.kidney = nn.Linear(1280, 3) #USED\n        self.liver = nn.Linear(1280, 3)  #USED\n        self.spleen = nn.Linear(1280, 3) #USED\n    \n    #--Override-on forward----------(is there function called \"forward\" called in train_function ?)\n    def forward(self, x):\n        # extract features\n        x = self.input(x)\n        x = self.features(x)\n        x = self.avgpool(x)\n        x = torch.flatten(x, 1)\n        \n        # output logits\n        bowel = self.bowel(x)\n        extravasation = self.extravasation(x)\n        kidney = self.kidney(x)\n        liver = self.liver(x)\n        spleen = self.spleen(x)\n        \n        return bowel, extravasation, kidney, liver, spleen","metadata":{"execution":{"iopub.status.busy":"2024-04-03T00:11:30.789276Z","iopub.execute_input":"2024-04-03T00:11:30.789708Z","iopub.status.idle":"2024-04-03T00:11:30.799716Z","shell.execute_reply.started":"2024-04-03T00:11:30.789671Z","shell.execute_reply":"2024-04-03T00:11:30.798572Z"},"trusted":true},"execution_count":4,"outputs":[]},{"cell_type":"code","source":"columns = ['Patient', 'Bowel', 'Extravasation', 'Kidney', 'Kidney_low', 'Kidney_high', 'Liver', 'Liver_low', 'Liver_high', 'Spleen','Spleen_low', 'Spleen_high']\npredictions_df = pd.DataFrame(columns=columns)\n\nmodel = CNNModel().to('cuda')\n\n# Load the saved weights\nmodel_path = '/kaggle/input/model-zoo/stdi_efficientnet_b0_'\nmodel.load_state_dict(torch.load(model_path))\nmodel.eval()\n\nfor batch_data in (val_dataloader_4):\n    inputs = batch_data['image'].to('cuda')\n    bowel = batch_data['bowel'].to('cuda')\n    extravasation = batch_data['extravasation'].to('cuda')\n    liver = batch_data['liver'].to('cuda')\n    kidney = batch_data['kidney'].to('cuda')\n    spleen = batch_data['spleen'].to('cuda')\n    \n    patients = batch_data['patient'].tolist()\n\n    b, e, k, l, s = model(inputs)\n\n    bowel_probs = torch.sigmoid(b.detach())\n    extravasation_probs = torch.sigmoid(e.detach())\n    \n    kidney_probs = F.softmax(k.detach(), dim=1)\n    liver_probs = F.softmax(l.detach(), dim=1)\n    spleen_probs = F.softmax(s.detach(), dim=1)\n  \n    bowel_list=bowel_probs.tolist()\n    extravasation_list = extravasation_probs.tolist()\n    kidney_list = kidney_probs.tolist()\n    liver_list = liver_probs.tolist()\n    spleen_list = spleen_probs.tolist()\n    \n    result_dicts=[]\n    for i in range(len(patients)):\n        result_dict = {\n            'Patient': patients[i],\n            'Bowel': bowel_list[i][0],\n            'Extravasation': extravasation_list[i][0],\n            'Kidney': kidney_list[i][0],\n            'Kidney_low': kidney_list[i][1],\n            'Kidney_high': kidney_list[i][2],\n            'Liver': liver_list[i][0],\n            'Liver_low': liver_list[i][1],\n            'Liver_high': liver_list[i][2],\n            'Spleen': spleen_list[i][0],\n            'Spleen_low': spleen_list[i][1],\n            'Spleen_high': spleen_list[i][2]}\n        result_dicts.append(result_dict)\n        #predictions_df = predictions_df.append(result_dict, ignore_index=True)\n# Concatenate the list of result dictionaries into a DataFrame\n\n    result_dfs = [pd.DataFrame(result_dict, index=[0]) for result_dict in result_dicts]\n\n# Concatenate the existing DataFrame with the new results\n    predictions_df = pd.concat([predictions_df] + result_dfs, ignore_index=True)\n        \n\n","metadata":{"execution":{"iopub.status.busy":"2024-04-03T00:11:56.315005Z","iopub.execute_input":"2024-04-03T00:11:56.315392Z","iopub.status.idle":"2024-04-03T00:11:57.056531Z","shell.execute_reply.started":"2024-04-03T00:11:56.315363Z","shell.execute_reply":"2024-04-03T00:11:57.055254Z"},"trusted":true},"execution_count":6,"outputs":[{"name":"stderr","text":"/opt/conda/lib/python3.10/site-packages/torchvision/models/_utils.py:208: UserWarning: The parameter 'pretrained' is deprecated since 0.13 and may be removed in the future, please use 'weights' instead.\n  warnings.warn(\n/opt/conda/lib/python3.10/site-packages/torchvision/models/_utils.py:223: UserWarning: Arguments other than a weight enum or `None` for 'weights' are deprecated since 0.13 and may be removed in the future. The current behavior is equivalent to passing `weights=None`.\n  warnings.warn(msg)\n","output_type":"stream"},{"traceback":["\u001b[0;31m---------------------------------------------------------------------------\u001b[0m","\u001b[0;31mNameError\u001b[0m                                 Traceback (most recent call last)","Cell \u001b[0;32mIn[6], line 11\u001b[0m\n\u001b[1;32m      8\u001b[0m model\u001b[38;5;241m.\u001b[39mload_state_dict(torch\u001b[38;5;241m.\u001b[39mload(model_path))\n\u001b[1;32m      9\u001b[0m model\u001b[38;5;241m.\u001b[39meval()\n\u001b[0;32m---> 11\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m batch_data \u001b[38;5;129;01min\u001b[39;00m (\u001b[43mval_dataloader_4\u001b[49m):\n\u001b[1;32m     12\u001b[0m     inputs \u001b[38;5;241m=\u001b[39m batch_data[\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mimage\u001b[39m\u001b[38;5;124m'\u001b[39m]\u001b[38;5;241m.\u001b[39mto(\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mcuda\u001b[39m\u001b[38;5;124m'\u001b[39m)\n\u001b[1;32m     13\u001b[0m     bowel \u001b[38;5;241m=\u001b[39m batch_data[\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mbowel\u001b[39m\u001b[38;5;124m'\u001b[39m]\u001b[38;5;241m.\u001b[39mto(\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mcuda\u001b[39m\u001b[38;5;124m'\u001b[39m)\n","\u001b[0;31mNameError\u001b[0m: name 'val_dataloader_4' is not defined"],"ename":"NameError","evalue":"name 'val_dataloader_4' is not defined","output_type":"error"}]},{"cell_type":"code","source":"# Save the dataframe to a CSV file\npredictions_df.to_csv('/kaggle/working/submission.csv', index=False)","metadata":{},"execution_count":null,"outputs":[]}]}