{"metadata":{"kernelspec":{"name":"python3","display_name":"Python 3","language":"python"},"language_info":{"name":"python","version":"3.10.14","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":183439689,"sourceType":"kernelVersion"}],"dockerImageVersionId":30733,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# RSNA2024 LSDC Training Baseline\nIn the [previous notebook](https://www.kaggle.com/code/itsuki9180/rsna2024-lsdc-making-dataset), We selected the images we wanted to use and exported them to png.\n\nThis notebook will use those images for training.\n\n### My other Notebooks\n- [RSNA2024 LSDC Making Dataset](https://www.kaggle.com/code/itsuki9180/rsna2024-lsdc-making-dataset) \n- [RSNA2024 LSDC Training Baseline](https://www.kaggle.com/code/itsuki9180/rsna2024-lsdc-training-baseline) <- you're reading now\n- [RSNA2024 LSDC Submission Baseline](https://www.kaggle.com/code/itsuki9180/rsna2024-lsdc-submission-baseline)","metadata":{}},{"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":"2024-07-24T20:17:06.928457Z","iopub.execute_input":"2024-07-24T20:17:06.928838Z","iopub.status.idle":"2024-07-24T20:22:34.189059Z","shell.execute_reply.started":"2024-07-24T20:17:06.928809Z","shell.execute_reply":"2024-07-24T20:22:34.187933Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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 transformers import get_cosine_schedule_with_warmup\n\nimport albumentations as A\n\nfrom sklearn.model_selection import KFold","metadata":{"execution":{"iopub.status.busy":"2024-07-24T20:22:45.932962Z","iopub.execute_input":"2024-07-24T20:22:45.933411Z","iopub.status.idle":"2024-07-24T20:23:23.551442Z","shell.execute_reply.started":"2024-07-24T20:22:45.933374Z","shell.execute_reply":"2024-07-24T20:23:23.550249Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"rd = '/kaggle/input/rsna-2024-lumbar-spine-degenerative-classification'","metadata":{"execution":{"iopub.status.busy":"2024-07-24T20:23:23.553795Z","iopub.execute_input":"2024-07-24T20:23:23.554266Z","iopub.status.idle":"2024-07-24T20:23:23.558378Z","shell.execute_reply.started":"2024-07-24T20:23:23.554236Z","shell.execute_reply":"2024-07-24T20:23:23.557671Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Config","metadata":{}},{"cell_type":"code","source":"NOT_DEBUG = True # True -> run naormally, False -> debug mode, with lesser computing cost\n\nOUTPUT_DIR = f'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\nSEED = 8620\n\nIMG_SIZE = [512, 512]\nIN_CHANS = 30\nN_LABELS = 25\nN_CLASSES = 3 * N_LABELS\n\nAUG_PROB = 0.75\n\nN_FOLDS = 2 if NOT_DEBUG else 2\nEPOCHS = 20 if NOT_DEBUG else 2\nMODEL_NAME = \"resnet50.a1_in1k\"\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-3 * TGT_BATCH_SIZE / 32\nWD = 1e-1\nAUG = True","metadata":{"execution":{"iopub.status.busy":"2024-07-24T20:30:46.131145Z","iopub.execute_input":"2024-07-24T20:30:46.131496Z","iopub.status.idle":"2024-07-24T20:30:46.137879Z","shell.execute_reply.started":"2024-07-24T20:30:46.131467Z","shell.execute_reply":"2024-07-24T20:30:46.137105Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"os.makedirs(OUTPUT_DIR, exist_ok=True)","metadata":{"execution":{"iopub.status.busy":"2024-07-24T20:30:48.581004Z","iopub.execute_input":"2024-07-24T20:30:48.581329Z","iopub.status.idle":"2024-07-24T20:30:48.585372Z","shell.execute_reply.started":"2024-07-24T20:30:48.581301Z","shell.execute_reply":"2024-07-24T20:30:48.584584Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def set_random_seed(seed: int = 8620, 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":"2024-07-24T20:30:48.922935Z","iopub.execute_input":"2024-07-24T20:30:48.923263Z","iopub.status.idle":"2024-07-24T20:30:48.930381Z","shell.execute_reply.started":"2024-07-24T20:30:48.923236Z","shell.execute_reply":"2024-07-24T20:30:48.929531Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":"2024-07-24T20:30:49.605302Z","iopub.execute_input":"2024-07-24T20:30:49.605694Z","iopub.status.idle":"2024-07-24T20:30:49.649955Z","shell.execute_reply.started":"2024-07-24T20:30:49.605662Z","shell.execute_reply":"2024-07-24T20:30:49.649053Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":"2024-07-24T20:30:50.230790Z","iopub.execute_input":"2024-07-24T20:30:50.231142Z","iopub.status.idle":"2024-07-24T20:30:50.240326Z","shell.execute_reply.started":"2024-07-24T20:30:50.231111Z","shell.execute_reply":"2024-07-24T20:30:50.239452Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"label2id = {'Normal/Mild': 0, 'Moderate':1, 'Severe':2}\ndf = df.replace(label2id)\ndf.head()","metadata":{"execution":{"iopub.status.busy":"2024-07-24T20:30:50.525969Z","iopub.execute_input":"2024-07-24T20:30:50.526256Z","iopub.status.idle":"2024-07-24T20:30:50.558856Z","shell.execute_reply.started":"2024-07-24T20:30:50.526230Z","shell.execute_reply":"2024-07-24T20:30:50.558052Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":"2024-07-24T20:30:50.962439Z","iopub.execute_input":"2024-07-24T20:30:50.962727Z","iopub.status.idle":"2024-07-24T20:30:50.966896Z","shell.execute_reply.started":"2024-07-24T20:30:50.962702Z","shell.execute_reply":"2024-07-24T20:30:50.966139Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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((512, 512, 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(0, 10, 1):\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(0, 10, 1):\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+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        axt2 = glob(f'./cvt_png/{st_id}/Axial T2/*.png')\n        axt2 = sorted(axt2)\n    \n        step = len(axt2) / 10.0\n        st = len(axt2)/2.0 - 4.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+20] = img.astype(np.uint8)\n            except:\n                #print(f'failed to load on {st_id}, Sagittal T2/STIR')\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":"2024-07-24T20:30:51.996161Z","iopub.execute_input":"2024-07-24T20:30:51.996447Z","iopub.status.idle":"2024-07-24T20:30:52.006876Z","shell.execute_reply.started":"2024-07-24T20:30:51.996422Z","shell.execute_reply":"2024-07-24T20:30:52.006132Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":"def apply_jitter(image, rows=None, cols=None):\n    color_jitter = A.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2, hue=0.2, p=AUG_PROB)\n#     print(image.shape)\n\n    for i in range(0, 30, 3):\n        image[..., i:i+3] = color_jitter(image=image[..., i:i+3])['image']\n    return image","metadata":{"execution":{"iopub.status.busy":"2024-07-24T20:30:52.769036Z","iopub.execute_input":"2024-07-24T20:30:52.769981Z","iopub.status.idle":"2024-07-24T20:30:52.775071Z","shell.execute_reply.started":"2024-07-24T20:30:52.769939Z","shell.execute_reply":"2024-07-24T20:30:52.774293Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def apply_clahe(image, rows=None, cols=None):\n    clahe = A.CLAHE(clip_limit=2.0, tile_grid_size=(8, 8), p=AUG_PROB)\n\n    for i in range(0, 30, 3):\n        image[..., i:i+3] = clahe(image=image[..., i:i+3].astype(np.uint8))['image']\n        \n    return image","metadata":{"execution":{"iopub.status.busy":"2024-07-24T20:30:53.010825Z","iopub.execute_input":"2024-07-24T20:30:53.011103Z","iopub.status.idle":"2024-07-24T20:30:53.016283Z","shell.execute_reply.started":"2024-07-24T20:30:53.011078Z","shell.execute_reply":"2024-07-24T20:30:53.015529Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"transforms_train = A.Compose([\n    A.Lambda(image=apply_jitter),\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.Lambda(image=apply_clahe),  # Adding CLAHE\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.Lambda(image=apply_clahe),  # Adding CLAHE\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":"2024-07-24T20:30:53.376788Z","iopub.execute_input":"2024-07-24T20:30:53.377024Z","iopub.status.idle":"2024-07-24T20:30:53.387730Z","shell.execute_reply.started":"2024-07-24T20:30:53.377001Z","shell.execute_reply":"2024-07-24T20:30:53.387052Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Trying Data Loader\nChecking if the data loader works properly.","metadata":{}},{"cell_type":"code","source":"tmp_ds = RSNA24Dataset(df, phase='train', transform=transforms_train)\ntmp_dl = DataLoader(\n            tmp_ds,\n            batch_size=1,\n            shuffle=False,\n            pin_memory=True,\n            drop_last=False,\n            num_workers=0\n            )\n\nfor i, (x, t) in enumerate(tmp_dl):\n    if i==5:break\n    print('x stat:', x.shape, x.min(), x.max(),x.mean(), x.std())\n    print(t, t.shape)\n    y = x.numpy().transpose(0,2,3,1)[0,...,:3]\n    y = (y + 1) / 2\n    plt.imshow(y)\n    plt.show()\n    print('y stat:', y.shape, y.min(), y.max(),y.mean(), y.std())\n    print()\nplt.close()\ndel tmp_ds, tmp_dl","metadata":{"execution":{"iopub.status.busy":"2024-07-24T20:30:54.855387Z","iopub.execute_input":"2024-07-24T20:30:54.855660Z","iopub.status.idle":"2024-07-24T20:30:59.045542Z","shell.execute_reply.started":"2024-07-24T20:30:54.855635Z","shell.execute_reply":"2024-07-24T20:30:59.044468Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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(\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":"2024-07-24T20:31:03.458942Z","iopub.execute_input":"2024-07-24T20:31:03.459292Z","iopub.status.idle":"2024-07-24T20:31:03.465069Z","shell.execute_reply.started":"2024-07-24T20:31:03.459262Z","shell.execute_reply":"2024-07-24T20:31:03.464307Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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(2, IN_CHANS, 512, 512)\nout = m(i)\nfor o in out:\n    print(o.shape, o.min(), o.max())","metadata":{"execution":{"iopub.status.busy":"2024-07-24T20:31:04.455400Z","iopub.execute_input":"2024-07-24T20:31:04.455766Z","iopub.status.idle":"2024-07-24T20:31:05.292037Z","shell.execute_reply.started":"2024-07-24T20:31:04.455735Z","shell.execute_reply":"2024-07-24T20:31:05.291125Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"del m, i, out","metadata":{"execution":{"iopub.status.busy":"2024-07-24T20:31:05.293306Z","iopub.execute_input":"2024-07-24T20:31:05.293558Z","iopub.status.idle":"2024-07-24T20:31:05.298036Z","shell.execute_reply.started":"2024-07-24T20:31:05.293533Z","shell.execute_reply":"2024-07-24T20:31:05.297391Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Train loop","metadata":{}},{"cell_type":"code","source":"# #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\nskf = KFold(n_splits=N_FOLDS, shuffle=True, random_state=SEED)\nfor fold, (trn_idx, val_idx) in enumerate(skf.split(range(len(df)))):\n    print('#'*30)\n    print(f'start fold{fold}')\n    print('#'*30)\n    print(len(trn_idx), len(val_idx))\n    df_train = df.iloc[trn_idx]\n    df_valid = 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    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    criterion2 = nn.CrossEntropyLoss(weight=weights)\n\n    best_loss = 1.2\n    best_wll = 1.2\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                        \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\n        total_loss = 0\n        y_preds = []\n        labels = []\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                            y_preds.append(y_pred.cpu())\n                            labels.append(gt.cpu())\n                        \n                        total_loss += loss.item()   \n    \n        val_loss = total_loss/len(valid_dl)\n        \n        y_preds = torch.cat(y_preds, dim=0)\n        labels = torch.cat(labels)\n        val_wll = criterion2(y_preds, labels)\n        \n        print(f'val_loss:{val_loss:.6f}, val_wll:{val_wll:.6f}')\n\n        if val_loss < best_loss or val_wll < best_wll:\n            \n            es_step = 0\n\n            if device!='cuda:0':\n#                 model.to('cuda:0') \n                model.to(device)\n                \n            if val_loss < best_loss:\n                print(f'epoch:{epoch}, best loss updated from {best_loss:.6f} to {val_loss:.6f}')\n                best_loss = val_loss\n                \n            if val_wll < best_wll:\n                print(f'epoch:{epoch}, best wll_metric updated from {best_wll:.6f} to {val_wll:.6f}')\n                best_wll = val_wll\n                fname = f'{OUTPUT_DIR}/best_wll_model_fold-{fold}.pt'\n                torch.save(model.state_dict(), fname)\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  \n                              ","metadata":{"execution":{"iopub.status.busy":"2024-07-24T20:31:06.451137Z","iopub.execute_input":"2024-07-24T20:31:06.451484Z","iopub.status.idle":"2024-07-24T20:33:25.317868Z","shell.execute_reply.started":"2024-07-24T20:31:06.451453Z","shell.execute_reply":"2024-07-24T20:33:25.316636Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# ","metadata":{}},{"cell_type":"markdown","source":"# Calculation of CV","metadata":{}},{"cell_type":"code","source":"cv = 0\ny_preds = []\nlabels = []\nweights = torch.tensor([1.0, 2.0, 4.0])\ncriterion2 = nn.CrossEntropyLoss(weight=weights)\n\nfor fold, (trn_idx, val_idx) in enumerate(skf.split(range(len(df)))):\n    print('#'*30)\n    print(f'start fold{fold}')\n    print('#'*30)\n    df_valid = df.iloc[val_idx]\n    valid_ds = RSNA24Dataset(df_valid, phase='valid', transform=transforms_val)\n    valid_dl = DataLoader(\n                valid_ds,\n                batch_size=1,\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=False)\n    fname = f'{OUTPUT_DIR}/best_wll_model_fold-{fold}.pt'\n    model.load_state_dict(torch.load(fname))\n    model.to(device)   \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                    y = model(x)\n                    for col in range(N_LABELS):\n                        pred = y[:,col*3:col*3+3]\n                        gt = t[:,col] \n                        y_pred = pred.float()\n                        y_preds.append(y_pred.cpu())\n                        labels.append(gt.cpu())\n\ny_preds = torch.cat(y_preds)\nlabels = torch.cat(labels)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cv = criterion2(y_preds, labels)\nprint('cv score:', cv.item())","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Calculation of Competition Metrics\nThis will give a slightly different score, probably due to the different behavior for nan.","metadata":{}},{"cell_type":"code","source":"from sklearn.metrics import log_loss\ny_pred_np = y_preds.softmax(1).numpy()\nlabels_np = labels.numpy()\ny_pred_nan = np.zeros((y_preds.shape[0], 1))\ny_pred2 = np.concatenate([y_pred_nan, y_pred_np],axis=1)\nweights = []\nfor l in labels:\n    if l==0: weights.append(1)\n    elif l==1: weights.append(2)\n    elif l==2: weights.append(4)\n    else: weights.append(0)\ncv2 = log_loss(labels, y_pred2, normalize=True, sample_weight=weights)\nprint('cv score:', cv2)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"np.save(f'{OUTPUT_DIR}/labels.npy', labels_np)\nnp.save(f'{OUTPUT_DIR}/final_oof.npy', y_pred2)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# When predictions are random\ngets about 1.1.","metadata":{}},{"cell_type":"code","source":"random_pred = np.ones((y_preds.shape[0], 3)) / 3.0\ny_pred3 = np.concatenate([y_pred_nan, random_pred],axis=1)\ncv3 = log_loss(labels, y_pred3, normalize=True, sample_weight=weights)\nprint('random score:', cv3)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Continuing with the [Submission Baseline...](https://www.kaggle.com/code/itsuki9180/rsna2024-lsdc-submission-baseline)","metadata":{}},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}