{"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":159608908,"sourceType":"kernelVersion"}],"dockerImageVersionId":30636,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import os\nimport sys\nimport pandas as pd\nimport numpy as np\nimport random\n\nfrom sklearn import model_selection\n\nimport tensorflow\n\nimport torch\nfrom torch.utils.data import DataLoader,Dataset\nimport torch.nn as nn\nfrom torch import optim\nimport torch.functional as F\nfrom pathlib import Path\nfrom tqdm import tqdm\n\nimport matplotlib.pyplot as plt\n\nfrom torchvision import transforms\n\nimport albumentations as A\nfrom albumentations.pytorch import ToTensorV2\n\nimport timm\n\n# from tqdm import tqdm\nfrom tqdm.auto import tqdm\n\n\nimport warnings\nwarnings.filterwarnings('ignore')\n","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-01-19T14:09:44.782398Z","iopub.execute_input":"2024-01-19T14:09:44.783058Z","iopub.status.idle":"2024-01-19T14:09:44.789922Z","shell.execute_reply.started":"2024-01-19T14:09:44.783025Z","shell.execute_reply":"2024-01-19T14:09:44.788995Z"},"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\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\nclass CFG:\n    CLASSES = [\"seizure_vote\", \"lpd_vote\", \"gpd_vote\", \"lrda_vote\", \"grda_vote\", \"other_vote\"]\n    N_CLASSES = len(CLASSES)\n    DEVICE = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n    image_transform=transforms.Resize((256, 256))\n    SEED=1086\n    N_FOLDS=5\n    NUM_EPOCHS=8    \n    BATCH_SIZE=32\n    NUM_WORKERS=4\n    PATIENCE=3\n    EPS=1e-5\ncfg = CFG()","metadata":{"execution":{"iopub.status.busy":"2024-01-19T14:09:44.793531Z","iopub.execute_input":"2024-01-19T14:09:44.793816Z","iopub.status.idle":"2024-01-19T14:09:44.814575Z","shell.execute_reply.started":"2024-01-19T14:09:44.793792Z","shell.execute_reply":"2024-01-19T14:09:44.813576Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def seed_everything(seed):\n    torch.backends.cudnn.deterministic = True\n    torch.backends.cudnn.benchmark = True\n    torch.manual_seed(seed)\n    np.random.seed(seed)\n    random.seed(seed)\nseed_everything(cfg.SEED)","metadata":{"execution":{"iopub.status.busy":"2024-01-19T14:09:44.816116Z","iopub.execute_input":"2024-01-19T14:09:44.816467Z","iopub.status.idle":"2024-01-19T14:09:44.826913Z","shell.execute_reply.started":"2024-01-19T14:09:44.816442Z","shell.execute_reply":"2024-01-19T14:09:44.826050Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test = pd.read_csv(DATA / \"test.csv\")\nsample_submission = pd.read_csv(DATA / \"sample_submission.csv\")","metadata":{"execution":{"iopub.status.busy":"2024-01-19T14:28:57.808912Z","iopub.execute_input":"2024-01-19T14:28:57.809625Z","iopub.status.idle":"2024-01-19T14:28:57.829735Z","shell.execute_reply.started":"2024-01-19T14:28:57.809591Z","shell.execute_reply":"2024-01-19T14:28:57.828792Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for spec_id in test[\"spectrogram_id\"]:\n    spec = pd.read_parquet(TEST_SPEC / f\"{spec_id}.parquet\")\n    spec_arr = spec.fillna(0).values[:, 1:].T.astype(\"float32\")\n    np.save(TEST_SPEC_SPLIT / f\"{spec_id}.npy\", spec_arr)","metadata":{"execution":{"iopub.status.busy":"2024-01-19T14:09:44.842852Z","iopub.execute_input":"2024-01-19T14:09:44.843181Z","iopub.status.idle":"2024-01-19T14:09:44.879807Z","shell.execute_reply.started":"2024-01-19T14:09:44.843151Z","shell.execute_reply":"2024-01-19T14:09:44.878975Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class HMSDataset(Dataset):\n    def __init__(self,df):\n        self.df = df\n        \n    def __len__(self):\n        return len(self.df)\n    \n    def __getitem__(self,idx:int):\n        img_path = TEST_SPEC_SPLIT / f\"{self.df.loc[:,'spectrogram_id'][idx]}.npy\"\n        labels = np.full((len(test), 6), -1, dtype=\"float32\")\n        img = np.load(img_path)\n        data_mean=img.mean(axis=(0,1))\n        data_std=img.std(axis=(0,1))\n        img=(img-data_mean)/(data_std+cfg.EPS)\n        img = np.nan_to_num(img, nan=0.0)\n        data_tensor = torch.unsqueeze(torch.Tensor(img), dim=0)\n        img = cfg.image_transform(data_tensor)\n        lab = [l for l in labels]\n        return torch.tensor(img),torch.tensor(lab)\n    \nclass HMSCnn(nn.Module):\n    def __init__(self):\n        super(HMSCnn, self).__init__()\n        self.conv1 = nn.Conv2d(1, 32, kernel_size=3, stride=1, padding=1)\n        self.relu1 = nn.ReLU()\n        self.pool1 = nn.MaxPool2d(kernel_size=2, stride=2)\n\n        self.conv2 = nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1)\n        self.relu2 = nn.ReLU()\n        self.pool2 = nn.MaxPool2d(kernel_size=2, stride=2)\n\n        self.conv3 = nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1)\n        self.relu3 = nn.ReLU()\n        self.pool3 = nn.MaxPool2d(kernel_size=2, stride=2)\n\n        self.fc1 = nn.Linear(128 * 32 * 32, 256)\n        self.relu4 = nn.ReLU()\n        self.fc2 = nn.Linear(256, 128)\n        self.fc3 = nn.Linear(128, 6)\n\n    def forward(self, x):\n        x = self.pool1(self.relu1(self.conv1(x)))\n        x = self.pool2(self.relu2(self.conv2(x)))\n        x = self.pool3(self.relu3(self.conv3(x)))\n        x = x.view(-1, 128 * 32 * 32)\n        x = self.relu4(self.fc1(x))\n        x = self.fc2(x)\n        x = self.fc3(x)\n        return x\nmodel = HMSCnn()\nmodel = model.to(cfg.DEVICE)","metadata":{"execution":{"iopub.status.busy":"2024-01-19T14:17:19.272396Z","iopub.execute_input":"2024-01-19T14:17:19.272737Z","iopub.status.idle":"2024-01-19T14:17:21.772529Z","shell.execute_reply.started":"2024-01-19T14:17:19.272713Z","shell.execute_reply":"2024-01-19T14:17:21.771593Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"labels_map = dict()\nfor index, value in enumerate((sample_submission).columns[1:]):\n    labels_map[value] = index","metadata":{"execution":{"iopub.status.busy":"2024-01-19T14:29:24.732619Z","iopub.execute_input":"2024-01-19T14:29:24.733265Z","iopub.status.idle":"2024-01-19T14:29:24.738043Z","shell.execute_reply.started":"2024-01-19T14:29:24.733222Z","shell.execute_reply":"2024-01-19T14:29:24.737105Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def test_mod(model,dataloader):\n    model.eval()\n    predictions =pd.DataFrame() \n    with torch.no_grad():\n        for data,_ in tqdm(dataloader):\n            data = data.to(cfg.DEVICE)\n            output = model(data)\n            m = nn.Softmax(dim=1)\n            res = m(output)\n            predictions = pd.concat([predictions, pd.DataFrame(torch.Tensor.cpu(res).numpy(), columns = list(labels_map.keys()))], ignore_index=True)\n            \n        return predictions","metadata":{"execution":{"iopub.status.busy":"2024-01-19T14:29:25.844621Z","iopub.execute_input":"2024-01-19T14:29:25.845015Z","iopub.status.idle":"2024-01-19T14:29:25.851680Z","shell.execute_reply.started":"2024-01-19T14:29:25.844985Z","shell.execute_reply":"2024-01-19T14:29:25.850593Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def test_on_fold(fold):\n    model.load_state_dict(torch.load(f'/kaggle/input/hms-starter-training-cnn/hms_model_fold_{fold}.bin'))\n    test_set = HMSDataset(test)\n    test_loader = DataLoader(test_set,batch_size=cfg.BATCH_SIZE,shuffle=False,num_workers=0)\n    preds = test_mod(model,test_loader)\n    return preds","metadata":{"execution":{"iopub.status.busy":"2024-01-19T14:29:27.096153Z","iopub.execute_input":"2024-01-19T14:29:27.097030Z","iopub.status.idle":"2024-01-19T14:29:27.102628Z","shell.execute_reply.started":"2024-01-19T14:29:27.096997Z","shell.execute_reply":"2024-01-19T14:29:27.101463Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pred1 = test_on_fold(0)\npred2 = test_on_fold(1)\npred3 = test_on_fold(2)\npred4 = test_on_fold(3)\npred5 = test_on_fold(4)","metadata":{"execution":{"iopub.status.busy":"2024-01-19T14:29:27.624866Z","iopub.execute_input":"2024-01-19T14:29:27.625712Z","iopub.status.idle":"2024-01-19T14:29:56.524763Z","shell.execute_reply.started":"2024-01-19T14:29:27.625666Z","shell.execute_reply":"2024-01-19T14:29:56.523868Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"final_pred = (pred1+pred2+pred3+pred4+pred5)/5","metadata":{"execution":{"iopub.status.busy":"2024-01-19T14:30:23.377964Z","iopub.execute_input":"2024-01-19T14:30:23.378347Z","iopub.status.idle":"2024-01-19T14:30:23.384287Z","shell.execute_reply.started":"2024-01-19T14:30:23.378315Z","shell.execute_reply":"2024-01-19T14:30:23.383211Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample_submission.iloc[:,1:] = final_pred.values","metadata":{"execution":{"iopub.status.busy":"2024-01-19T14:32:48.371141Z","iopub.execute_input":"2024-01-19T14:32:48.371767Z","iopub.status.idle":"2024-01-19T14:32:48.382909Z","shell.execute_reply.started":"2024-01-19T14:32:48.371735Z","shell.execute_reply":"2024-01-19T14:32:48.382062Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample_submission","metadata":{"execution":{"iopub.status.busy":"2024-01-19T14:33:06.090362Z","iopub.execute_input":"2024-01-19T14:33:06.091344Z","iopub.status.idle":"2024-01-19T14:33:06.102880Z","shell.execute_reply.started":"2024-01-19T14:33:06.091307Z","shell.execute_reply":"2024-01-19T14:33:06.102045Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample_submission.to_csv('submission.csv',index=False)","metadata":{"execution":{"iopub.status.busy":"2024-01-19T14:33:25.650223Z","iopub.execute_input":"2024-01-19T14:33:25.650568Z","iopub.status.idle":"2024-01-19T14:33:25.658179Z","shell.execute_reply.started":"2024-01-19T14:33:25.650543Z","shell.execute_reply":"2024-01-19T14:33:25.657190Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}