{"metadata":{"kernelspec":{"name":"python3","display_name":"Python 3","language":"python"},"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":71549,"databundleVersionId":8561470,"sourceType":"competition"},{"sourceId":192939335,"sourceType":"kernelVersion"}],"dockerImageVersionId":30733,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Import Libralies","metadata":{}},{"cell_type":"code","source":"!unzip -q /kaggle/input/rsna2024-lsdc-making-dataset/_output_.zip","metadata":{"execution":{"iopub.status.busy":"2025-11-11T15:31:22.896993Z","iopub.execute_input":"2025-11-11T15:31:22.897263Z","iopub.status.idle":"2025-11-11T15:33:22.616559Z","shell.execute_reply.started":"2025-11-11T15:31:22.897239Z","shell.execute_reply":"2025-11-11T15:33:22.614949Z"},"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, train_test_split\nfrom sklearn.metrics import f1_score, ConfusionMatrixDisplay\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\nfrom torchvision.models.segmentation import lraspp_mobilenet_v3_large\n\n\nimport timm\nfrom transformers import get_cosine_schedule_with_warmup\n\nimport albumentations as A\n\nfrom sklearn.model_selection import KFold","metadata":{"execution":{"iopub.status.busy":"2025-11-11T15:33:39.473687Z","iopub.execute_input":"2025-11-11T15:33:39.474063Z","iopub.status.idle":"2025-11-11T15:33:42.348399Z","shell.execute_reply.started":"2025-11-11T15:33:39.474038Z","shell.execute_reply":"2025-11-11T15:33:42.347206Z"},"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-11-11T15:33:47.123323Z","iopub.execute_input":"2025-11-11T15:33:47.12406Z","iopub.status.idle":"2025-11-11T15:33:47.128996Z","shell.execute_reply.started":"2025-11-11T15:33:47.124028Z","shell.execute_reply":"2025-11-11T15:33:47.12778Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Config","metadata":{}},{"cell_type":"code","source":"# Remember to change NOT_DEBUG to True for real training\nNOT_DEBUG = True # True -> run naormally, False -> debug mode, with lesser computing cost\n\nOUTPUT_DIR = f'/kaggle/working/rsna24-results'\ndevice = 'cuda:0' if torch.cuda.is_available() else 'cpu'\nN_WORKERS = os.cpu_count()\nUSE_AMP = True # can change True if using T4 or newer than Ampere\n\n\nSEED = 8620\n\nIMG_SIZE = [512, 512]\nIN_CHANS = 30\nN_LABELS = 25\nN_CLASSES = 3 * N_LABELS\n\nAUG_PROB = 0.75\nSELECTED_FOLDS = [0, 1, 2, 3, 4]\nN_FOLDS = 5 if NOT_DEBUG else 2\nEPOCHS = 25 if NOT_DEBUG else 2\n# MODEL_NAME = \"tf_efficientnet_b4.ns_jft_in1k\" if NOT_DEBUG else \"tf_efficientnet_b0.ns_jft_in1k\"\n# TODO: you can choose other convolutional neural network (CNN) architectures designed to \n#       achieve state-of-the-art accuracy in various computer vision tasks\n\nMODEL_NAME = 'edgenext_base.in21k_ft_in1k' if NOT_DEBUG else \"densenet121\"\n\nGRAD_ACC = 2\nTGT_BATCH_SIZE = 32\nBATCH_SIZE = TGT_BATCH_SIZE // GRAD_ACC\nMAX_GRAD_NORM = None\nEARLY_STOPPING_EPOCH = 3\n\nLR = 2e-4 * TGT_BATCH_SIZE / 32\nWD = 1e-2\nAUG = True","metadata":{"execution":{"iopub.status.busy":"2025-11-11T15:33:48.951657Z","iopub.execute_input":"2025-11-11T15:33:48.952053Z","iopub.status.idle":"2025-11-11T15:33:48.960021Z","shell.execute_reply.started":"2025-11-11T15:33:48.952024Z","shell.execute_reply":"2025-11-11T15:33:48.958892Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"os.makedirs(OUTPUT_DIR, exist_ok=True)","metadata":{"execution":{"iopub.status.busy":"2025-11-11T15:33:52.333724Z","iopub.execute_input":"2025-11-11T15:33:52.334105Z","iopub.status.idle":"2025-11-11T15:33:52.33972Z","shell.execute_reply.started":"2025-11-11T15:33:52.334078Z","shell.execute_reply":"2025-11-11T15:33:52.338381Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def set_random_seed(seed: int = 2222, deterministic: bool = False):\n    \"\"\"Set seeds\"\"\"\n    random.seed(seed)\n    np.random.seed(seed)\n    os.environ[\"PYTHONHASHSEED\"] = str(seed)\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed(seed)  # type: ignore\n    torch.backends.cudnn.benchmark = True\n    torch.backends.cudnn.deterministic = deterministic  # type: ignore\n\nset_random_seed(SEED)","metadata":{"execution":{"iopub.status.busy":"2025-11-11T15:33:52.797949Z","iopub.execute_input":"2025-11-11T15:33:52.798322Z","iopub.status.idle":"2025-11-11T15:33:52.808737Z","shell.execute_reply.started":"2025-11-11T15:33:52.798297Z","shell.execute_reply":"2025-11-11T15:33:52.807304Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Open Dataframes","metadata":{}},{"cell_type":"code","source":"df = pd.read_csv(f'{rd}/train.csv')\ndf.head()","metadata":{"execution":{"iopub.status.busy":"2025-11-11T15:33:57.109167Z","iopub.execute_input":"2025-11-11T15:33:57.109546Z","iopub.status.idle":"2025-11-11T15:33:57.197118Z","shell.execute_reply.started":"2025-11-11T15:33:57.109519Z","shell.execute_reply":"2025-11-11T15:33:57.196027Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Change the state to Label.\n\nThe dataframe contains some Nans, which we will replace with -100 so that We and function can ignore them when calculating the loss and score.","metadata":{}},{"cell_type":"code","source":"df = df.fillna(-100)","metadata":{"execution":{"iopub.status.busy":"2025-11-11T15:33:59.516784Z","iopub.execute_input":"2025-11-11T15:33:59.517153Z","iopub.status.idle":"2025-11-11T15:33:59.527446Z","shell.execute_reply.started":"2025-11-11T15:33:59.517129Z","shell.execute_reply":"2025-11-11T15:33:59.526379Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"label2id = {'Normal/Mild': 0, 'Moderate':1, 'Severe':2}\ndf = df.replace(label2id)\ndf.head()","metadata":{"execution":{"iopub.status.busy":"2025-11-11T15:33:59.8398Z","iopub.execute_input":"2025-11-11T15:33:59.840766Z","iopub.status.idle":"2025-11-11T15:33:59.88137Z","shell.execute_reply.started":"2025-11-11T15:33:59.840731Z","shell.execute_reply":"2025-11-11T15:33:59.88023Z"},"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-11-11T15:34:00.375187Z","iopub.execute_input":"2025-11-11T15:34:00.375566Z","iopub.status.idle":"2025-11-11T15:34:00.381944Z","shell.execute_reply.started":"2025-11-11T15:34:00.375538Z","shell.execute_reply":"2025-11-11T15:34:00.380568Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Define Dataset\n\nThis implementation is very slow and leaves a lot of room for improvement.","metadata":{}},{"cell_type":"code","source":"class RSNA24Dataset(Dataset):\n    def __init__(self, df, phase='train', transform=None):\n        self.df = df\n        self.transform = transform\n        self.phase = phase\n    \n    def __len__(self):\n        return len(self.df)\n\n    def __getitem__(self, idx):\n        x = np.zeros((IMG_SIZE[0], IMG_SIZE[1], IN_CHANS), dtype=np.uint8)\n        t = self.df.iloc[idx]\n        st_id = int(t['study_id'])\n        label = t[1:].values.astype(np.int64)\n        \n        # Sagittal T1\n        for i in range(IN_CHANS//3):\n            try:\n                p = f'./cvt_png/{st_id}/Sagittal T1/{i:03d}.png'\n                img = Image.open(p).convert('L')\n                img = np.array(img)\n                x[..., i] = 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        for i in range(IN_CHANS//3):\n            try:\n                p = f'./cvt_png/{st_id}/Sagittal T2_STIR/{i:03d}.png'\n                img = Image.open(p).convert('L')\n                img = np.array(img)\n                x[..., i+(IN_CHANS//3)] = 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        axt2 = glob(f'./cvt_png/{st_id}/Axial T2/*.png')\n        axt2 = sorted(axt2)\n    \n        step = len(axt2) / (IN_CHANS//3)\n        st = len(axt2)/2.0 - 6.0*step\n        end = len(axt2)+0.0001\n                \n        for i, j in enumerate(np.arange(st, end, step)):\n            try:\n                p = axt2[max(0, int((j-0.5001).round()))]\n                img = Image.open(p).convert('L')\n                img = np.array(img)\n                x[..., i+2*(IN_CHANS//3)] = img.astype(np.uint8)\n            except:\n                #print(f'failed to load on {st_id}, Axial T2')\n                pass\n        \n        assert np.sum(x)>0\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, label","metadata":{"execution":{"iopub.status.busy":"2025-11-11T15:34:05.790058Z","iopub.execute_input":"2025-11-11T15:34:05.790845Z","iopub.status.idle":"2025-11-11T15:34:05.802877Z","shell.execute_reply.started":"2025-11-11T15:34:05.790791Z","shell.execute_reply":"2025-11-11T15:34:05.801392Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Define Data Augmentaion\nData augmentation is important because the number of images used for training is extremely small.\nSee [this notebook](https://www.kaggle.com/code/haqishen/1st-place-soluiton-code-small-ver) by [Qishen Ha](https://www.kaggle.com/haqishen) for help setting up this augmentation.","metadata":{}},{"cell_type":"code","source":"transforms_train = A.Compose([\n    A.RandomBrightnessContrast(brightness_limit=(-0.2, 0.2), contrast_limit=(-0.2, 0.2), p=AUG_PROB),\n    A.OneOf([\n        A.MotionBlur(blur_limit=5),\n        A.MedianBlur(blur_limit=5),\n        A.GaussianBlur(blur_limit=5),\n        A.GaussNoise(var_limit=(5.0, 30.0)),\n    ], p=AUG_PROB),\n\n    A.OneOf([\n        A.OpticalDistortion(distort_limit=1.0),\n        A.GridDistortion(num_steps=5, distort_limit=1.),\n        A.ElasticTransform(alpha=3),\n    ], p=AUG_PROB),\n\n    A.ShiftScaleRotate(shift_limit=0.1, scale_limit=0.1, rotate_limit=15, border_mode=0, p=AUG_PROB),\n    A.Resize(IMG_SIZE[0], IMG_SIZE[1]),\n    #A.CoarseDropout(max_holes=16, max_height=64, max_width=64, min_holes=1, min_height=8, min_width=8, p=AUG_PROB),    \n    A.Normalize(mean=0.5, std=0.5)\n])\n\ntransforms_val = A.Compose([\n    A.Resize(IMG_SIZE[0], IMG_SIZE[1]),\n    A.Normalize(mean=0.5, std=0.5)\n])\n\nif not NOT_DEBUG or not AUG:\n    transforms_train = transforms_val","metadata":{"execution":{"iopub.status.busy":"2025-11-11T15:34:10.012158Z","iopub.execute_input":"2025-11-11T15:34:10.012515Z","iopub.status.idle":"2025-11-11T15:34:10.023147Z","shell.execute_reply.started":"2025-11-11T15:34:10.01249Z","shell.execute_reply":"2025-11-11T15:34:10.021966Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Define Model\nWe use timm, which is commonly used for image classification.","metadata":{}},{"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(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    def forward(self, x):\n        y=self.model(x)\n        return y","metadata":{"execution":{"iopub.status.busy":"2025-11-11T15:34:14.938488Z","iopub.execute_input":"2025-11-11T15:34:14.938915Z","iopub.status.idle":"2025-11-11T15:34:14.946499Z","shell.execute_reply.started":"2025-11-11T15:34:14.938884Z","shell.execute_reply":"2025-11-11T15:34:14.945338Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Testing Model\nChecking if the model works properly.","metadata":{}},{"cell_type":"code","source":"m = RSNA24Model(MODEL_NAME, in_c=IN_CHANS, n_classes=N_CLASSES, pretrained=False)\ni = torch.randn(1, IN_CHANS, IMG_SIZE[0], IMG_SIZE[1])\nout = m(i)\nfor o in out:\n    print(o.shape, o.min(), o.max())","metadata":{"execution":{"iopub.status.busy":"2025-11-11T15:34:15.537842Z","iopub.execute_input":"2025-11-11T15:34:15.538218Z","iopub.status.idle":"2025-11-11T15:34:19.486032Z","shell.execute_reply.started":"2025-11-11T15:34:15.53819Z","shell.execute_reply":"2025-11-11T15:34:19.484785Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"del m, i, out","metadata":{"execution":{"iopub.status.busy":"2025-11-11T15:34:21.928048Z","iopub.execute_input":"2025-11-11T15:34:21.928389Z","iopub.status.idle":"2025-11-11T15:34:21.936592Z","shell.execute_reply.started":"2025-11-11T15:34:21.928365Z","shell.execute_reply":"2025-11-11T15:34:21.935617Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"new_df, test_df = train_test_split(df,test_size=0.1, shuffle=True, random_state=SEED)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-11T15:47:45.01699Z","iopub.execute_input":"2025-11-11T15:47:45.017422Z","iopub.status.idle":"2025-11-11T15:47:45.026962Z","shell.execute_reply.started":"2025-11-11T15:47:45.017389Z","shell.execute_reply":"2025-11-11T15:47:45.025919Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Train loop","metadata":{}},{"cell_type":"code","source":"%time\n#autocast = torch.cuda.amp.autocast(enabled=USE_AMP, dtype=torch.bfloat16) # if your gpu is newer Ampere, you can use this, lesser appearance of nan than half\nautocast = torch.cuda.amp.autocast(enabled=USE_AMP, dtype=torch.half) # you can use with T4 gpu. or newer\nscaler = torch.cuda.amp.GradScaler(enabled=USE_AMP, init_scale=4096)\n\nval_losses = []\ntrain_losses = []\nskf = KFold(n_splits=N_FOLDS, shuffle=True, random_state=SEED)\nfor fold, (trn_idx, val_idx) in enumerate(skf.split(range(len(new_df)))):\n    if NOT_DEBUG == False:\n        if fold == 1: break;\n    if fold not in SELECTED_FOLDS: \n        print(f\"Jump fold {fold}\")\n        continue;\n    else:\n        print('#'*30)\n        print(f'Start fold {fold}')\n        print('#'*30)\n        print(len(trn_idx), len(val_idx))\n        df_train = new_df.iloc[trn_idx]\n        df_valid = new_df.iloc[val_idx]\n\n        train_ds = RSNA24Dataset(df_train, phase='train', transform=transforms_train)\n        train_dl = DataLoader(\n                    train_ds,\n                    batch_size=BATCH_SIZE,\n                    shuffle=True,\n                    pin_memory=True,\n                    drop_last=True,\n                    num_workers=N_WORKERS\n                    )\n\n        valid_ds = RSNA24Dataset(df_valid, phase='valid', transform=transforms_val)\n        valid_dl = DataLoader(\n                    valid_ds,\n                    batch_size=BATCH_SIZE*2,\n                    shuffle=False,\n                    pin_memory=True,\n                    drop_last=False,\n                    num_workers=N_WORKERS\n                    )\n\n        model = RSNA24Model(MODEL_NAME, IN_CHANS, N_CLASSES, pretrained=True)\n        fname = f'{OUTPUT_DIR}/best_wll_model_fold-{fold}.pt'\n        if os.path.exists(fname):\n            model = RSNA24Model(MODEL_NAME, IN_CHANS, N_CLASSES, pretrained=False)\n            model.load_state_dict(torch.load(fname))\n        model.to(device)\n\n        optimizer = AdamW(model.parameters(), lr=LR, weight_decay=WD)\n\n        warmup_steps = EPOCHS/10 * len(train_dl) // GRAD_ACC\n        num_total_steps = EPOCHS * len(train_dl) // GRAD_ACC\n        num_cycles = 0.475\n        scheduler = get_cosine_schedule_with_warmup(optimizer,\n                                                    num_warmup_steps=warmup_steps,\n                                                    num_training_steps=num_total_steps,\n                                                    num_cycles=num_cycles)\n\n        weights = torch.tensor([1.0, 2.0, 4.0])\n        criterion = nn.CrossEntropyLoss(weight=weights.to(device))\n        #criterion = FocalLoss(gamma=2,weight=weights.to(device),reduction='mean')\n\n        best_loss = 1.5\n        es_step = 0\n\n        for epoch in range(1, EPOCHS+1):\n            print(f'start epoch {epoch}')\n            model.train()\n            total_loss = 0\n            with tqdm(train_dl, leave=True) as pbar:\n                optimizer.zero_grad()\n                for idx, (x, t) in enumerate(pbar):  \n                    x = x.to(device)\n                    t = t.to(device)\n\n                    with autocast:\n                        loss = 0\n                        y = model(x)\n                        for col in range(N_LABELS):\n                            pred = y[:,col*3:col*3+3]\n                            gt = t[:,col]\n                            loss = loss + criterion(pred, gt) / N_LABELS\n                        total_loss += loss.item()\n                        if GRAD_ACC > 1:\n                            loss = loss / GRAD_ACC\n\n                    if not math.isfinite(loss):\n                        print(f\"Loss is {loss}, stopping training\")\n                        sys.exit(1)\n\n                    pbar.set_postfix(\n                        OrderedDict(\n                            loss=f'{loss.item()*GRAD_ACC:.6f}',\n                            lr=f'{optimizer.param_groups[0][\"lr\"]:.3e}'\n                        )\n                    )\n                    scaler.scale(loss).backward()\n\n                    torch.nn.utils.clip_grad_norm_(model.parameters(), MAX_GRAD_NORM or 1e9)\n\n                    if (idx + 1) % GRAD_ACC == 0:\n                        scaler.step(optimizer)\n                        scaler.update()\n                        optimizer.zero_grad()\n                        if scheduler is not None:\n                            scheduler.step()                    \n\n            train_loss = total_loss/len(train_dl)\n            print(f'train_loss:{train_loss:.6f}')\n            train_losses.append(train_loss)\n            total_loss = 0\n\n            model.eval()\n            with tqdm(valid_dl, leave=True) as pbar:\n                with torch.no_grad():\n                    for idx, (x, t) in enumerate(pbar):\n\n                        x = x.to(device)\n                        t = t.to(device)\n\n                        with autocast:\n                            loss = 0\n                            loss_ema = 0\n                            y = model(x)\n                            for col in range(N_LABELS):\n                                pred = y[:,col*3:col*3+3]\n                                gt = t[:,col]\n\n                                loss = loss + criterion(pred, gt) / N_LABELS\n                                y_pred = pred.float()\n  \n                            total_loss += loss.item()   \n\n            val_loss = total_loss/len(valid_dl)\n            print(f'val_loss:{val_loss:.6f}')\n            val_losses.append(val_loss)\n            if val_loss < best_loss:\n\n                if device!='cuda:0':\n                    model.to('cuda:0')                \n\n                print(f'epoch:{epoch}, best weighted_logloss updated from {best_loss:.6f} to {val_loss:.6f}')\n                best_loss = val_loss\n                fname = f'{OUTPUT_DIR}/best_wll_model_fold-{fold}.pt'\n                torch.save(model.state_dict(), fname)\n                print(f'{fname} is saved')\n                es_step = 0\n\n                if device!='cuda:0':\n                    model.to(device)\n\n            else:\n                es_step += 1\n                if es_step >= EARLY_STOPPING_EPOCH:\n                    print('early stopping')\n                    break  ","metadata":{"execution":{"iopub.status.busy":"2025-11-11T15:47:47.278131Z","iopub.execute_input":"2025-11-11T15:47:47.278489Z","iopub.status.idle":"2025-11-11T15:47:50.659895Z","shell.execute_reply.started":"2025-11-11T15:47:47.278463Z","shell.execute_reply":"2025-11-11T15:47:50.654083Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!rm -r cvt_png msk_png","metadata":{"execution":{"iopub.status.busy":"2024-08-06T21:12:04.276513Z","iopub.execute_input":"2024-08-06T21:12:04.276893Z","iopub.status.idle":"2024-08-06T21:12:05.371971Z","shell.execute_reply.started":"2024-08-06T21:12:04.276867Z","shell.execute_reply":"2024-08-06T21:12:05.370753Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Continuing with the [Submission Baseline...](https://www.kaggle.com/code/itsuki9180/rsna2024-lsdc-submission-baseline)","metadata":{}}]}