{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":59093,"databundleVersionId":7469972,"sourceType":"competition"},{"sourceId":7447935,"sourceType":"datasetVersion","datasetId":4334122},{"sourceId":7452079,"sourceType":"datasetVersion","datasetId":4337415,"isSourceIdPinned":true},{"sourceId":7464465,"sourceType":"datasetVersion","datasetId":4344851,"isSourceIdPinned":true},{"sourceId":7497291,"sourceType":"datasetVersion","datasetId":4365555},{"sourceId":159396114,"sourceType":"kernelVersion"}],"dockerImageVersionId":30636,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# About\n\nIn this notebook, I'll share an image clacification approach for given spectrograms.\n\n* **version 1**: naive approach\n* **version 2**: For comparing with [Chris's EfficientNetB2 Starter](https://www.kaggle.com/code/cdeotte/efficientnetb2-starter-lb-0-57), I added **log transform** and **LR scheduling**.\n\nThis is inference notebook. Training notebook is here:  \nhttps://www.kaggle.com/code/ttahara/hms-hbac-resnet34d-baseline-training/","metadata":{}},{"cell_type":"markdown","source":"# Prepare","metadata":{}},{"cell_type":"markdown","source":"## Import","metadata":{}},{"cell_type":"code","source":"import sys\nimport os\nimport gc\nimport copy\nimport yaml\nimport random\nimport shutil\nfrom time import time\nimport typing as tp\nfrom pathlib import Path\n\nimport numpy as np\nimport pandas as pd\n\nfrom tqdm.notebook import tqdm\nfrom sklearn.model_selection import StratifiedGroupKFold\n\nimport torch\nfrom torch import nn\nfrom torch import optim\nfrom torch.optim import lr_scheduler\nfrom torch.cuda import amp\n\nimport timm\n\nimport albumentations as A\nfrom albumentations.pytorch import ToTensorV2","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-01-28T10:51:57.626468Z","iopub.execute_input":"2024-01-28T10:51:57.626770Z","iopub.status.idle":"2024-01-28T10:52:05.695666Z","shell.execute_reply.started":"2024-01-28T10:51:57.626745Z","shell.execute_reply":"2024-01-28T10:52:05.694467Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"","metadata":{"execution":{"iopub.status.busy":"2024-01-28T10:52:05.697743Z","iopub.execute_input":"2024-01-28T10:52:05.698398Z","iopub.status.idle":"2024-01-28T10:52:05.704980Z","shell.execute_reply.started":"2024-01-28T10:52:05.698358Z","shell.execute_reply":"2024-01-28T10:52:05.703844Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ROOT = Path.cwd().parent\nINPUT = ROOT / \"input\"\nOUTPUT = ROOT / \"output\"\nSRC = ROOT / \"src\"\n\nDATA = INPUT / \"hms-harmful-brain-activity-classification\"\nTRAIN_SPEC = DATA / \"train_spectrograms\"\nTEST_SPEC = DATA / \"test_spectrograms\"\n\n# TRAINED_MODEL = \"/kaggle/input/hms-hbac-resnet34d-baseline-exp02\"\n\nTMP = ROOT / \"tmp\"\nTRAIN_SPEC_SPLIT = TMP / \"train_spectrograms_split\"\nTEST_SPEC_SPLIT = TMP / \"test_spectrograms_split\"\nTMP.mkdir(exist_ok=True)\nTRAIN_SPEC_SPLIT.mkdir(exist_ok=True)\nTEST_SPEC_SPLIT.mkdir(exist_ok=True)\n\n\nRANDAM_SEED = 1086\nCLASSES = [\"seizure_vote\", \"lpd_vote\", \"gpd_vote\", \"lrda_vote\", \"grda_vote\", \"other_vote\"]\nN_CLASSES = len(CLASSES)\nFOLDS = [0, 1, 2, 3, 4]\nN_FOLDS = len(FOLDS)","metadata":{"execution":{"iopub.status.busy":"2024-01-28T10:52:05.706164Z","iopub.execute_input":"2024-01-28T10:52:05.706560Z","iopub.status.idle":"2024-01-28T10:52:05.718510Z","shell.execute_reply.started":"2024-01-28T10:52:05.706521Z","shell.execute_reply":"2024-01-28T10:52:05.717562Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class CFG1:\n    model_name = \"tf_efficientnetv2_l_in21ft1k\"\n    img_size_h = 400\n    img_size_w = 300\n    channels = 1\n    max_epoch = 7\n    batch_size = 32\n    lr = 1.0e-03\n    weight_decay = 1.0e-02\n    es_patience =  5\n    seed = 1086\n    deterministic = True\n    enable_amp = True\n    device = \"cuda\"\n    TRAINED_MODEL=INPUT / \"hms-hbac-effnet-l-augs-0-250-5\"\n    model_filename = \"best_model_fold{}.pth\"\n\nclass CFG2:\n    model_name = \"tf_efficientnetv2_l_in21ft1k\"\n    img_size_h = 512\n    img_size_w = 512\n    channels = 1\n    max_epoch = 7\n    batch_size = 32\n    lr = 1.0e-03\n    weight_decay = 1.0e-02\n    es_patience =  5\n    seed = 1086\n    deterministic = True\n    enable_amp = True\n    device = \"cuda\"\n    TRAINED_MODEL=INPUT / \"hms-hbac-effnetv2-baseline\"\n    model_filename = \"best_model_fold{}.pth\" \n\nclass CFG3:\n    model_name = \"resnet34d\"\n    img_size_h = 512\n    img_size_w = 512\n    channels = 1\n    max_epoch = 7\n    batch_size = 32\n    lr = 1.0e-03\n    weight_decay = 1.0e-02\n    es_patience =  5\n    seed = 1086\n    deterministic = True\n    enable_amp = True\n    device = \"cuda\"\n    TRAINED_MODEL=INPUT / \"hms-baseline-resnet34d-512-512-training-5-folds\"\n    model_filename = \"HMS_resnet_fold{}.pth\"\n\ndevice = torch.device(CFG1.device)","metadata":{"execution":{"iopub.status.busy":"2024-01-28T11:05:03.580753Z","iopub.execute_input":"2024-01-28T11:05:03.581133Z","iopub.status.idle":"2024-01-28T11:05:03.591694Z","shell.execute_reply.started":"2024-01-28T11:05:03.581099Z","shell.execute_reply":"2024-01-28T11:05:03.590602Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Read Data, Convert Spectrograms to Numpy file","metadata":{}},{"cell_type":"code","source":"test = pd.read_csv(DATA / \"test.csv\")","metadata":{"execution":{"iopub.status.busy":"2024-01-28T11:05:04.551993Z","iopub.execute_input":"2024-01-28T11:05:04.552372Z","iopub.status.idle":"2024-01-28T11:05:04.559520Z","shell.execute_reply.started":"2024-01-28T11:05:04.552342Z","shell.execute_reply":"2024-01-28T11:05:04.558700Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test.head()","metadata":{"execution":{"iopub.status.busy":"2024-01-28T11:05:05.078716Z","iopub.execute_input":"2024-01-28T11:05:05.079114Z","iopub.status.idle":"2024-01-28T11:05:05.089648Z","shell.execute_reply.started":"2024-01-28T11:05:05.079085Z","shell.execute_reply":"2024-01-28T11:05:05.088627Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### convert sepectogram files to numpy files","metadata":{}},{"cell_type":"code","source":"for spec_id in test[\"spectrogram_id\"]:\n    spec = pd.read_parquet(TEST_SPEC / f\"{spec_id}.parquet\")\n    \n    spec_arr = spec.fillna(0).values[:, 1:].T.astype(\"float32\")  # (Hz, Time) = (400, 300)\n    \n    np.save(TEST_SPEC_SPLIT / f\"{spec_id}.npy\", spec_arr)","metadata":{"execution":{"iopub.status.busy":"2024-01-28T11:05:05.146686Z","iopub.execute_input":"2024-01-28T11:05:05.147040Z","iopub.status.idle":"2024-01-28T11:05:05.188748Z","shell.execute_reply.started":"2024-01-28T11:05:05.147013Z","shell.execute_reply":"2024-01-28T11:05:05.187957Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Difinition, Model, Dataset","metadata":{}},{"cell_type":"markdown","source":"### model","metadata":{}},{"cell_type":"code","source":"class HMSHBACSpecModel(nn.Module):\n\n    def __init__(\n            self,\n            model_name: str,\n            pretrained: bool,\n            in_channels: int,\n            num_classes: int,\n        ):\n        super().__init__()\n        self.model = timm.create_model(\n            model_name=model_name, pretrained=False,\n            num_classes=num_classes, in_chans=in_channels)\n\n    def forward(self, x):\n        h = self.model(x)      \n\n        return h","metadata":{"execution":{"iopub.status.busy":"2024-01-28T11:05:05.248788Z","iopub.execute_input":"2024-01-28T11:05:05.249163Z","iopub.status.idle":"2024-01-28T11:05:05.255731Z","shell.execute_reply.started":"2024-01-28T11:05:05.249133Z","shell.execute_reply":"2024-01-28T11:05:05.254609Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## dataset","metadata":{}},{"cell_type":"code","source":"FilePath = tp.Union[str, Path]\nLabel = tp.Union[int, float, np.ndarray]\n\nclass HMSHBACSpecDataset(torch.utils.data.Dataset):\n\n    def __init__(\n        self,\n        image_paths: tp.Sequence[FilePath],\n        labels: tp.Sequence[Label],\n        transform: A.Compose,\n        channels: int = 1\n    ):\n        self.image_paths = image_paths\n        self.labels = labels\n        self.transform = transform\n        self.channels = channels\n\n    def __len__(self):\n        return len(self.image_paths)\n\n    def __getitem__(self, index: int):\n        img_path = self.image_paths[index]\n        label = self.labels[index]\n\n        img = np.load(img_path)  # shape: (Hz, Time) = (400, 300)\n\n        chunks = np.array_split(img, self.channels, axis=0)\n        # Stack the chunks along a new axis to get an array of shape (4, 100, 300)\n        img = np.stack(chunks, axis=-1)\n\n        img = self._apply_transform(img)\n\n        # log transform\n        img = np.clip(img, np.exp(-4), np.exp(8))\n        img = np.log(img)\n\n        # normalize per image\n        eps = 1e-6\n        img_mean = img.mean(axis=(0, 1))\n        img = img - img_mean\n        img_std = img.std(axis=(0, 1))\n        img = img / (img_std + eps)\n\n        return {\"data\": img, \"target\": label}\n\n    def _apply_transform(self, img: np.ndarray):\n        \"\"\"apply transform to image and mask\"\"\"\n        transformed = self.transform(image=img)\n        img = transformed[\"image\"]\n        return img","metadata":{"execution":{"iopub.status.busy":"2024-01-28T11:05:05.318811Z","iopub.execute_input":"2024-01-28T11:05:05.319174Z","iopub.status.idle":"2024-01-28T11:05:05.330423Z","shell.execute_reply.started":"2024-01-28T11:05:05.319144Z","shell.execute_reply":"2024-01-28T11:05:05.329465Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Inference Test Data","metadata":{}},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def to_device(\n    tensors: tp.Union[tp.Tuple[torch.Tensor], tp.Dict[str, torch.Tensor]],\n    device: torch.device, *args, **kwargs\n):\n    if isinstance(tensors, tuple):\n        return (t.to(device, *args, **kwargs) for t in tensors)\n    elif isinstance(tensors, dict):\n        return {\n            k: t.to(device, *args, **kwargs) for k, t in tensors.items()}\n    else:\n        return tensors.to(device, *args, **kwargs)\n\n    \ndef get_test_path_label(test: pd.DataFrame):\n    \"\"\"Get file path and dummy target info.\"\"\"\n    \n    img_paths = []\n    labels = np.full((len(test), 6), -1, dtype=\"float32\")\n    for spec_id in test[\"spectrogram_id\"].values:\n        img_path = TEST_SPEC_SPLIT / f\"{spec_id}.npy\"\n        img_paths.append(img_path)\n        \n    test_data = {\n        \"image_paths\": img_paths,\n        \"labels\": [l for l in labels]}\n    \n    return test_data\n\ndef get_test_transforms(CFG):\n    test_transform = A.Compose([\n        A.Resize(p=1.0, height=CFG.img_size_h, width=CFG.img_size_w),\n        ToTensorV2(p=1.0)\n    ])\n    return test_transform","metadata":{"execution":{"iopub.status.busy":"2024-01-28T11:05:05.412557Z","iopub.execute_input":"2024-01-28T11:05:05.412937Z","iopub.status.idle":"2024-01-28T11:05:05.422991Z","shell.execute_reply.started":"2024-01-28T11:05:05.412906Z","shell.execute_reply":"2024-01-28T11:05:05.422018Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def run_inference_loop(model, loader, device):\n    model.to(device)\n    model.eval()\n    pred_list = []\n    with torch.no_grad():\n        for batch in tqdm(loader):\n            x = to_device(batch[\"data\"], device)\n            y = model(x)\n            pred_list.append(y.softmax(dim=1).detach().cpu().numpy())\n        \n    pred_arr = np.concatenate(pred_list)\n    del pred_list\n    return pred_arr","metadata":{"execution":{"iopub.status.busy":"2024-01-28T11:05:05.441816Z","iopub.execute_input":"2024-01-28T11:05:05.442453Z","iopub.status.idle":"2024-01-28T11:05:05.448163Z","shell.execute_reply.started":"2024-01-28T11:05:05.442426Z","shell.execute_reply":"2024-01-28T11:05:05.447287Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def make_preds(cfg):\n    test_preds_arr = np.zeros((N_FOLDS, len(test), N_CLASSES))\n\n    test_path_label = get_test_path_label(test)\n    test_transform = get_test_transforms(cfg)\n    test_dataset = HMSHBACSpecDataset(**test_path_label, transform=test_transform, channels=cfg.channels)\n    test_loader = torch.utils.data.DataLoader(\n        test_dataset, batch_size=cfg.batch_size, num_workers=4, shuffle=False, drop_last=False)\n\n\n    for i, fold_id in enumerate(FOLDS):\n        print(f\"\\n[fold {fold_id}]\")\n\n        # # get model\n    #     model_path = TRAINED_MODEL / f\"HMS_resnet_fold{fold_id}.pth\"\n    #     model = torch.load(model_path, map_location=device)\n        model_path = cfg.TRAINED_MODEL / cfg.model_filename.format(fold_id)\n        try:\n            model = HMSHBACSpecModel(\n                model_name=cfg.model_name, pretrained=False, num_classes=6, in_channels=cfg.channels)\n            model.load_state_dict(torch.load(model_path, map_location=device))\n        except:\n            model = torch.load(model_path, map_location=device)\n\n        # # inference\n        test_pred = run_inference_loop(model, test_loader, device)\n        test_preds_arr[i] = test_pred\n\n        del model\n        torch.cuda.empty_cache()\n        gc.collect()\n    return test_preds_arr","metadata":{"execution":{"iopub.status.busy":"2024-01-28T11:06:22.417538Z","iopub.execute_input":"2024-01-28T11:06:22.418290Z","iopub.status.idle":"2024-01-28T11:06:22.427455Z","shell.execute_reply.started":"2024-01-28T11:06:22.418252Z","shell.execute_reply":"2024-01-28T11:06:22.426513Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Make Submission","metadata":{}},{"cell_type":"code","source":"test_preds_arr_total = np.zeros((len(test), N_CLASSES))\nfor cfg in [CFG1, CFG2, CFG3]:\n    test_preds_arr = make_preds(cfg)\n    test_pred = test_preds_arr.mean(axis=0)\n    \n    test_preds_arr_total += test_pred\ntest_preds_arr_total /= 3\n\ntest_pred_df = pd.DataFrame(\n    test_preds_arr_total, columns=CLASSES\n)\n\ntest_pred_df = pd.concat([test[[\"eeg_id\"]], test_pred_df], axis=1)","metadata":{"execution":{"iopub.status.busy":"2024-01-28T11:06:23.173289Z","iopub.execute_input":"2024-01-28T11:06:23.174005Z","iopub.status.idle":"2024-01-28T11:07:05.661437Z","shell.execute_reply.started":"2024-01-28T11:06:23.173968Z","shell.execute_reply":"2024-01-28T11:07:05.660251Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"smpl_sub = pd.read_csv(DATA / \"sample_submission.csv\")\n\nsub = pd.merge(\n    smpl_sub[[\"eeg_id\"]], test_pred_df, on=\"eeg_id\", how=\"left\")\n\nsub.to_csv(\"submission.csv\", index=False)\n\nsub.head()","metadata":{"execution":{"iopub.status.busy":"2024-01-28T11:07:18.035823Z","iopub.execute_input":"2024-01-28T11:07:18.036217Z","iopub.status.idle":"2024-01-28T11:07:18.066914Z","shell.execute_reply.started":"2024-01-28T11:07:18.036186Z","shell.execute_reply":"2024-01-28T11:07:18.065902Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# EOF","metadata":{}}]}