{"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":"nvidiaTeslaT4","dataSources":[{"sourceId":71549,"databundleVersionId":8561470,"sourceType":"competition"},{"sourceId":189926243,"sourceType":"kernelVersion"}],"dockerImageVersionId":30747,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Imports","metadata":{}},{"cell_type":"code","source":"import os\nimport math, random\nimport torch\nimport torchvision.models as models\nfrom torch import nn\nfrom torch.optim import AdamW\nfrom torch.utils.data import DataLoader, Dataset\nfrom transformers import ViTForImageClassification, ViTFeatureExtractor, ViTConfig, TrainingArguments, Trainer, DefaultDataCollator, get_cosine_schedule_with_warmup\nfrom PIL import Image\nfrom datasets import load_dataset\nimport pandas as pd\nimport albumentations as A\nimport numpy as np\nfrom glob import glob\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import KFold\nfrom collections import OrderedDict","metadata":{"execution":{"iopub.status.busy":"2024-07-27T18:58:46.527001Z","iopub.execute_input":"2024-07-27T18:58:46.527598Z","iopub.status.idle":"2024-07-27T18:58:46.538549Z","shell.execute_reply.started":"2024-07-27T18:58:46.527556Z","shell.execute_reply":"2024-07-27T18:58:46.537445Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Configs","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 = 5 if NOT_DEBUG else 2\nEPOCHS = 20 if NOT_DEBUG else 2\nMODEL_NAME = \"vit_b3.ns_jft_in1k\" if NOT_DEBUG else \"vit_b0.ns_jft_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-4 * TGT_BATCH_SIZE / 32\nWD = 1e-2\nAUG = True","metadata":{"execution":{"iopub.status.busy":"2024-07-27T18:58:49.884650Z","iopub.execute_input":"2024-07-27T18:58:49.885407Z","iopub.status.idle":"2024-07-27T18:58:49.941465Z","shell.execute_reply.started":"2024-07-27T18:58:49.885375Z","shell.execute_reply":"2024-07-27T18:58:49.940460Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"os.makedirs(OUTPUT_DIR, exist_ok=True)","metadata":{"execution":{"iopub.status.busy":"2024-07-27T18:58:51.526251Z","iopub.execute_input":"2024-07-27T18:58:51.526606Z","iopub.status.idle":"2024-07-27T18:58:51.531165Z","shell.execute_reply.started":"2024-07-27T18:58:51.526580Z","shell.execute_reply":"2024-07-27T18:58:51.530252Z"},"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-27T18:58:51.708653Z","iopub.execute_input":"2024-07-27T18:58:51.708916Z","iopub.status.idle":"2024-07-27T18:58:51.717396Z","shell.execute_reply.started":"2024-07-27T18:58:51.708893Z","shell.execute_reply":"2024-07-27T18:58:51.716502Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Load the model and feature extractor","metadata":{}},{"cell_type":"code","source":"# Load a pre-trained ResNet model (e.g., ResNet50)\nmodel = models.resnet50(pretrained=True)\n\n# Modify the first convolutional layer to accept 30 channels\nmodel.conv1 = torch.nn.Conv2d(\n    in_channels=30,\n    out_channels=model.conv1.out_channels,\n    kernel_size=model.conv1.kernel_size,\n    stride=model.conv1.stride,\n    padding=model.conv1.padding,\n    bias=model.conv1.bias is not None\n)\n\n# Modify the final fully connected layer to output 75 class labels\nnum_features = model.fc.in_features\nmodel.fc = torch.nn.Linear(num_features, 75)","metadata":{"execution":{"iopub.status.busy":"2024-07-27T18:58:54.239046Z","iopub.execute_input":"2024-07-27T18:58:54.239405Z","iopub.status.idle":"2024-07-27T18:58:55.866179Z","shell.execute_reply.started":"2024-07-27T18:58:54.239377Z","shell.execute_reply":"2024-07-27T18:58:55.865166Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Check that the model works properly","metadata":{}},{"cell_type":"code","source":"# Create a random tensor with 30 channels and 512x512 image size\ni = torch.randn(2, 30, 512, 512)\n\n# Pass the tensor through the model\nout = model(i)\n\n# Print the shapes and value ranges of the outputs\nprint(\"Output shape:\", out.shape)\nprint(\"Output value range: min =\", out.min().item(), \", max =\", out.max().item())\n\n# Cleanup\ndel model, i, out","metadata":{"execution":{"iopub.status.busy":"2024-07-27T18:59:09.960420Z","iopub.execute_input":"2024-07-27T18:59:09.960778Z","iopub.status.idle":"2024-07-27T18:59:11.965750Z","shell.execute_reply.started":"2024-07-27T18:59:09.960747Z","shell.execute_reply":"2024-07-27T18:59:11.964839Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Get the converted png images from the previous notebook\n!unzip -q -o /kaggle/input/glsdc-dataset/_output_.zip","metadata":{"execution":{"iopub.status.busy":"2024-07-27T18:59:48.927173Z","iopub.execute_input":"2024-07-27T18:59:48.927555Z","iopub.status.idle":"2024-07-27T19:04:07.635276Z","shell.execute_reply.started":"2024-07-27T18:59:48.927526Z","shell.execute_reply":"2024-07-27T19:04:07.634351Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Open Dataframes","metadata":{}},{"cell_type":"code","source":"rd = '/kaggle/input/rsna-2024-lumbar-spine-degenerative-classification'\ndf = pd.read_csv(f'{rd}/train.csv')\ndf.head()","metadata":{"execution":{"iopub.status.busy":"2024-07-27T19:11:15.827607Z","iopub.execute_input":"2024-07-27T19:11:15.827989Z","iopub.status.idle":"2024-07-27T19:11:15.896439Z","shell.execute_reply.started":"2024-07-27T19:11:15.827957Z","shell.execute_reply":"2024-07-27T19:11:15.895543Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = df.fillna(-100)\n\nlabel2id = {'Normal/Mild': 0, 'Moderate':1, 'Severe':2}\ndf = df.replace(label2id)\ndf.head()","metadata":{"execution":{"iopub.status.busy":"2024-07-27T19:11:19.252125Z","iopub.execute_input":"2024-07-27T19:11:19.252981Z","iopub.status.idle":"2024-07-27T19:11:19.318403Z","shell.execute_reply.started":"2024-07-27T19:11:19.252947Z","shell.execute_reply":"2024-07-27T19:11:19.317530Z"},"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-27T19:11:20.493112Z","iopub.execute_input":"2024-07-27T19:11:20.493462Z","iopub.status.idle":"2024-07-27T19:11:20.498267Z","shell.execute_reply.started":"2024-07-27T19:11:20.493434Z","shell.execute_reply":"2024-07-27T19:11:20.497195Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Define Dataset","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-27T19:11:23.306228Z","iopub.execute_input":"2024-07-27T19:11:23.306601Z","iopub.status.idle":"2024-07-27T19:11:23.320719Z","shell.execute_reply.started":"2024-07-27T19:11:23.306572Z","shell.execute_reply":"2024-07-27T19:11:23.319494Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Define Data 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":"2024-07-27T19:11:25.165668Z","iopub.execute_input":"2024-07-27T19:11:25.166231Z","iopub.status.idle":"2024-07-27T19:11:25.179256Z","shell.execute_reply.started":"2024-07-27T19:11:25.166203Z","shell.execute_reply":"2024-07-27T19:11:25.178423Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Run the Dataloader","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-27T19:11:27.028882Z","iopub.execute_input":"2024-07-27T19:11:27.029450Z","iopub.status.idle":"2024-07-27T19:11:31.691555Z","shell.execute_reply.started":"2024-07-27T19:11:27.029418Z","shell.execute_reply":"2024-07-27T19:11:31.690646Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Training","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    # Load a pre-trained ResNet model (e.g., ResNet50)\n    model = models.resnet50(pretrained=True)\n\n    # Modify the first convolutional layer to accept 30 channels\n    model.conv1 = torch.nn.Conv2d(\n        in_channels=30,\n        out_channels=model.conv1.out_channels,\n        kernel_size=model.conv1.kernel_size,\n        stride=model.conv1.stride,\n        padding=model.conv1.padding,\n        bias=model.conv1.bias is not None\n    )\n\n    # Modify the final fully connected layer to output 75 class labels\n    num_features = model.fc.in_features\n    model.fc = torch.nn.Linear(num_features, 75)\n    \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                \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","metadata":{"execution":{"iopub.status.busy":"2024-07-27T19:38:55.581648Z","iopub.execute_input":"2024-07-27T19:38:55.582050Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# CV Score Calculation","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\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":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cv = criterion2(y_preds, labels)\nprint('cv score:', cv.item())","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Competition Metrics","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":{},"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":"code","source":"!rm -r cvt_png","metadata":{},"execution_count":null,"outputs":[]}]}