{"metadata":{"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":59093,"databundleVersionId":7469972,"sourceType":"competition"},{"sourceId":7392775,"sourceType":"datasetVersion","datasetId":4297782},{"sourceId":7465251,"sourceType":"datasetVersion","datasetId":4317718},{"sourceId":7570342,"sourceType":"datasetVersion","datasetId":4407194},{"sourceId":7626715,"sourceType":"datasetVersion","datasetId":4382744},{"sourceId":7752365,"sourceType":"datasetVersion","datasetId":4417235}],"dockerImageVersionId":30636,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true},"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.10.12"},"papermill":{"default_parameters":{},"duration":101.739864,"end_time":"2024-03-03T17:15:15.283704","environment_variables":{},"exception":null,"input_path":"__notebook__.ipynb","output_path":"__notebook__.ipynb","parameters":{},"start_time":"2024-03-03T17:13:33.543840","version":"2.4.0"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Features+Head Ensemble Starter [LB 0.34] for HMS Brain Comp\nThis is Features+Head is a combination and ensemble Starter notebook for Kaggle's HMS brain comp. We can train 4 different models using:\n- Kaggle's spectrograms (CV 0.6123 – LB 0.41)\n- Chris's EEG spectrograms(modified version) (CV 0.6288 – LB 0.39)\n- Both Kaggle and EEG spectrograms (CV 0.5646 – LB 0.37)\n- Chris's [WaveNet][4] (CV 0.6992 - LB 0.41)\n\n**The Ensemble achieves LB 0.34** \n\nGreat discussion [here][5] by @KOLOO that led to the latest score!\n\nFeatures+Head Starter uses Chris Deotte's Kaggle dataset [here][1]. Also Uses Chris's EEG spectrograms [here][3] (modified version) \n\n### Train and Infer Tips\n\nThis notebook can be used both to train and submit (infer) to Kaggle LB. When training, you can set variable `submission = False` , you can also set `TEST_MODE = TRUE` to upload 500 samples queckly instead of the whole dataset for testing. \n\nTo train a specific model type, you should set `DATA_TYPE = 'both|eeg|kaggle|raw'`, `kaggle` to train on Kaggle's spectrograms, `eeg` to train on EEG's spectrograms, `both` to train on Kaggle's and EEG's spectrograms, `raw` to train on EEG's signal with WaveNet,\n\nFor submission after training models, you should save them in the LOAD_MODELS_FROM dataset, then run this notebook with `submission = True`.\n\nOnce we have all the models saved to LOAD_MODELS_FROM and ready ensemble, we should set `submission = True` and `ENSEMBLE = True` and set the models versions that we prior specified, as well as their `LBs` for weighted ensemble.\n\nThis notebook is made as generic as possible to expand and try different experiments.\n\nWhat you could do:\n- Change EfficientNetB(0-7) with `LOAD_BACKBONE_FROM`\n- Data augmentation by setting DataGenerator's parameter to `augment = True`\n- Different image configurations as input.\n- WaveNet model tuning.\n\n\nThis notebook is a direct descendent of Chris's notebook [here][2]\n\n[1]: https://www.kaggle.com/datasets/cdeotte/brain-spectrograms\n[2]: https://www.kaggle.com/code/cdeotte/efficientnetb2-starter-lb-0-57\n[3]: https://www.kaggle.com/datasets/nartaa/eeg-spectrograms\n[4]: https://www.kaggle.com/competitions/hms-harmful-brain-activity-classification/discussion/468684\n[5]: https://www.kaggle.com/competitions/hms-harmful-brain-activity-classification/discussion/477461","metadata":{"papermill":{"duration":0.009301,"end_time":"2024-03-03T17:13:37.231229","exception":false,"start_time":"2024-03-03T17:13:37.221928","status":"completed"},"tags":[]}},{"cell_type":"code","source":"import os, random\nimport tensorflow as tf\nimport tensorflow\nimport tensorflow.keras.backend as K\nimport pandas as pd, numpy as np\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras.models import load_model\n\nLOAD_BACKBONE_FROM = '/kaggle/input/efficientnetb-tf-keras/EfficientNetB2.h5'\nLOAD_MODELS_FROM = '/kaggle/input/features-head-starter-models/'\nVER = 47\nDATA_TYPE = 'both' # both|eeg|kaggle|raw\nTEST_MODE = False\nsubmission = True\n\n# Setup for ensemble\nENSEMBLE = True\nLBs = [0.37,0.39,0.41,0.41] # for weighted ensemble we use LBs of each model\nVERK = 43 # Kaggle's spectrogram model version\nVERB = 47 # Kaggle's and EEG's spectrogram model version\nVERE = 42 # EEG's spectrogram model version\nVERR = 37 # EEG's raw wavenet model version, trained on single GPU\n\nnp.random.seed(42)\nrandom.seed(42)\ntf.random.set_seed(42)\n\n# USE SINGLE GPU, MULTIPLE GPUS \ngpus = tf.config.list_physical_devices('GPU')\n# WE USE MIXED PRECISION\ntf.config.optimizer.set_experimental_options({\"auto_mixed_precision\": True})\nif len(gpus)>1:\n    strategy = tf.distribute.MirroredStrategy()\n    print(f'Using {len(gpus)} GPUs')\nelse:\n    strategy = tf.distribute.OneDeviceStrategy(device=\"/gpu:0\")\n    print(f'Using {len(gpus)} GPU')","metadata":{"execution":{"iopub.execute_input":"2024-03-03T17:13:37.249520Z","iopub.status.busy":"2024-03-03T17:13:37.248816Z","iopub.status.idle":"2024-03-03T17:13:52.256316Z","shell.execute_reply":"2024-03-03T17:13:52.255221Z"},"papermill":{"duration":15.019425,"end_time":"2024-03-03T17:13:52.258732","exception":false,"start_time":"2024-03-03T17:13:37.239307","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Load and create Non-Overlapping Eeg Id Train Data\nThe competition data description says that test data does not have multiple crops from the same `eeg_id`. Therefore we will train and validate using only 1 crop per `eeg_id`. There is a discussion about this [here][1].\n[1]: https://www.kaggle.com/competitions/hms-harmful-brain-activity-classification/discussion/467021","metadata":{"papermill":{"duration":0.008576,"end_time":"2024-03-03T17:13:52.276274","exception":false,"start_time":"2024-03-03T17:13:52.267698","status":"completed"},"tags":[]}},{"cell_type":"code","source":"TARGETS = ['seizure_vote', 'lpd_vote', 'gpd_vote', 'lrda_vote', 'grda_vote', 'other_vote']\nFEATS2 = ['Fp1','T3','C3','O1','Fp2','C4','T4','O2']\nFEAT2IDX = {x:y for x,y in zip(FEATS2,range(len(FEATS2)))}\n\ndef eeg_from_parquet(parquet_path):\n\n    eeg = pd.read_parquet(parquet_path, columns=FEATS2)\n    rows = len(eeg)\n    offset = (rows-10_000)//2\n    eeg = eeg.iloc[offset:offset+10_000]\n    data = np.zeros((10_000,len(FEATS2)))\n    for j,col in enumerate(FEATS2):\n        \n        # FILL NAN\n        x = eeg[col].values.astype('float32')\n        m = np.nanmean(x)\n        if np.isnan(x).mean()<1: x = np.nan_to_num(x,nan=m)\n        else: x[:] = 0\n        \n        data[:,j] = x\n\n    return data\n\ndef add_kl(data):\n    import torch\n    labels = data[TARGETS].values + 1e-5\n\n    # compute kl-loss with uniform distribution by pytorch\n    data['kl'] = torch.nn.functional.kl_div(\n        torch.log(torch.tensor(labels)),\n        torch.tensor([1 / 6] * 6),\n        reduction='none'\n    ).sum(dim=1).numpy()\n    return data\n\ndef reset_seed(seed):\n    np.random.seed(seed)\n    random.seed(seed)\n    tf.random.set_seed(seed)\n    \nif not submission:\n    train = pd.read_csv('/kaggle/input/hms-harmful-brain-activity-classification/train.csv')\n    TARGETS = ['seizure_vote', 'lpd_vote', 'gpd_vote', 'lrda_vote', 'grda_vote', 'other_vote']\n    META = ['spectrogram_id','spectrogram_label_offset_seconds','patient_id','expert_consensus']\n    train = train.groupby('eeg_id')[META+TARGETS\n                           ].agg({**{m:'first' for m in META},**{t:'sum' for t in TARGETS}}).reset_index() \n    train[TARGETS] = train[TARGETS]/train[TARGETS].values.sum(axis=1,keepdims=True)\n    train.columns = ['eeg_id','spec_id','offset','patient_id','target'] + TARGETS\n    train = add_kl(train)\n    print(train.head(1).to_string())","metadata":{"execution":{"iopub.execute_input":"2024-03-03T17:13:52.294962Z","iopub.status.busy":"2024-03-03T17:13:52.294371Z","iopub.status.idle":"2024-03-03T17:13:52.308315Z","shell.execute_reply":"2024-03-03T17:13:52.307515Z"},"papermill":{"duration":0.024968,"end_time":"2024-03-03T17:13:52.310258","exception":false,"start_time":"2024-03-03T17:13:52.285290","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Read Train Spectrograms and EEGs\n\nWe can read 3 file from Chris's [Kaggle dataset here][1] which contains all the 11k spectrograms. From Chris's modified EEG spectrogram [here][2]. From Chris's EEG signals [here][3]\n\n[1]: https://www.kaggle.com/datasets/cdeotte/brain-spectrograms\n[2]: https://www.kaggle.com/datasets/nartaa/eeg-spectrograms\n[3]: https://www.kaggle.com/datasets/cdeotte/brain-eegs","metadata":{"papermill":{"duration":0.007831,"end_time":"2024-03-03T17:13:52.325843","exception":false,"start_time":"2024-03-03T17:13:52.318012","status":"completed"},"tags":[]}},{"cell_type":"code","source":"%%time\nif not submission:\n    # FOR TESTING SET TEST_MODE TO TRUE\n    if TEST_MODE:\n        train = train.sample(500,random_state=42).reset_index(drop=True)\n        spectrograms = {}\n        for i,e in enumerate(train.spec_id.values):\n            if i%100==0: print(i,', ',end='')\n            x = pd.read_parquet(f'/kaggle/input/hms-harmful-brain-activity-classification/train_spectrograms/{e}.parquet')\n            spectrograms[e] = x.values\n        all_eegs = {}\n        for i,e in enumerate(train.eeg_id.values):\n            if i%100==0: print(i,', ',end='')\n            x = np.load(f'/kaggle/input/eeg-spectrograms/EEG_Spectrograms/{e}.npy')\n            all_eegs[e] = x\n        all_raw_eegs = {}\n        for i,e in enumerate(train.eeg_id.values):\n            if i%100==0: print(i,', ',end='')\n            x = eeg_from_parquet(f'/kaggle/input/hms-harmful-brain-activity-classification/train_eegs/{e}.parquet')              \n            all_raw_eegs[e] = x\n    else:\n        spectrograms = None\n        all_eegs = None\n        all_raw_eegs = None\n        if DATA_TYPE=='both' or DATA_TYPE=='kaggle':\n            spectrograms = np.load('/kaggle/input/brain-spectrograms/specs.npy',allow_pickle=True).item()\n        if DATA_TYPE=='both' or DATA_TYPE=='eeg':\n            all_eegs = np.load('/kaggle/input/eeg-spectrograms/eeg_specs.npy',allow_pickle=True).item()\n        if DATA_TYPE=='raw':\n            all_raw_eegs = np.load('/kaggle/input/brain-eegs/eegs.npy',allow_pickle=True).item()","metadata":{"execution":{"iopub.execute_input":"2024-03-03T17:13:52.342754Z","iopub.status.busy":"2024-03-03T17:13:52.342121Z","iopub.status.idle":"2024-03-03T17:13:52.352512Z","shell.execute_reply":"2024-03-03T17:13:52.351636Z"},"papermill":{"duration":0.021122,"end_time":"2024-03-03T17:13:52.354762","exception":false,"start_time":"2024-03-03T17:13:52.333640","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# DATA GENERATOR\nThis data generator outputs 512x512x3, the spectrogram and eeg images are concatenated all togother in a single image. For using data augmention you can set `augment = True` when creating the train data generator.","metadata":{"papermill":{"duration":0.007968,"end_time":"2024-03-03T17:13:52.370870","exception":false,"start_time":"2024-03-03T17:13:52.362902","status":"completed"},"tags":[]}},{"cell_type":"code","source":"import albumentations as albu\nfrom scipy.signal import butter, lfilter\n\nclass DataGenerator():\n    'Generates data for Keras'\n    def __init__(self, data, specs=None, eeg_specs=None, raw_eegs=None, augment=False, mode='train', data_type=DATA_TYPE): \n        self.data = data\n        self.augment = augment\n        self.mode = mode\n        self.data_type = data_type\n        self.specs = specs\n        self.eeg_specs = eeg_specs\n        self.raw_eegs = raw_eegs\n        self.on_epoch_end()\n        \n    def __len__(self):\n        return self.data.shape[0]\n\n    def __getitem__(self, index):\n        X, y = self.data_generation(index)\n        if self.augment: X = self.augmentation(X)\n        return X, y\n    \n    def __call__(self):\n        for i in range(self.__len__()):\n            yield self.__getitem__(i)\n            \n            if i == self.__len__()-1:\n                self.on_epoch_end()\n                \n    def on_epoch_end(self):\n        if self.mode=='train': \n            self.data = self.data.sample(frac=1).reset_index(drop=True)\n    \n    def data_generation(self, index):\n        if self.data_type == 'both':\n            X,y = self.generate_all_specs(index)\n        elif self.data_type == 'eeg' or self.data_type == 'kaggle':\n            X,y = self.generate_specs(index)\n        elif self.data_type == 'raw':\n            X,y = self.generate_raw(index)\n\n        return X,y\n    \n    def generate_all_specs(self, index):\n        X = np.zeros((512,512,3),dtype='float32')\n        y = np.zeros((6,),dtype='float32')\n        \n        row = self.data.iloc[index]\n        if self.mode=='test': \n            offset = 0\n        else:\n            offset = int(row.offset/2)\n            \n        eeg = self.eeg_specs[row.eeg_id]\n        spec = self.specs[row.spec_id]\n        \n        imgs = [spec[offset:offset+300,k*100:(k+1)*100].T for k in [0,2,1,3]] # to match kaggle with eeg\n        img = np.stack(imgs,axis=-1)\n        # LOG TRANSFORM SPECTROGRAM\n        img = np.clip(img,np.exp(-4),np.exp(8))\n        img = np.log(img)\n            \n        # STANDARDIZE PER IMAGE\n        img = np.nan_to_num(img, nan=0.0)    \n            \n        mn = img.flatten().min()\n        mx = img.flatten().max()\n        ep = 1e-5\n        img = 255 * (img - mn) / (mx - mn + ep)\n        \n        X[0_0+56:100+56,:256,0] = img[:,22:-22,0] # LL_k\n        X[100+56:200+56,:256,0] = img[:,22:-22,2] # RL_k\n        X[0_0+56:100+56,:256,1] = img[:,22:-22,1] # LP_k\n        X[100+56:200+56,:256,1] = img[:,22:-22,3] # RP_k\n        X[0_0+56:100+56,:256,2] = img[:,22:-22,2] # RL_k\n        X[100+56:200+56,:256,2] = img[:,22:-22,1] # LP_k\n        \n        X[0_0+56:100+56,256:,0] = img[:,22:-22,0] # LL_k\n        X[100+56:200+56,256:,0] = img[:,22:-22,2] # RL_k\n        X[0_0+56:100+56,256:,1] = img[:,22:-22,1] # LP_k\n        X[100+56:200+56,256:,1] = img[:,22:-22,3] # RP_K\n        \n        # EEG\n        img = eeg\n        mn = img.flatten().min()\n        mx = img.flatten().max()\n        ep = 1e-5\n        img = 255 * (img - mn) / (mx - mn + ep)\n        X[200+56:300+56,:256,0] = img[:,22:-22,0] # LL_e\n        X[300+56:400+56,:256,0] = img[:,22:-22,2] # RL_e\n        X[200+56:300+56,:256,1] = img[:,22:-22,1] # LP_e\n        X[300+56:400+56,:256,1] = img[:,22:-22,3] # RP_e\n        X[200+56:300+56,:256,2] = img[:,22:-22,2] # RL_e\n        X[300+56:400+56,:256,2] = img[:,22:-22,1] # LP_e\n        \n        X[200+56:300+56,256:,0] = img[:,22:-22,0] # LL_e\n        X[300+56:400+56,256:,0] = img[:,22:-22,2] # RL_e\n        X[200+56:300+56,256:,1] = img[:,22:-22,1] # LP_e\n        X[300+56:400+56,256:,1] = img[:,22:-22,3] # RP_e\n\n        if self.mode!='test':\n            y[:] = row[TARGETS]\n        \n        return X,y\n    \n    def generate_specs(self, index):\n        X = np.zeros((512,512,3),dtype='float32')\n        y = np.zeros((6,),dtype='float32')\n        \n        row = self.data.iloc[index]\n        if self.mode=='test': \n            offset = 0\n        else:\n            offset = int(row.offset/2)\n            \n        if self.data_type == 'eeg':\n            img = self.eeg_specs[row.eeg_id]\n        elif self.data_type == 'kaggle':\n            spec = self.specs[row.spec_id]\n            imgs = [spec[offset:offset+300,k*100:(k+1)*100].T for k in [0,2,1,3]] # to match kaggle with eeg\n            img = np.stack(imgs,axis=-1)\n            # LOG TRANSFORM SPECTROGRAM\n            img = np.clip(img,np.exp(-4),np.exp(8))\n            img = np.log(img)\n            \n            # STANDARDIZE PER IMAGE\n            img = np.nan_to_num(img, nan=0.0)    \n            \n        mn = img.flatten().min()\n        mx = img.flatten().max()\n        ep = 1e-5\n        img = 255 * (img - mn) / (mx - mn + ep)\n        \n        X[0_0+56:100+56,:256,0] = img[:,22:-22,0]\n        X[100+56:200+56,:256,0] = img[:,22:-22,2]\n        X[0_0+56:100+56,:256,1] = img[:,22:-22,1]\n        X[100+56:200+56,:256,1] = img[:,22:-22,3]\n        X[0_0+56:100+56,:256,2] = img[:,22:-22,2]\n        X[100+56:200+56,:256,2] = img[:,22:-22,1]\n        \n        X[0_0+56:100+56,256:,0] = img[:,22:-22,0]\n        X[100+56:200+56,256:,0] = img[:,22:-22,1]\n        X[0_0+56:100+56,256:,1] = img[:,22:-22,2]\n        X[100+56:200+56,256:,1] = img[:,22:-22,3]\n        \n        X[200+56:300+56,:256,0] = img[:,22:-22,0]\n        X[300+56:400+56,:256,0] = img[:,22:-22,1]\n        X[200+56:300+56,:256,1] = img[:,22:-22,2]\n        X[300+56:400+56,:256,1] = img[:,22:-22,3]\n        X[200+56:300+56,:256,2] = img[:,22:-22,3]\n        X[300+56:400+56,:256,2] = img[:,22:-22,2]\n        \n        X[200+56:300+56,256:,0] = img[:,22:-22,0]\n        X[300+56:400+56,256:,0] = img[:,22:-22,2]\n        X[200+56:300+56,256:,1] = img[:,22:-22,1]\n        X[300+56:400+56,256:,1] = img[:,22:-22,3]\n        \n        if self.mode!='test':\n            y[:] = row[TARGETS]\n        \n        return X,y\n    \n    def generate_raw(self,index):\n        X = np.zeros((10_000,8),dtype='float32')\n        y = np.zeros((6,),dtype='float32')\n        \n        row = self.data.iloc[index]\n        eeg = self.raw_eegs[row.eeg_id]\n            \n        # FEATURE ENGINEER\n        X[:,0] = eeg[:,FEAT2IDX['Fp1']] - eeg[:,FEAT2IDX['T3']]\n        X[:,1] = eeg[:,FEAT2IDX['T3']] - eeg[:,FEAT2IDX['O1']]\n            \n        X[:,2] = eeg[:,FEAT2IDX['Fp1']] - eeg[:,FEAT2IDX['C3']]\n        X[:,3] = eeg[:,FEAT2IDX['C3']] - eeg[:,FEAT2IDX['O1']]\n            \n        X[:,4] = eeg[:,FEAT2IDX['Fp2']] - eeg[:,FEAT2IDX['C4']]\n        X[:,5] = eeg[:,FEAT2IDX['C4']] - eeg[:,FEAT2IDX['O2']]\n            \n        X[:,6] = eeg[:,FEAT2IDX['Fp2']] - eeg[:,FEAT2IDX['T4']]\n        X[:,7] = eeg[:,FEAT2IDX['T4']] - eeg[:,FEAT2IDX['O2']]\n            \n        # STANDARDIZE\n        X = np.clip(X,-1024,1024)\n        X = np.nan_to_num(X, nan=0) / 32.0\n            \n        # BUTTER LOW-PASS FILTER\n        X = self.butter_lowpass_filter(X)\n        # Downsample\n        X = X[::5,:]\n        \n        if self.mode!='test':\n            y[:] = row[TARGETS]\n                \n        return X,y\n        \n    def butter_lowpass_filter(self, data, cutoff_freq=20, sampling_rate=200, order=4):\n        nyquist = 0.5 * sampling_rate\n        normal_cutoff = cutoff_freq / nyquist\n        b, a = butter(order, normal_cutoff, btype='low', analog=False)\n        filtered_data = lfilter(b, a, data, axis=0)\n        return filtered_data\n    \n    def resize(self, img,size):\n        composition = albu.Compose([\n                albu.Resize(size[0],size[1])\n            ])\n        return composition(image=img)['image']\n            \n    def augmentation(self, img):\n        composition = albu.Compose([\n                albu.HorizontalFlip(p=0.4)\n            ])\n        return composition(image=img)['image']","metadata":{"execution":{"iopub.execute_input":"2024-03-03T17:13:52.388578Z","iopub.status.busy":"2024-03-03T17:13:52.388270Z","iopub.status.idle":"2024-03-03T17:13:54.625646Z","shell.execute_reply":"2024-03-03T17:13:54.624742Z"},"papermill":{"duration":2.248907,"end_time":"2024-03-03T17:13:54.628134","exception":false,"start_time":"2024-03-03T17:13:52.379227","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# DISPLAY DATA GENERATOR\nBelow we display example data generator spectrogram images and raw EEG signals.","metadata":{"papermill":{"duration":0.008885,"end_time":"2024-03-03T17:13:54.646135","exception":false,"start_time":"2024-03-03T17:13:54.637250","status":"completed"},"tags":[]}},{"cell_type":"code","source":"if not submission and DATA_TYPE!='raw':\n    gen = DataGenerator(train, augment=False, specs=spectrograms, eeg_specs=all_eegs, data_type=DATA_TYPE)\n    for x,y in gen:\n        break\n    plt.imshow(x[:,:,0])\n    plt.title(f'Target = {y.round(1)}',size=12)\n    plt.yticks([])\n    plt.ylabel('Frequencies (Hz)',size=12)\n    plt.xlabel('Time (sec)',size=12)\n    plt.show()\n    \nif not submission and DATA_TYPE=='raw':\n    gen = DataGenerator(train, raw_eegs=all_raw_eegs, data_type=DATA_TYPE)\n    for x,y in gen:\n        plt.figure(figsize=(20,4))\n        offset = 0\n        for j in range(x.shape[-1]):\n            if j!=0: offset -= x[:,j].min()\n            plt.plot(range(2_000),x[:,j]+offset,label=f'feature {j+1}')\n            offset += x[:,j].max()\n        plt.legend()\n        plt.show()\n        break","metadata":{"execution":{"iopub.execute_input":"2024-03-03T17:13:54.665173Z","iopub.status.busy":"2024-03-03T17:13:54.664626Z","iopub.status.idle":"2024-03-03T17:13:54.674213Z","shell.execute_reply":"2024-03-03T17:13:54.673143Z"},"papermill":{"duration":0.021571,"end_time":"2024-03-03T17:13:54.676501","exception":false,"start_time":"2024-03-03T17:13:54.654930","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# TRAINING","metadata":{"papermill":{"duration":0.009379,"end_time":"2024-03-03T17:13:54.694693","exception":false,"start_time":"2024-03-03T17:13:54.685314","status":"completed"},"tags":[]}},{"cell_type":"markdown","source":"## LEARNING RATE","metadata":{"papermill":{"duration":0.007933,"end_time":"2024-03-03T17:13:54.710721","exception":false,"start_time":"2024-03-03T17:13:54.702788","status":"completed"},"tags":[]}},{"cell_type":"code","source":"\nif not submission:\n\n    def lrfn(epoch):\n        e3 = 1e-3 if DATA_TYPE=='raw' else 1e-4\n        return [1e-3,1e-3,e3,1e-4,1e-5][epoch]\n\n    LR = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose = True)\n    \n    def lrfn2(epoch):\n        return [1e-5,1e-5,1e-6][epoch]\n\n    LR2 = tf.keras.callbacks.LearningRateScheduler(lrfn2, verbose = True)","metadata":{"execution":{"iopub.execute_input":"2024-03-03T17:13:54.728610Z","iopub.status.busy":"2024-03-03T17:13:54.728321Z","iopub.status.idle":"2024-03-03T17:13:54.734037Z","shell.execute_reply":"2024-03-03T17:13:54.733151Z"},"papermill":{"duration":0.017031,"end_time":"2024-03-03T17:13:54.736108","exception":false,"start_time":"2024-03-03T17:13:54.719077","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## MODEL AND UTILITY FUNCTIONS","metadata":{"papermill":{"duration":0.007987,"end_time":"2024-03-03T17:13:54.752857","exception":false,"start_time":"2024-03-03T17:13:54.744870","status":"completed"},"tags":[]}},{"cell_type":"code","source":"from tensorflow.keras.layers import Input, Dense, Multiply, Add, Conv1D, Concatenate\n\ndef build_model():  \n    inp = tf.keras.layers.Input((512,512,3))\n    base_model = load_model(f'{LOAD_BACKBONE_FROM}')    \n    x = base_model(inp)\n    x = tf.keras.layers.GlobalAveragePooling2D()(x)\n    output = tf.keras.layers.Dense(6,activation='softmax', dtype='float32')(x)\n    model = tf.keras.Model(inputs=inp, outputs=output)\n    opt = tf.keras.optimizers.Adam(learning_rate = 1e-3)\n    loss = tf.keras.losses.KLDivergence()\n    model.compile(loss=loss, optimizer=opt)  \n    return model\n\ndef score(y_true, y_pred):\n    kl = tf.keras.metrics.KLDivergence()\n    return kl(y_true, y_pred)\n\ndef wave_block(x, filters, kernel_size, n):\n    dilation_rates = [2**i for i in range(n)]\n    x = Conv1D(filters = filters,\n               kernel_size = 1,\n               padding = 'same')(x)\n    res_x = x\n    for dilation_rate in dilation_rates:\n        tanh_out = Conv1D(filters = filters,\n                          kernel_size = kernel_size,\n                          padding = 'same', \n                          activation = 'tanh', \n                          dilation_rate = dilation_rate)(x)\n        sigm_out = Conv1D(filters = filters,\n                          kernel_size = kernel_size,\n                          padding = 'same',\n                          activation = 'sigmoid', \n                          dilation_rate = dilation_rate)(x)\n        x = Multiply()([tanh_out, sigm_out])\n        x = Conv1D(filters = filters,\n                   kernel_size = 1,\n                   padding = 'same')(x)\n        res_x = Add()([res_x, x])\n    return res_x\n\ndef build_wave_model():\n        \n    # INPUT \n    inp = tf.keras.Input(shape=(2_000,8))\n    \n    ############\n    # FEATURE EXTRACTION SUB MODEL\n    inp2 = tf.keras.Input(shape=(2_000,1))\n    x = wave_block(inp2, 8, 4, 6)\n    x = wave_block(x, 16, 4, 6)\n    x = wave_block(x, 32, 4, 6)\n    x = wave_block(x, 64, 4, 6)\n    model2 = tf.keras.Model(inputs=inp2, outputs=x)\n    ###########\n    \n    # LEFT TEMPORAL CHAIN\n    x1 = model2(inp[:,:,0:1])\n    x1 = tf.keras.layers.GlobalAveragePooling1D()(x1)\n    x2 = model2(inp[:,:,1:2])\n    x2 = tf.keras.layers.GlobalAveragePooling1D()(x2)\n    z1 = tf.keras.layers.Average()([x1,x2])\n    \n    # LEFT PARASAGITTAL CHAIN\n    x1 = model2(inp[:,:,2:3])\n    x1 = tf.keras.layers.GlobalAveragePooling1D()(x1)\n    x2 = model2(inp[:,:,3:4])\n    x2 = tf.keras.layers.GlobalAveragePooling1D()(x2)\n    z2 = tf.keras.layers.Average()([x1,x2])\n    \n    # RIGHT PARASAGITTAL CHAIN\n    x1 = model2(inp[:,:,4:5])\n    x1 = tf.keras.layers.GlobalAveragePooling1D()(x1)\n    x2 = model2(inp[:,:,5:6])\n    x2 = tf.keras.layers.GlobalAveragePooling1D()(x2)\n    z3 = tf.keras.layers.Average()([x1,x2])\n    \n    # RIGHT TEMPORAL CHAIN\n    x1 = model2(inp[:,:,6:7])\n    x1 = tf.keras.layers.GlobalAveragePooling1D()(x1)\n    x2 = model2(inp[:,:,7:8])\n    x2 = tf.keras.layers.GlobalAveragePooling1D()(x2)\n    z4 = tf.keras.layers.Average()([x1,x2])\n    \n    # COMBINE CHAINS\n    y = tf.keras.layers.Concatenate()([z1,z2,z3,z4])\n    y = tf.keras.layers.Dense(64, activation='relu')(y)\n    y = tf.keras.layers.Dense(6,activation='softmax', dtype='float32')(y)\n    \n    # COMPILE MODEL\n    model = tf.keras.Model(inputs=inp, outputs=y)\n    opt = tf.keras.optimizers.Adam(learning_rate = 1e-3)\n    loss = tf.keras.losses.KLDivergence()\n    model.compile(loss=loss, optimizer = opt)\n    \n    return model\n\ndef plot_hist(hist):\n    metrics = ['loss']\n    for i,metric in enumerate(metrics):\n        plt.figure(figsize=(10,4))\n        plt.subplot(1,2,i+1)\n        plt.plot(hist[metric])\n        plt.plot(hist[f'val_{metric}'])\n        plt.title(f'{metric}',size=12)\n        plt.ylabel(f'{metric}',size=12)\n        plt.xlabel('epoch',size=12)\n        plt.legend([\"train\", \"validation\"], loc=\"upper left\")\n        plt.show()","metadata":{"execution":{"iopub.execute_input":"2024-03-03T17:13:54.772009Z","iopub.status.busy":"2024-03-03T17:13:54.771692Z","iopub.status.idle":"2024-03-03T17:13:54.798148Z","shell.execute_reply":"2024-03-03T17:13:54.797401Z"},"papermill":{"duration":0.038778,"end_time":"2024-03-03T17:13:54.800238","exception":false,"start_time":"2024-03-03T17:13:54.761460","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## TRANSFER LEARNING","metadata":{"papermill":{"duration":0.008661,"end_time":"2024-03-03T17:13:54.817886","exception":false,"start_time":"2024-03-03T17:13:54.809225","status":"completed"},"tags":[]}},{"cell_type":"code","source":"from sklearn.model_selection import KFold, GroupKFold\nimport tensorflow.keras.backend as K, gc\n\nif not submission:\n    # for CV scores setting random seed works for single GPU only\n    reset_seed(42)\n    all_oof = []\n    all_true = []\n    losses = []\n    val_losses = []\n    total_hist = {}\n\n    gkf = GroupKFold(n_splits=5)\n    for i, (train_index, valid_index) in enumerate(gkf.split(train, train.target, train.patient_id)):   \n        \n        print('#'*25)\n        print(f'### Fold {i+1}')\n        \n        data, val = train.iloc[train_index],train.iloc[valid_index]\n        train_gen = DataGenerator(data, augment=False, specs=spectrograms, eeg_specs=all_eegs, raw_eegs=all_raw_eegs)\n        valid_gen = DataGenerator(val, mode='valid', specs=spectrograms, eeg_specs=all_eegs, raw_eegs=all_raw_eegs)\n        data = data[data['kl']<5.5]\n        train_gen2 = DataGenerator(data, augment=False, specs=spectrograms, eeg_specs=all_eegs, raw_eegs=all_raw_eegs)\n        in_shape = (2000,8) if DATA_TYPE=='raw' else (512,512,3)\n        EPOCHS = 5\n        BATCH_SIZE_PER_REPLICA = 8\n        BATCH_SIZE = BATCH_SIZE_PER_REPLICA * strategy.num_replicas_in_sync\n\n        train_dataset = tf.data.Dataset.from_generator(generator=train_gen, \n                                                   output_signature=(tf.TensorSpec(shape=in_shape, dtype=tf.float32),\n                                                                     tf.TensorSpec(shape=(6,), dtype=tf.float32))).batch(BATCH_SIZE).prefetch(tf.data.AUTOTUNE)\n        val_dataset = tf.data.Dataset.from_generator(generator=valid_gen, \n                                                   output_signature=(tf.TensorSpec(shape=in_shape, dtype=tf.float32),\n                                                                     tf.TensorSpec(shape=(6,), dtype=tf.float32))).batch(BATCH_SIZE).prefetch(tf.data.AUTOTUNE)\n        train_dataset2 = tf.data.Dataset.from_generator(generator=train_gen2, \n                                                   output_signature=(tf.TensorSpec(shape=in_shape, dtype=tf.float32),\n                                                                     tf.TensorSpec(shape=(6,), dtype=tf.float32))).batch(BATCH_SIZE).prefetch(tf.data.AUTOTUNE)\n            \n        print(f'### train size {len(train_index)}, valid size {len(valid_index)}')\n        print('#'*25)\n        \n        K.clear_session()\n        with strategy.scope():\n            if DATA_TYPE=='raw':\n                model = build_wave_model()\n            else:\n                model = build_model()\n        \n        hist = model.fit(train_dataset, validation_data = val_dataset, \n                         epochs=EPOCHS, callbacks=[LR])\n        print(f'### seconds stage train size {len(data)}, valid size {len(val)}')\n        print('#'*25)\n        hist2 = model.fit(train_dataset2, validation_data = val_dataset, \n                         epochs=3, callbacks=[LR2])\n        losses.append(hist.history['loss']+hist2.history['loss'])\n        val_losses.append(hist.history['val_loss']+hist2.history['val_loss'])\n        with strategy.scope():\n            model.save_weights(f'model_{DATA_TYPE}_{VER}_{i}.weights.h5')\n        oof = model.predict(val_dataset, verbose=1)\n        all_oof.append(oof)\n        all_true.append(train.iloc[valid_index][TARGETS].values)    \n        del model, oof\n        gc.collect()\n        \n    total_hist['loss'] = np.mean(losses,axis=0)\n    total_hist['val_loss'] = np.mean(val_losses,axis=0)\n    all_oof = np.concatenate(all_oof)\n    all_true = np.concatenate(all_true)\n    plot_hist(total_hist)\n    print('#'*25)\n    print(f'CV KL SCORE: {score(all_true,all_oof)}')","metadata":{"execution":{"iopub.execute_input":"2024-03-03T17:13:54.837383Z","iopub.status.busy":"2024-03-03T17:13:54.836654Z","iopub.status.idle":"2024-03-03T17:13:54.857113Z","shell.execute_reply":"2024-03-03T17:13:54.856175Z"},"papermill":{"duration":0.032338,"end_time":"2024-03-03T17:13:54.859116","exception":false,"start_time":"2024-03-03T17:13:54.826778","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Infer Test and Create Submission CSV\nInfer the test data and create a `submission.csv` file.","metadata":{"papermill":{"duration":0.008533,"end_time":"2024-03-03T17:13:54.876670","exception":false,"start_time":"2024-03-03T17:13:54.868137","status":"completed"},"tags":[]}},{"cell_type":"code","source":"import pywt, librosa\n\nUSE_WAVELET = None \n\nNAMES = ['LL','LP','RP','RR']\n\nFEATS = [['Fp1','F7','T3','T5','O1'],\n         ['Fp1','F3','C3','P3','O1'],\n         ['Fp2','F8','T4','T6','O2'],\n         ['Fp2','F4','C4','P4','O2']]\n\n# DENOISE FUNCTION\ndef maddest(d, axis=None):\n    return np.mean(np.absolute(d - np.mean(d, axis)), axis)\n\ndef denoise(x, wavelet='haar', level=1):    \n    coeff = pywt.wavedec(x, wavelet, mode=\"per\")\n    sigma = (1/0.6745) * maddest(coeff[-level])\n\n    uthresh = sigma * np.sqrt(2*np.log(len(x)))\n    coeff[1:] = (pywt.threshold(i, value=uthresh, mode='hard') for i in coeff[1:])\n\n    ret=pywt.waverec(coeff, wavelet, mode='per')\n    \n    return ret\n\nimport librosa\n\ndef spectrogram_from_eeg(parquet_path, display=False):\n    \n    # LOAD MIDDLE 50 SECONDS OF EEG SERIES\n    eeg = pd.read_parquet(parquet_path)\n    middle = (len(eeg)-10_000)//2\n    eeg = eeg.iloc[middle:middle+10_000]\n    \n    # VARIABLE TO HOLD SPECTROGRAM\n    img = np.zeros((100,300,4),dtype='float32')\n    \n    if display: plt.figure(figsize=(10,7))\n    signals = []\n    for k in range(4):\n        COLS = FEATS[k]\n        \n        for kk in range(4):\n            # FILL NANS\n            x1 = eeg[COLS[kk]].values\n            x2 = eeg[COLS[kk+1]].values\n            m = np.nanmean(x1)\n            if np.isnan(x1).mean()<1: x1 = np.nan_to_num(x1,nan=m)\n            else: x1[:] = 0\n            m = np.nanmean(x2)\n            if np.isnan(x2).mean()<1: x2 = np.nan_to_num(x2,nan=m)\n            else: x2[:] = 0\n                \n            # COMPUTE PAIR DIFFERENCES\n            x = x1 - x2\n\n            # DENOISE\n            if USE_WAVELET:\n                x = denoise(x, wavelet=USE_WAVELET)\n            signals.append(x)\n\n            # RAW SPECTROGRAM\n            mel_spec = librosa.feature.melspectrogram(y=x, sr=200, hop_length=len(x)//300, \n                  n_fft=1024, n_mels=100, fmin=0, fmax=20, win_length=128)\n            \n            # LOG TRANSFORM\n            width = (mel_spec.shape[1]//30)*30\n            mel_spec_db = librosa.power_to_db(mel_spec, ref=np.max).astype(np.float32)[:,:width]\n            img[:,:,k] += mel_spec_db\n                \n        # AVERAGE THE 4 MONTAGE DIFFERENCES\n        img[:,:,k] /= 4.0\n        \n        if display:\n            plt.subplot(2,2,k+1)\n            plt.imshow(img[:,:,k],aspect='auto',origin='lower')\n            \n    if display: \n        plt.show()\n        plt.figure(figsize=(10,5))\n        offset = 0\n        for k in range(4):\n            if k>0: offset -= signals[3-k].min()\n            plt.plot(range(10_000),signals[k]+offset,label=NAMES[3-k])\n            offset += signals[3-k].max()\n        plt.legend()\n        plt.show()\n        \n    return img","metadata":{"_kg_hide-input":true,"execution":{"iopub.execute_input":"2024-03-03T17:13:54.895735Z","iopub.status.busy":"2024-03-03T17:13:54.895014Z","iopub.status.idle":"2024-03-03T17:13:54.918570Z","shell.execute_reply":"2024-03-03T17:13:54.917840Z"},"papermill":{"duration":0.035441,"end_time":"2024-03-03T17:13:54.920514","exception":false,"start_time":"2024-03-03T17:13:54.885073","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"if submission:\n    test = pd.read_csv('/kaggle/input/hms-harmful-brain-activity-classification/test.csv')\n    print('Test shape',test.shape)\n    test.head()","metadata":{"execution":{"iopub.execute_input":"2024-03-03T17:13:54.942336Z","iopub.status.busy":"2024-03-03T17:13:54.942033Z","iopub.status.idle":"2024-03-03T17:13:54.957025Z","shell.execute_reply":"2024-03-03T17:13:54.955966Z"},"papermill":{"duration":0.028182,"end_time":"2024-03-03T17:13:54.959119","exception":false,"start_time":"2024-03-03T17:13:54.930937","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# READ ALL SPECTROGRAMS\nif submission:\n    PATH2 = '/kaggle/input/hms-harmful-brain-activity-classification/test_spectrograms/'\n    files2 = os.listdir(PATH2)\n    print(f'There are {len(files2)} test spectrogram parquets')\n    \n    spectrograms2 = {}\n    for i,f in enumerate(files2):\n        if i%100==0: print(i,', ',end='')\n        tmp = pd.read_parquet(f'{PATH2}{f}')\n        name = int(f.split('.')[0])\n        spectrograms2[name] = tmp.iloc[:,1:].values\n    \n    # RENAME FOR DATA GENERATOR\n    test = test.rename({'spectrogram_id':'spec_id'},axis=1)","metadata":{"execution":{"iopub.execute_input":"2024-03-03T17:13:54.978630Z","iopub.status.busy":"2024-03-03T17:13:54.977867Z","iopub.status.idle":"2024-03-03T17:13:55.203021Z","shell.execute_reply":"2024-03-03T17:13:55.202255Z"},"papermill":{"duration":0.237311,"end_time":"2024-03-03T17:13:55.205190","exception":false,"start_time":"2024-03-03T17:13:54.967879","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# READ ALL EEG SPECTROGRAMS\nif submission:\n    PATH2 = '/kaggle/input/hms-harmful-brain-activity-classification/test_eegs/'\n    DISPLAY = 0\n    EEG_IDS2 = test.eeg_id.unique()\n    all_eegs2 = {}\n\n    print('Converting Test EEG to Spectrograms...'); print()\n    for i,eeg_id in enumerate(EEG_IDS2):\n        \n        # CREATE SPECTROGRAM FROM EEG PARQUET\n        img = spectrogram_from_eeg(f'{PATH2}{eeg_id}.parquet', i<DISPLAY)\n        all_eegs2[eeg_id] = img","metadata":{"execution":{"iopub.execute_input":"2024-03-03T17:13:55.224611Z","iopub.status.busy":"2024-03-03T17:13:55.223942Z","iopub.status.idle":"2024-03-03T17:14:05.529229Z","shell.execute_reply":"2024-03-03T17:14:05.527757Z"},"papermill":{"duration":10.319308,"end_time":"2024-03-03T17:14:05.533196","exception":false,"start_time":"2024-03-03T17:13:55.213888","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# READ ALL RAW EEG SIGNALS\nif submission :\n    all_raw_eegs2 = {}\n    EEG_IDS2 = test.eeg_id.unique()\n    PATH2 = '/kaggle/input/hms-harmful-brain-activity-classification/test_eegs/'\n\n    print('Processing Test EEG parquets...'); print()\n    for i,eeg_id in enumerate(EEG_IDS2):\n        \n        # SAVE EEG TO PYTHON DICTIONARY OF NUMPY ARRAYS\n        data = eeg_from_parquet(f'{PATH2}{eeg_id}.parquet')\n        all_raw_eegs2[eeg_id] = data","metadata":{"execution":{"iopub.execute_input":"2024-03-03T17:14:05.577468Z","iopub.status.busy":"2024-03-03T17:14:05.576207Z","iopub.status.idle":"2024-03-03T17:14:05.611246Z","shell.execute_reply":"2024-03-03T17:14:05.609992Z"},"papermill":{"duration":0.061557,"end_time":"2024-03-03T17:14:05.615731","exception":false,"start_time":"2024-03-03T17:14:05.554174","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Submission ON TEST without ensemble\nif submission and not ENSEMBLE:\n    preds = []\n    \n    if DATA_TYPE=='raw':\n        test_gen = DataGenerator(test, mode='test', raw_eegs=all_raw_eegs2)\n        in_shape = (2000,8)\n    else:\n        test_gen = DataGenerator(test, mode='test', specs = spectrograms2, eeg_specs = all_eegs2)\n        in_shape = (512,512,3)\n    \n    test_dataset = tf.data.Dataset.from_generator(generator=test_gen, \n                                               output_signature=(tf.TensorSpec(shape=in_shape, dtype=tf.float32),\n                                                                 tf.TensorSpec(shape=(6,), dtype=tf.float32))).batch(64).prefetch(tf.data.AUTOTUNE)\n    if DATA_TYPE=='raw':\n        model = build_wave_model()\n    else:\n        model = build_model()\n\n    for i in range(5):\n        print(f'Fold {i+1}')\n        model.load_weights(f'{LOAD_MODELS_FROM}model_{DATA_TYPE}_{VER}_{i}.weights.h5')\n        pred = model.predict(test_dataset, verbose=1)\n        preds.append(pred)\n        \n    pred = np.mean(preds,axis=0)\n    print('Test preds shape',pred.shape)","metadata":{"execution":{"iopub.execute_input":"2024-03-03T17:14:05.659866Z","iopub.status.busy":"2024-03-03T17:14:05.659560Z","iopub.status.idle":"2024-03-03T17:14:05.669348Z","shell.execute_reply":"2024-03-03T17:14:05.668407Z"},"papermill":{"duration":0.033962,"end_time":"2024-03-03T17:14:05.671441","exception":false,"start_time":"2024-03-03T17:14:05.637479","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Submission ON TEST with ensemble\nif submission and ENSEMBLE:\n    preds = []\n    test_gen_kaggle = DataGenerator(test, mode='test', data_type='kaggle', specs = spectrograms2, eeg_specs = all_eegs2)\n    test_dataset_kaggle = tf.data.Dataset.from_generator(generator=test_gen_kaggle, \n                                               output_signature=(tf.TensorSpec(shape=(512,512,3), dtype=tf.float32),\n                                                                 tf.TensorSpec(shape=(6,), dtype=tf.float32))).batch(64).prefetch(tf.data.AUTOTUNE)\n    test_gen_both = DataGenerator(test, mode='test', data_type='both', specs = spectrograms2, eeg_specs = all_eegs2)\n    test_dataset_both = tf.data.Dataset.from_generator(generator=test_gen_both, \n                                               output_signature=(tf.TensorSpec(shape=(512,512,3), dtype=tf.float32),\n                                                                 tf.TensorSpec(shape=(6,), dtype=tf.float32))).batch(64).prefetch(tf.data.AUTOTUNE)\n\n    test_gen_eeg = DataGenerator(test, mode='test', data_type='eeg', specs = spectrograms2, eeg_specs = all_eegs2)\n    test_dataset_eeg = tf.data.Dataset.from_generator(generator=test_gen_eeg, \n                                               output_signature=(tf.TensorSpec(shape=(512,512,3), dtype=tf.float32),\n                                                                 tf.TensorSpec(shape=(6,), dtype=tf.float32))).batch(64).prefetch(tf.data.AUTOTUNE)\n    test_gen_raw = DataGenerator(test, mode='test', data_type='raw', raw_eegs=all_raw_eegs2)\n    test_dataset_raw = tf.data.Dataset.from_generator(generator=test_gen_raw, \n                                               output_signature=(tf.TensorSpec(shape=(2000,8), dtype=tf.float32),\n                                                                 tf.TensorSpec(shape=(6,), dtype=tf.float32))).batch(64).prefetch(tf.data.AUTOTUNE)\n \n    # LB SCORE FOR EACH MODEL\n    lbs = 1 - np.array(LBs)\n    weights = lbs/lbs.sum()\n    model = build_model()\n    model_wave = build_wave_model()\n\n    for i in range(5):\n        print(f'Fold {i+1}')\n        \n        model.load_weights(f'{LOAD_MODELS_FROM}model_kaggle_{VERK}_{i}.weights.h5')\n        pred_kaggle = model.predict(test_dataset_kaggle, verbose=1)\n        \n        model.load_weights(f'{LOAD_MODELS_FROM}model_both_{VERB}_{i}.weights.h5')\n        pred_both = model.predict(test_dataset_both, verbose=1)\n        \n        model.load_weights(f'{LOAD_MODELS_FROM}model_eeg_{VERE}_{i}.weights.h5')\n        pred_eeg = model.predict(test_dataset_eeg, verbose=1)\n        \n        model_wave.load_weights(f'{LOAD_MODELS_FROM}model_raw_{VERR}_{i}.weights.h5')\n        pred_raw = model_wave.predict(test_dataset_raw, verbose=1)\n        \n        pred = np.array([pred_both,pred_eeg,pred_kaggle,pred_raw])\n        pred = np.average(pred,axis=0,weights=weights)\n        preds.append(pred)\n        \n    pred = np.mean(preds,axis=0)\n    print('Test preds shape',pred.shape)","metadata":{"execution":{"iopub.execute_input":"2024-03-03T17:14:05.691783Z","iopub.status.busy":"2024-03-03T17:14:05.691069Z","iopub.status.idle":"2024-03-03T17:15:12.065056Z","shell.execute_reply":"2024-03-03T17:15:12.063899Z"},"papermill":{"duration":66.385954,"end_time":"2024-03-03T17:15:12.067289","exception":false,"start_time":"2024-03-03T17:14:05.681335","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"if submission:\n    sub = pd.DataFrame({'eeg_id':test.eeg_id.values})\n    sub[TARGETS] = pred\n    sub.to_csv('submission.csv',index=False)\n    print('Submissionn shape',sub.shape)\n    print()\n    print(sub.head().to_string())","metadata":{"execution":{"iopub.execute_input":"2024-03-03T17:15:12.093657Z","iopub.status.busy":"2024-03-03T17:15:12.092996Z","iopub.status.idle":"2024-03-03T17:15:12.108476Z","shell.execute_reply":"2024-03-03T17:15:12.107424Z"},"papermill":{"duration":0.030287,"end_time":"2024-03-03T17:15:12.110333","exception":false,"start_time":"2024-03-03T17:15:12.080046","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# SANITY CHECK TO CONFIRM PREDICTIONS SUM TO ONE\nif submission:\n    print(sub.iloc[:,-6:].sum(axis=1).to_string())","metadata":{"execution":{"iopub.execute_input":"2024-03-03T17:15:12.135518Z","iopub.status.busy":"2024-03-03T17:15:12.134922Z","iopub.status.idle":"2024-03-03T17:15:12.141103Z","shell.execute_reply":"2024-03-03T17:15:12.140175Z"},"papermill":{"duration":0.020742,"end_time":"2024-03-03T17:15:12.143017","exception":false,"start_time":"2024-03-03T17:15:12.122275","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]}]}