{"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":[{"sourceType":"competition","sourceId":52254,"databundleVersionId":9674523},{"sourceType":"modelInstanceVersion","sourceId":992,"databundleVersionId":4905385,"modelInstanceId":846,"modelId":101},{"sourceType":"kernelVersion","sourceId":144565665},{"sourceType":"kernelVersion","sourceId":144629118}],"dockerImageVersionId":30559,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import os\nimport pydicom\n\nimport pandas as pd\nimport numpy as np\n\nimport torch\nimport torchvision\nfrom torch import nn\nimport torch.nn.functional as F\nfrom torch import optim\nfrom torchvision import transforms\n\nfrom torch.utils.data import Dataset, DataLoader\n\nimport matplotlib.pyplot as plt\n\nfrom joblib import Parallel, delayed\nimport sys\n\nfrom tqdm import tqdm","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2026-05-12T17:32:23.479244Z","iopub.execute_input":"2026-05-12T17:32:23.480065Z","iopub.status.idle":"2026-05-12T17:32:23.485264Z","shell.execute_reply.started":"2026-05-12T17:32:23.480036Z","shell.execute_reply":"2026-05-12T17:32:23.484452Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"SEED = 42\n\nnp.random.seed(SEED)\ntorch.manual_seed(SEED)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-12T17:32:23.486901Z","iopub.execute_input":"2026-05-12T17:32:23.487577Z","iopub.status.idle":"2026-05-12T17:32:23.502144Z","shell.execute_reply.started":"2026-05-12T17:32:23.487545Z","shell.execute_reply":"2026-05-12T17:32:23.501325Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-12T17:32:23.503196Z","iopub.execute_input":"2026-05-12T17:32:23.503489Z","iopub.status.idle":"2026-05-12T17:32:23.512624Z","shell.execute_reply.started":"2026-05-12T17:32:23.503452Z","shell.execute_reply":"2026-05-12T17:32:23.511902Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"TEST_ROOT = '/kaggle/input/rsna-2023-abdominal-trauma-detection/test_images'\nTEST_SERIES = '/kaggle/input/rsna-2023-abdominal-trauma-detection/test_series_meta.csv'\n\nVOLUME = (128, 64, 64)\n\nBATCH_SIZE = 32\n\nVOLUME = (128, 64, 64)\n\nWINDOW_STEP = 2\n# Odd Number Only\nWINDOW_WIDTH = 3\nPAD_ENDING = True\n\nSLICE_NUM = (128-1)//2 + 1\n\nTARGET_COLS  = [\n    \"bowel_injury\", \"extravasation_injury\",\n    \"kidney_healthy\", \"kidney_low\", \"kidney_high\",\n    \"liver_healthy\", \"liver_low\", \"liver_high\",\n    \"spleen_healthy\", \"spleen_low\", \"spleen_high\",\n]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-12T17:32:23.51475Z","iopub.execute_input":"2026-05-12T17:32:23.515087Z","iopub.status.idle":"2026-05-12T17:32:23.522586Z","shell.execute_reply.started":"2026-05-12T17:32:23.515067Z","shell.execute_reply":"2026-05-12T17:32:23.521946Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"SLICE_NUM","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-12T17:32:23.523466Z","iopub.execute_input":"2026-05-12T17:32:23.523794Z","iopub.status.idle":"2026-05-12T17:32:23.533699Z","shell.execute_reply.started":"2026-05-12T17:32:23.523774Z","shell.execute_reply":"2026-05-12T17:32:23.532831Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class Net(nn.Module):\n    \n    def __init__(self):\n        \n        super(Net, self).__init__()\n        \n        resnet = torchvision.models.resnet18()\n        self.backbone = nn.Sequential(*list(resnet.children())[:-1])\n        \n        self.ltsm = nn.LSTM(input_size=512, hidden_size=128, batch_first=True)\n        self.fc = nn.Linear(in_features=128*SLICE_NUM, out_features=11)\n    \n    def forward(self, x):\n        \n        batch_size = x.shape[0]\n        x = x.view(batch_size * SLICE_NUM, WINDOW_WIDTH, VOLUME[1], VOLUME[2])\n        x = self.backbone(x)\n        x = x.view(batch_size, SLICE_NUM, -1) \n        \n        x, _ = self.ltsm(x)\n        x = torch.flatten(x, start_dim=1)\n        \n        x = self.fc(x)\n        \n        return x","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-12T17:32:23.534659Z","iopub.execute_input":"2026-05-12T17:32:23.535137Z","iopub.status.idle":"2026-05-12T17:32:23.541604Z","shell.execute_reply.started":"2026-05-12T17:32:23.535115Z","shell.execute_reply":"2026-05-12T17:32:23.540851Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = Net().to(device)\nsum(p.numel() for p in model.parameters() if p.requires_grad)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-12T17:32:23.542543Z","iopub.execute_input":"2026-05-12T17:32:23.542777Z","iopub.status.idle":"2026-05-12T17:32:23.733453Z","shell.execute_reply.started":"2026-05-12T17:32:23.542758Z","shell.execute_reply":"2026-05-12T17:32:23.732502Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\n\nprint(os.listdir('/kaggle/input'))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-12T17:32:23.734454Z","iopub.execute_input":"2026-05-12T17:32:23.734928Z","iopub.status.idle":"2026-05-12T17:32:23.739501Z","shell.execute_reply.started":"2026-05-12T17:32:23.734904Z","shell.execute_reply":"2026-05-12T17:32:23.738524Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from torchvision.models import resnet18\n\nmodel = resnet18(weights=None)\nmodel = model.to(device)\n\nprint(\"MODEL LOADED\")\nprint(next(model.parameters()).device)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-12T17:32:23.740562Z","iopub.execute_input":"2026-05-12T17:32:23.7408Z","iopub.status.idle":"2026-05-12T17:32:23.918879Z","shell.execute_reply.started":"2026-05-12T17:32:23.74078Z","shell.execute_reply":"2026-05-12T17:32:23.918039Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch\n\nx = torch.randn(1, 3, 224, 224).to(device)\n\nwith torch.no_grad():\n    y = model(x)\n\nprint(y.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-12T17:32:23.921575Z","iopub.execute_input":"2026-05-12T17:32:23.921865Z","iopub.status.idle":"2026-05-12T17:32:23.933014Z","shell.execute_reply.started":"2026-05-12T17:32:23.921841Z","shell.execute_reply":"2026-05-12T17:32:23.93159Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\n\nprint(os.listdir('/kaggle/input/rsna-2023-abdominal-trauma-detection'))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-12T17:32:23.93445Z","iopub.execute_input":"2026-05-12T17:32:23.93487Z","iopub.status.idle":"2026-05-12T17:32:23.940523Z","shell.execute_reply.started":"2026-05-12T17:32:23.93483Z","shell.execute_reply":"2026-05-12T17:32:23.939632Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Cell 2  ← RUN THIS NOW\nimport os\n\nprint(os.listdir('/kaggle/input/rsna-2023-abdominal-trauma-detection'))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-12T17:32:23.941551Z","iopub.execute_input":"2026-05-12T17:32:23.941829Z","iopub.status.idle":"2026-05-12T17:32:23.949112Z","shell.execute_reply.started":"2026-05-12T17:32:23.941809Z","shell.execute_reply":"2026-05-12T17:32:23.948214Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(os.listdir('/kaggle/input/rsna-2023-abdominal-trauma-detection/train_images')[:5])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-12T17:32:23.950139Z","iopub.execute_input":"2026-05-12T17:32:23.950432Z","iopub.status.idle":"2026-05-12T17:32:23.961708Z","shell.execute_reply.started":"2026-05-12T17:32:23.950403Z","shell.execute_reply":"2026-05-12T17:32:23.960816Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"patient_path = '/kaggle/input/rsna-2023-abdominal-trauma-detection/train_images/26501'\n\nimport os\nprint(os.listdir(patient_path)[:5])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-12T17:32:23.962796Z","iopub.execute_input":"2026-05-12T17:32:23.963121Z","iopub.status.idle":"2026-05-12T17:32:23.968856Z","shell.execute_reply.started":"2026-05-12T17:32:23.963094Z","shell.execute_reply":"2026-05-12T17:32:23.967937Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"series_path = '/kaggle/input/rsna-2023-abdominal-trauma-detection/train_images/26501/22032'\n\nimport os\nprint(os.listdir(series_path)[:5])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-12T17:32:23.969899Z","iopub.execute_input":"2026-05-12T17:32:23.970206Z","iopub.status.idle":"2026-05-12T17:32:23.979357Z","shell.execute_reply.started":"2026-05-12T17:32:23.970179Z","shell.execute_reply":"2026-05-12T17:32:23.97843Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\n\ndef dicom_to_image(dcm):\n\n    # Extract pixel data\n    img = dcm.pixel_array.astype(np.float32)\n\n    # Apply DICOM scaling\n    intercept = dcm.get(\"RescaleIntercept\", 0)\n    slope = dcm.get(\"RescaleSlope\", 1)\n\n    img = img * slope + intercept\n\n    # Normalize to 0-1\n    img = (img - img.min()) / (img.max() - img.min() + 1e-6)\n\n    return img","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-12T17:36:53.151716Z","iopub.execute_input":"2026-05-12T17:36:53.152533Z","iopub.status.idle":"2026-05-12T17:36:53.157423Z","shell.execute_reply.started":"2026-05-12T17:36:53.152502Z","shell.execute_reply":"2026-05-12T17:36:53.156538Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import cv2\nimg_resized = cv2.resize(img, (224, 224))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-12T17:41:04.019768Z","iopub.execute_input":"2026-05-12T17:41:04.02061Z","iopub.status.idle":"2026-05-12T17:41:04.024907Z","shell.execute_reply.started":"2026-05-12T17:41:04.020577Z","shell.execute_reply":"2026-05-12T17:41:04.024108Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pydicom\nimport matplotlib.pyplot as plt\n\ndcm_path = '/kaggle/input/rsna-2023-abdominal-trauma-detection/train_images/26501/22032/12.dcm'\n\ndcm = pydicom.dcmread(dcm_path)\n\nimg = dicom_to_image(dcm)\n\nprint(img.shape)\nprint(img.min(), img.max())\n\nplt.figure(figsize=(6,6))\nplt.imshow(img, cmap='gray')\nplt.title(\"Processed DICOM\")\nplt.axis('off')\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-12T17:41:07.514391Z","iopub.execute_input":"2026-05-12T17:41:07.514843Z","iopub.status.idle":"2026-05-12T17:41:07.673691Z","shell.execute_reply.started":"2026-05-12T17:41:07.514814Z","shell.execute_reply":"2026-05-12T17:41:07.672901Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import cv2\nimport torch\nimport numpy as np\n\nimg_resized = cv2.resize(img, (224, 224))\n\nimg_3ch = np.stack([img_resized]*3, axis=-1)\n\ntensor = torch.tensor(img_3ch).permute(2,0,1).float()\n\ntensor = tensor.unsqueeze(0).to(device)\n\nprint(tensor.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-12T17:32:24.010994Z","iopub.status.idle":"2026-05-12T17:32:24.011373Z","shell.execute_reply.started":"2026-05-12T17:32:24.011154Z","shell.execute_reply":"2026-05-12T17:32:24.011186Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.eval()\n\nwith torch.no_grad():\n    output = model(tensor)\n\nprint(output.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-12T17:32:24.013186Z","iopub.status.idle":"2026-05-12T17:32:24.013592Z","shell.execute_reply.started":"2026-05-12T17:32:24.013376Z","shell.execute_reply":"2026-05-12T17:32:24.013395Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pred_class = output.argmax(dim=1).item()\n\nprint(\"Predicted class:\", pred_class)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-12T17:32:24.014793Z","iopub.status.idle":"2026-05-12T17:32:24.015208Z","shell.execute_reply.started":"2026-05-12T17:32:24.015002Z","shell.execute_reply":"2026-05-12T17:32:24.015023Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# normalize image for visualization\nimg_vis = (img * 255).astype(np.uint8)\n\n# create enhanced version\nenhanced = cv2.equalizeHist(img_vis)\n\n# optional sharpening\nkernel = np.array([\n    [0, -1, 0],\n    [-1, 5,-1],\n    [0, -1, 0]\n])\n\nenhanced = cv2.filter2D(enhanced, -1, kernel)\n\n# side-by-side plot\nfig, ax = plt.subplots(1, 2, figsize=(12,6))\n\nax[0].imshow(img_vis, cmap='gray')\nax[0].set_title(\"Original CT Scan\")\nax[0].axis('off')\n\nax[1].imshow(enhanced, cmap='inferno')\nax[1].set_title(f\"AI-Enhanced Output | Predicted Class: {pred_class}\")\nax[1].axis('off')\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-12T17:32:24.016783Z","iopub.status.idle":"2026-05-12T17:32:24.017131Z","shell.execute_reply.started":"2026-05-12T17:32:24.016944Z","shell.execute_reply":"2026-05-12T17:32:24.016997Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"activation = {}\n\ndef hook_fn(module, input, output):\n    activation['feat'] = output.detach()\n\nhook = model.layer1.register_forward_hook(hook_fn)\n\nwith torch.no_grad():\n    _ = model(tensor)\n\nfeature_map = activation['feat'][0, 0].cpu().numpy()\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-12T17:32:24.018482Z","iopub.status.idle":"2026-05-12T17:32:24.019145Z","shell.execute_reply.started":"2026-05-12T17:32:24.018944Z","shell.execute_reply":"2026-05-12T17:32:24.018982Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.figure(figsize=(6,6))\nplt.imshow(feature_map, cmap='inferno')\nplt.title(\"ResNet Feature Map\")\nplt.axis('off')\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-12T17:32:24.020327Z","iopub.status.idle":"2026-05-12T17:32:24.020621Z","shell.execute_reply.started":"2026-05-12T17:32:24.020489Z","shell.execute_reply":"2026-05-12T17:32:24.020503Z"}},"outputs":[],"execution_count":null}]}