{"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":159009253,"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-15T12:46:21.479644Z","iopub.execute_input":"2024-01-15T12:46:21.479975Z","iopub.status.idle":"2024-01-15T12:46:29.429620Z","shell.execute_reply.started":"2024-01-15T12:46:21.479948Z","shell.execute_reply":"2024-01-15T12:46:29.428589Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"","metadata":{"execution":{"iopub.status.busy":"2024-01-15T12:46:29.431528Z","iopub.execute_input":"2024-01-15T12:46:29.432546Z","iopub.status.idle":"2024-01-15T12:46:29.437025Z","shell.execute_reply.started":"2024-01-15T12:46:29.432508Z","shell.execute_reply":"2024-01-15T12:46:29.436083Z"},"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\nTRAINED_MODEL = INPUT / \"hms-hbac-resnet34d-baseline-training\"\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-15T12:46:38.293349Z","iopub.execute_input":"2024-01-15T12:46:38.294102Z","iopub.status.idle":"2024-01-15T12:46:38.302040Z","shell.execute_reply.started":"2024-01-15T12:46:38.294069Z","shell.execute_reply":"2024-01-15T12:46:38.300895Z"},"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-15T12:46:39.430475Z","iopub.execute_input":"2024-01-15T12:46:39.431170Z","iopub.status.idle":"2024-01-15T12:46:39.448398Z","shell.execute_reply.started":"2024-01-15T12:46:39.431136Z","shell.execute_reply":"2024-01-15T12:46:39.447496Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test.head()","metadata":{"execution":{"iopub.status.busy":"2024-01-15T12:46:41.648599Z","iopub.execute_input":"2024-01-15T12:46:41.649311Z","iopub.status.idle":"2024-01-15T12:46:41.666425Z","shell.execute_reply.started":"2024-01-15T12:46:41.649278Z","shell.execute_reply":"2024-01-15T12:46:41.665612Z"},"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-15T12:46:42.773556Z","iopub.execute_input":"2024-01-15T12:46:42.774388Z","iopub.status.idle":"2024-01-15T12:46:42.997336Z","shell.execute_reply.started":"2024-01-15T12:46:42.774353Z","shell.execute_reply":"2024-01-15T12:46:42.996548Z"},"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=pretrained,\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-15T12:46:45.565942Z","iopub.execute_input":"2024-01-15T12:46:45.566872Z","iopub.status.idle":"2024-01-15T12:46:45.572579Z","shell.execute_reply.started":"2024-01-15T12:46:45.566831Z","shell.execute_reply":"2024-01-15T12:46:45.571677Z"},"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    ):\n        self.image_paths = image_paths\n        self.labels = labels\n        self.transform = transform\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        # 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        img = img[..., None] # shape: (Hz, Time) -> (Hz, Time, Channel)\n        img = self._apply_transform(img)\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-15T12:46:51.433106Z","iopub.execute_input":"2024-01-15T12:46:51.433465Z","iopub.status.idle":"2024-01-15T12:46:51.443979Z","shell.execute_reply.started":"2024-01-15T12:46:51.433436Z","shell.execute_reply":"2024-01-15T12:46:51.443006Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Inference Test Data","metadata":{}},{"cell_type":"code","source":"class CFG:\n    model_name = \"resnet34d\"\n    img_size = 512\n    max_epoch = 9\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\"","metadata":{"execution":{"iopub.status.busy":"2024-01-15T12:46:52.221229Z","iopub.execute_input":"2024-01-15T12:46:52.221594Z","iopub.status.idle":"2024-01-15T12:46:52.228170Z","shell.execute_reply.started":"2024-01-15T12:46:52.221562Z","shell.execute_reply":"2024-01-15T12:46:52.227202Z"},"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, width=CFG.img_size),\n        ToTensorV2(p=1.0)\n    ])\n    return test_transform","metadata":{"execution":{"iopub.status.busy":"2024-01-15T12:46:56.912583Z","iopub.execute_input":"2024-01-15T12:46:56.912946Z","iopub.status.idle":"2024-01-15T12:46:56.922944Z","shell.execute_reply.started":"2024-01-15T12:46:56.912916Z","shell.execute_reply":"2024-01-15T12:46:56.921822Z"},"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-15T12:47:00.536080Z","iopub.execute_input":"2024-01-15T12:47:00.536442Z","iopub.status.idle":"2024-01-15T12:47:00.542847Z","shell.execute_reply.started":"2024-01-15T12:47:00.536413Z","shell.execute_reply":"2024-01-15T12:47:00.541699Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_preds_arr = np.zeros((N_FOLDS, len(test), N_CLASSES))\n\ntest_path_label = get_test_path_label(test)\ntest_transform = get_test_transforms(CFG)\ntest_dataset = HMSHBACSpecDataset(**test_path_label, transform=test_transform)\ntest_loader = torch.utils.data.DataLoader(\n    test_dataset, batch_size=CFG.batch_size, num_workers=4, shuffle=False, drop_last=False)\n\ndevice = torch.device(CFG.device)\n\nfor fold_id in range(N_FOLDS):\n    print(f\"\\n[fold {fold_id}]\")\n    \n    # # get model\n    model_path = TRAINED_MODEL / f\"best_model_fold{fold_id}.pth\"\n    model = HMSHBACSpecModel(\n        model_name=CFG.model_name, pretrained=False, num_classes=6, in_channels=1)\n    model.load_state_dict(torch.load(model_path, map_location=device))\n    \n    # # inference\n    test_pred = run_inference_loop(model, test_loader, device)\n    test_preds_arr[fold_id] = test_pred\n    \n    del model\n    torch.cuda.empty_cache()\n    gc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-01-15T12:47:00.980519Z","iopub.execute_input":"2024-01-15T12:47:00.981444Z","iopub.status.idle":"2024-01-15T12:47:11.422890Z","shell.execute_reply.started":"2024-01-15T12:47:00.981407Z","shell.execute_reply":"2024-01-15T12:47:11.422017Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Make Submission","metadata":{}},{"cell_type":"code","source":"test_pred = test_preds_arr.mean(axis=0)\n\ntest_pred_df = pd.DataFrame(\n    test_pred, columns=CLASSES\n)\n\ntest_pred_df = pd.concat([test[[\"eeg_id\"]], test_pred_df], axis=1)","metadata":{"execution":{"iopub.status.busy":"2024-01-15T12:47:14.334539Z","iopub.execute_input":"2024-01-15T12:47:14.335455Z","iopub.status.idle":"2024-01-15T12:47:14.344827Z","shell.execute_reply.started":"2024-01-15T12:47:14.335419Z","shell.execute_reply":"2024-01-15T12:47:14.343908Z"},"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-15T12:47:16.537753Z","iopub.execute_input":"2024-01-15T12:47:16.538149Z","iopub.status.idle":"2024-01-15T12:47:16.568159Z","shell.execute_reply.started":"2024-01-15T12:47:16.538116Z","shell.execute_reply":"2024-01-15T12:47:16.567097Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# EOF","metadata":{}}]}