{"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.11.11","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":71549,"databundleVersionId":8561470,"sourceType":"competition"},{"sourceId":8728463,"sourceType":"datasetVersion","datasetId":5238658},{"sourceId":11992166,"sourceType":"datasetVersion","datasetId":7542869},{"sourceId":184402550,"sourceType":"kernelVersion"},{"sourceId":242444386,"sourceType":"kernelVersion"},{"sourceId":244187274,"sourceType":"kernelVersion"},{"sourceId":245456111,"sourceType":"kernelVersion"}],"dockerImageVersionId":31041,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true},"papermill":{"default_parameters":{},"duration":22.28799,"end_time":"2024-06-19T21:35:43.284727","environment_variables":{},"exception":null,"input_path":"__notebook__.ipynb","output_path":"__notebook__.ipynb","parameters":{},"start_time":"2024-06-19T21:35:20.996737","version":"2.5.0"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"rd = '/kaggle/input/rsna-2024-lumbar-spine-degenerative-classification'","metadata":{"execution":{"iopub.status.busy":"2025-06-14T22:27:35.201199Z","iopub.execute_input":"2025-06-14T22:27:35.201371Z","iopub.status.idle":"2025-06-14T22:27:35.207301Z","shell.execute_reply.started":"2025-06-14T22:27:35.201355Z","shell.execute_reply":"2025-06-14T22:27:35.206598Z"},"papermill":{"duration":0.014905,"end_time":"2024-06-19T21:35:32.704012","exception":false,"start_time":"2024-06-19T21:35:32.689107","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os  # Bu satır eklenmeli\nimport torch  # Bu satır zaten ekli\n\nOUTPUT_DIR = f'/kaggle/input/rsna2024-lsdc-training-baseline/rsna24-results'\ndevice = 'cuda:0' if torch.cuda.is_available() else 'cpu'\nN_WORKERS = os.cpu_count()\nUSE_AMP = True\nSEED = 8620\n\nIMG_SIZE = [512, 512]\nIN_CHANS = 30\nN_LABELS = 25\nN_CLASSES = 3 * N_LABELS\n\nN_FOLDS = 5\n\nMODEL_NAME = \"resnext101_32x8d\"\n\nBATCH_SIZE = 1\n","metadata":{"execution":{"iopub.status.busy":"2025-06-14T22:29:29.869202Z","iopub.execute_input":"2025-06-14T22:29:29.869483Z","iopub.status.idle":"2025-06-14T22:29:29.874251Z","shell.execute_reply.started":"2025-06-14T22:29:29.869461Z","shell.execute_reply":"2025-06-14T22:29:29.873471Z"},"papermill":{"duration":0.086708,"end_time":"2024-06-19T21:35:32.814105","exception":false,"start_time":"2024-06-19T21:35:32.727397","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"rd = '/kaggle/input/rsna-2024-lumbar-spine-degenerative-classification'","metadata":{"execution":{"iopub.status.busy":"2025-05-29T07:22:45.624458Z","iopub.execute_input":"2025-05-29T07:22:45.62492Z","iopub.status.idle":"2025-05-29T07:22:45.641382Z","shell.execute_reply.started":"2025-05-29T07:22:45.6249Z","shell.execute_reply":"2025-05-29T07:22:45.640665Z"},"papermill":{"duration":0.015691,"end_time":"2024-06-19T21:35:32.837732","exception":false,"start_time":"2024-06-19T21:35:32.822041","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport gc\nimport sys\nfrom PIL import Image\nimport cv2\nimport math, random\nimport numpy as np\nimport pandas as pd\nfrom glob import glob\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import KFold\n\nfrom collections import OrderedDict\n\nimport torch\nimport torch.nn.functional as F\nfrom torch import nn\nfrom torch.utils.data import DataLoader, Dataset\nfrom torch.optim import AdamW\n\nimport timm\nfrom timm.utils import ModelEmaV2\nfrom transformers import get_cosine_schedule_with_warmup\n\nimport albumentations as A\n\nfrom sklearn.model_selection import KFold\n\nimport re\nimport pydicom","metadata":{"execution":{"iopub.status.busy":"2025-05-29T07:21:57.859573Z","iopub.execute_input":"2025-05-29T07:21:57.859816Z","iopub.status.idle":"2025-05-29T07:22:45.4812Z","shell.execute_reply.started":"2025-05-29T07:21:57.859792Z","shell.execute_reply":"2025-05-29T07:22:45.480435Z"},"papermill":{"duration":8.77009,"end_time":"2024-06-19T21:35:32.681013","exception":false,"start_time":"2024-06-19T21:35:23.910923","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"device = torch.device('cuda:0') if torch.cuda.is_available() else torch.device('cpu')\ndevice","metadata":{"execution":{"iopub.status.busy":"2025-05-29T07:22:45.643154Z","iopub.execute_input":"2025-05-29T07:22:45.643386Z","iopub.status.idle":"2025-05-29T07:22:45.658143Z","shell.execute_reply.started":"2025-05-29T07:22:45.64337Z","shell.execute_reply":"2025-05-29T07:22:45.657565Z"},"papermill":{"duration":0.017434,"end_time":"2024-06-19T21:35:32.862999","exception":false,"start_time":"2024-06-19T21:35:32.845565","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df = pd.read_csv(f'{rd}/test_series_descriptions.csv')\ndf.head()","metadata":{"execution":{"iopub.status.busy":"2025-05-29T07:22:45.658847Z","iopub.execute_input":"2025-05-29T07:22:45.659103Z","iopub.status.idle":"2025-05-29T07:22:45.702164Z","shell.execute_reply.started":"2025-05-29T07:22:45.659081Z","shell.execute_reply":"2025-05-29T07:22:45.701517Z"},"papermill":{"duration":0.046121,"end_time":"2024-06-19T21:35:32.917045","exception":false,"start_time":"2024-06-19T21:35:32.870924","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"study_ids = list(df['study_id'].unique())","metadata":{"execution":{"iopub.status.busy":"2025-05-29T07:22:45.702986Z","iopub.execute_input":"2025-05-29T07:22:45.703281Z","iopub.status.idle":"2025-05-29T07:22:45.71019Z","shell.execute_reply.started":"2025-05-29T07:22:45.703263Z","shell.execute_reply":"2025-05-29T07:22:45.709575Z"},"papermill":{"duration":0.017149,"end_time":"2024-06-19T21:35:32.942351","exception":false,"start_time":"2024-06-19T21:35:32.925202","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sample_sub = pd.read_csv(f'{rd}/sample_submission.csv')","metadata":{"execution":{"iopub.status.busy":"2025-05-29T07:22:45.711044Z","iopub.execute_input":"2025-05-29T07:22:45.711314Z","iopub.status.idle":"2025-05-29T07:22:45.740383Z","shell.execute_reply.started":"2025-05-29T07:22:45.711295Z","shell.execute_reply":"2025-05-29T07:22:45.739914Z"},"papermill":{"duration":0.019315,"end_time":"2024-06-19T21:35:32.970629","exception":false,"start_time":"2024-06-19T21:35:32.951314","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"LABELS = list(sample_sub.columns[1:])\nLABELS","metadata":{"execution":{"iopub.status.busy":"2025-05-29T07:22:45.741184Z","iopub.execute_input":"2025-05-29T07:22:45.741856Z","iopub.status.idle":"2025-05-29T07:22:45.74618Z","shell.execute_reply.started":"2025-05-29T07:22:45.741838Z","shell.execute_reply":"2025-05-29T07:22:45.745564Z"},"papermill":{"duration":0.016249,"end_time":"2024-06-19T21:35:32.995501","exception":false,"start_time":"2024-06-19T21:35:32.979252","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"CONDITIONS = [\n    'spinal_canal_stenosis', \n    'left_neural_foraminal_narrowing', \n    'right_neural_foraminal_narrowing',\n    'left_subarticular_stenosis',\n    'right_subarticular_stenosis'\n]\n\nLEVELS = [\n    'l1_l2',\n    'l2_l3',\n    'l3_l4',\n    'l4_l5',\n    'l5_s1',\n]","metadata":{"execution":{"iopub.status.busy":"2025-05-29T07:22:45.746907Z","iopub.execute_input":"2025-05-29T07:22:45.747134Z","iopub.status.idle":"2025-05-29T07:22:45.760873Z","shell.execute_reply.started":"2025-05-29T07:22:45.747111Z","shell.execute_reply":"2025-05-29T07:22:45.760252Z"},"papermill":{"duration":0.015634,"end_time":"2024-06-19T21:35:33.019358","exception":false,"start_time":"2024-06-19T21:35:33.003724","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def atoi(text):\n    return int(text) if text.isdigit() else text\n\ndef natural_keys(text):\n    return [ atoi(c) for c in re.split(r'(\\d+)', text) ]","metadata":{"execution":{"iopub.status.busy":"2025-05-29T07:22:45.761545Z","iopub.execute_input":"2025-05-29T07:22:45.761852Z","iopub.status.idle":"2025-05-29T07:22:45.7764Z","shell.execute_reply.started":"2025-05-29T07:22:45.761836Z","shell.execute_reply":"2025-05-29T07:22:45.775886Z"},"papermill":{"duration":0.015473,"end_time":"2024-06-19T21:35:33.043027","exception":false,"start_time":"2024-06-19T21:35:33.027554","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class RSNA24TestDataset(Dataset):\n    def __init__(self, df, study_ids, phase='test', transform=None):\n        self.df = df\n        self.study_ids = study_ids\n        self.transform = transform\n        self.phase = phase\n    \n    def __len__(self):\n        return len(self.study_ids)\n    \n    def get_img_paths(self, study_id, series_desc):\n        pdf = self.df[self.df['study_id']==study_id]\n        pdf_ = pdf[pdf['series_description']==series_desc]\n        allimgs = []\n        for i, row in pdf_.iterrows():\n            pimgs = glob.glob(f'{rd}/test_images/{study_id}/{row[\"series_id\"]}/*.dcm')\n            pimgs = sorted(pimgs, key=natural_keys)\n            allimgs.extend(pimgs)\n            \n        return allimgs\n    \n    def read_dcm_ret_arr(self, src_path):\n        dicom_data = pydicom.dcmread(src_path)\n        image = dicom_data.pixel_array\n        image = (image - image.min()) / (image.max() - image.min() + 1e-6) * 255\n        img = cv2.resize(image, (IMG_SIZE[0], IMG_SIZE[1]),interpolation=cv2.INTER_CUBIC)\n        assert img.shape==(IMG_SIZE[0], IMG_SIZE[1])\n        return img\n\n    def __getitem__(self, idx):\n        x = np.zeros((IMG_SIZE[0], IMG_SIZE[1], IN_CHANS), dtype=np.uint8)\n        st_id = self.study_ids[idx]        \n        \n        # Sagittal T1\n        allimgs_st1 = self.get_img_paths(st_id, 'Sagittal T1')\n        if len(allimgs_st1)==0:\n            print(st_id, ': Sagittal T1, has no images')\n        \n        else:\n            step = len(allimgs_st1) / 10.0\n            st = len(allimgs_st1)/2.0 - 4.0*step\n            end = len(allimgs_st1)+0.0001\n            for j, i in enumerate(np.arange(st, end, step)):\n                try:\n                    ind2 = max(0, int((i-0.5001).round()))\n                    img = self.read_dcm_ret_arr(allimgs_st1[ind2])\n                    x[..., j] = img.astype(np.uint8)\n                except:\n                    print(f'failed to load on {st_id}, Sagittal T1')\n                    pass\n            \n        # Sagittal T2/STIR\n        allimgs_st2 = self.get_img_paths(st_id, 'Sagittal T2/STIR')\n        if len(allimgs_st2)==0:\n            print(st_id, ': Sagittal T2/STIR, has no images')\n            \n        else:\n            step = len(allimgs_st2) / 10.0\n            st = len(allimgs_st2)/2.0 - 4.0*step\n            end = len(allimgs_st2)+0.0001\n            for j, i in enumerate(np.arange(st, end, step)):\n                try:\n                    ind2 = max(0, int((i-0.5001).round()))\n                    img = self.read_dcm_ret_arr(allimgs_st2[ind2])\n                    x[..., j+10] = img.astype(np.uint8)\n                except:\n                    print(f'failed to load on {st_id}, Sagittal T2/STIR')\n                    pass\n            \n        # Axial T2\n        allimgs_at2 = self.get_img_paths(st_id, 'Axial T2')\n        if len(allimgs_at2)==0:\n            print(st_id, ': Axial T2, has no images')\n            \n        else:\n            step = len(allimgs_at2) / 10.0\n            st = len(allimgs_at2)/2.0 - 4.0*step\n            end = len(allimgs_at2)+0.0001\n\n            for j, i in enumerate(np.arange(st, end, step)):\n                try:\n                    ind2 = max(0, int((i-0.5001).round()))\n                    img = self.read_dcm_ret_arr(allimgs_at2[ind2])\n                    x[..., j+20] = img.astype(np.uint8)\n                except:\n                    print(f'failed to load on {st_id}, Axial T2')\n                    pass  \n            \n            \n        if self.transform is not None:\n            x = self.transform(image=x)['image']\n\n        x = x.transpose(2, 0, 1)\n                \n        return x, str(st_id)","metadata":{"execution":{"iopub.status.busy":"2025-05-29T07:22:45.777186Z","iopub.execute_input":"2025-05-29T07:22:45.777432Z","iopub.status.idle":"2025-05-29T07:22:45.797677Z","shell.execute_reply.started":"2025-05-29T07:22:45.777411Z","shell.execute_reply":"2025-05-29T07:22:45.796947Z"},"papermill":{"duration":0.03143,"end_time":"2024-06-19T21:35:33.098536","exception":false,"start_time":"2024-06-19T21:35:33.067106","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"transforms_test = A.Compose([\n    A.Resize(IMG_SIZE[0], IMG_SIZE[1]),\n    A.Normalize(mean=0.5, std=0.5)\n])","metadata":{"execution":{"iopub.status.busy":"2025-05-29T07:22:45.798433Z","iopub.execute_input":"2025-05-29T07:22:45.798636Z","iopub.status.idle":"2025-05-29T07:22:45.818249Z","shell.execute_reply.started":"2025-05-29T07:22:45.798622Z","shell.execute_reply":"2025-05-29T07:22:45.817548Z"},"papermill":{"duration":0.015243,"end_time":"2024-06-19T21:35:33.122003","exception":false,"start_time":"2024-06-19T21:35:33.10676","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_ds = RSNA24TestDataset(df, study_ids, transform=transforms_test)\ntest_dl = DataLoader(\n    test_ds, \n    batch_size=1, \n    shuffle=False,\n    num_workers=N_WORKERS,\n    pin_memory=True,\n    drop_last=False\n)","metadata":{"execution":{"iopub.status.busy":"2025-05-29T07:22:45.82084Z","iopub.execute_input":"2025-05-29T07:22:45.82103Z","iopub.status.idle":"2025-05-29T07:22:45.83248Z","shell.execute_reply.started":"2025-05-29T07:22:45.821016Z","shell.execute_reply":"2025-05-29T07:22:45.831958Z"},"papermill":{"duration":0.01513,"end_time":"2024-06-19T21:35:33.14516","exception":false,"start_time":"2024-06-19T21:35:33.13003","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Define Model","metadata":{"papermill":{"duration":0.007899,"end_time":"2024-06-19T21:35:33.161191","exception":false,"start_time":"2024-06-19T21:35:33.153292","status":"completed"},"tags":[]}},{"cell_type":"code","source":"class RSNA24Model(nn.Module):\n    def __init__(self, model_name, in_c=30, n_classes=75, pretrained=True, features_only=False):\n        super().__init__()\n        self.model = timm.create_model(\n                                    model_name,\n                                    pretrained=pretrained, \n                                    features_only=features_only,\n                                    in_chans=in_c,\n                                    num_classes=n_classes,\n                                    global_pool='avg'\n                                    )\n    \n    def forward(self, x):\n        y = self.model(x)\n        return y","metadata":{"execution":{"iopub.status.busy":"2025-05-29T07:22:45.833216Z","iopub.execute_input":"2025-05-29T07:22:45.8335Z","iopub.status.idle":"2025-05-29T07:22:45.848067Z","shell.execute_reply.started":"2025-05-29T07:22:45.833484Z","shell.execute_reply":"2025-05-29T07:22:45.847415Z"},"papermill":{"duration":0.016562,"end_time":"2024-06-19T21:35:33.186608","exception":false,"start_time":"2024-06-19T21:35:33.170046","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"models = []","metadata":{"execution":{"iopub.status.busy":"2025-05-29T07:22:45.84879Z","iopub.execute_input":"2025-05-29T07:22:45.849028Z","iopub.status.idle":"2025-05-29T07:22:45.866168Z","shell.execute_reply.started":"2025-05-29T07:22:45.849007Z","shell.execute_reply":"2025-05-29T07:22:45.865472Z"},"papermill":{"duration":0.014206,"end_time":"2024-06-19T21:35:33.225288","exception":false,"start_time":"2024-06-19T21:35:33.211082","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import glob\nCKPT_PATHS = glob.glob('/kaggle/input/resnext101-32x8d-training/rsna24-results/best_wll_model_fold-*.pt')\nCKPT_PATHS = sorted(CKPT_PATHS)","metadata":{"execution":{"iopub.status.busy":"2025-05-29T07:22:45.866864Z","iopub.execute_input":"2025-05-29T07:22:45.867175Z","iopub.status.idle":"2025-05-29T07:22:45.889224Z","shell.execute_reply.started":"2025-05-29T07:22:45.867152Z","shell.execute_reply":"2025-05-29T07:22:45.888558Z"},"papermill":{"duration":0.018919,"end_time":"2024-06-19T21:35:33.252499","exception":false,"start_time":"2024-06-19T21:35:33.23358","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for i, cp in enumerate(CKPT_PATHS):\n    print(f'loading {cp}...')\n    model = RSNA24Model(MODEL_NAME, IN_CHANS, N_CLASSES, pretrained=False)\n    model.load_state_dict(torch.load(cp))\n    model.eval()\n    model.half()\n    model.to(device)\n    models.append(model)","metadata":{"execution":{"iopub.status.busy":"2025-05-29T07:22:45.89014Z","iopub.execute_input":"2025-05-29T07:22:45.890559Z","iopub.status.idle":"2025-05-29T07:23:16.011484Z","shell.execute_reply.started":"2025-05-29T07:22:45.890541Z","shell.execute_reply":"2025-05-29T07:23:16.010952Z"},"papermill":{"duration":4.761899,"end_time":"2024-06-19T21:35:38.022457","exception":false,"start_time":"2024-06-19T21:35:33.260558","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"autocast = torch.cuda.amp.autocast(enabled=USE_AMP, dtype=torch.half)\ny_preds = []\nrow_names = []\n\nwith tqdm(test_dl, leave=True) as pbar:\n    with torch.no_grad():\n        for idx, (x, si) in enumerate(pbar):\n            x = x.to(device)\n            pred_per_study = np.zeros((25, 3))\n            \n            for cond in CONDITIONS:\n                for level in LEVELS:\n                    row_names.append(si[0] + '_' + cond + '_' + level)\n            \n            with autocast:\n                for m in models:\n                    y = m(x)[0]\n                    for col in range(N_LABELS):\n                        pred = y[col*3:col*3+3]\n                        y_pred = pred.float().softmax(0).cpu().numpy()\n                        pred_per_study[col] += y_pred / len(models)\n                y_preds.append(pred_per_study)\n\ny_preds = np.concatenate(y_preds, axis=0)","metadata":{"execution":{"iopub.status.busy":"2025-05-29T07:23:16.012065Z","iopub.execute_input":"2025-05-29T07:23:16.012244Z","iopub.status.idle":"2025-05-29T07:23:18.888713Z","shell.execute_reply.started":"2025-05-29T07:23:16.012231Z","shell.execute_reply":"2025-05-29T07:23:18.887802Z"},"papermill":{"duration":2.524115,"end_time":"2024-06-19T21:35:40.578124","exception":false,"start_time":"2024-06-19T21:35:38.054009","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sub = pd.DataFrame()\nsub['row_id'] = row_names\nsub[LABELS] = y_preds\nsub.head(25)","metadata":{"execution":{"iopub.status.busy":"2025-05-29T07:23:18.889928Z","iopub.execute_input":"2025-05-29T07:23:18.890171Z","iopub.status.idle":"2025-05-29T07:23:18.907074Z","shell.execute_reply.started":"2025-05-29T07:23:18.890147Z","shell.execute_reply":"2025-05-29T07:23:18.906485Z"},"papermill":{"duration":0.03739,"end_time":"2024-06-19T21:35:40.643827","exception":false,"start_time":"2024-06-19T21:35:40.606437","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sub.to_csv('submission.csv', index=False)\npd.read_csv('submission.csv').head()","metadata":{"execution":{"iopub.status.busy":"2025-05-29T07:23:18.907757Z","iopub.execute_input":"2025-05-29T07:23:18.908043Z","iopub.status.idle":"2025-05-29T07:23:18.942845Z","shell.execute_reply.started":"2025-05-29T07:23:18.908017Z","shell.execute_reply":"2025-05-29T07:23:18.942024Z"},"papermill":{"duration":0.029248,"end_time":"2024-06-19T21:35:40.68401","exception":false,"start_time":"2024-06-19T21:35:40.654762","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"papermill":{"duration":0.009437,"end_time":"2024-06-19T21:35:40.722499","exception":false,"start_time":"2024-06-19T21:35:40.713062","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null}]}