{"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":"nvidiaTeslaT4","dataSources":[{"sourceId":59093,"databundleVersionId":7469972,"sourceType":"competition"},{"sourceId":7392733,"sourceType":"datasetVersion","datasetId":4297749},{"sourceId":7392775,"sourceType":"datasetVersion","datasetId":4297782},{"sourceId":7402356,"sourceType":"datasetVersion","datasetId":4304475},{"sourceId":7403069,"sourceType":"datasetVersion","datasetId":4304949},{"sourceId":7447509,"sourceType":"datasetVersion","datasetId":4334995},{"sourceId":7450712,"sourceType":"datasetVersion","datasetId":4336944},{"sourceId":7498245,"sourceType":"datasetVersion","datasetId":4330042},{"sourceId":158958765,"sourceType":"kernelVersion"},{"sourceId":159333316,"sourceType":"kernelVersion"},{"sourceId":159396114,"sourceType":"kernelVersion"},{"sourceId":160750808,"sourceType":"kernelVersion"}],"dockerImageVersionId":30636,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import warnings\nwarnings.filterwarnings(\"ignore\")\nimport os, gc\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"0,1\"\nimport time\nimport math\nimport json\nimport tensorflow as tf\nimport pandas as pd, numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sb\nprint('TensorFlow version =',tf.__version__)\n\n# USE MULTIPLE GPUS\ngpus = tf.config.list_physical_devices('GPU')\nif len(gpus)<=1: \n    strategy = tf.distribute.OneDeviceStrategy(device=\"/gpu:0\")\n    print(f'Using {len(gpus)} GPU')\nelse: \n    strategy = tf.distribute.MirroredStrategy()\n    print(f'Using {len(gpus)} GPUs')\n\nVER = 5\n\n# IF THIS EQUALS NONE, THEN WE TRAIN NEW MODELS\n# IF THIS EQUALS DISK PATH, THEN WE LOAD PREVIOUSLY TRAINED MODELS\nLOAD_MODELS_FROM = '/kaggle/input/brain-efficientnet-models-v3-v4-v5/'\n\nUSE_KAGGLE_SPECTROGRAMS = True\nUSE_EEG_SPECTROGRAMS = True","metadata":{"execution":{"iopub.status.busy":"2024-01-28T15:43:11.528015Z","iopub.execute_input":"2024-01-28T15:43:11.528286Z","iopub.status.idle":"2024-01-28T15:43:26.272481Z","shell.execute_reply.started":"2024-01-28T15:43:11.528261Z","shell.execute_reply":"2024-01-28T15:43:26.271495Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# USE MIXED PRECISION\nMIX = True\nif MIX:\n    tf.config.optimizer.set_experimental_options({\"auto_mixed_precision\": True})\n    print('Mixed precision enabled')\nelse:\n    print('Using full precision')","metadata":{"execution":{"iopub.status.busy":"2024-01-28T15:43:26.274132Z","iopub.execute_input":"2024-01-28T15:43:26.274670Z","iopub.status.idle":"2024-01-28T15:43:26.280198Z","shell.execute_reply.started":"2024-01-28T15:43:26.274641Z","shell.execute_reply":"2024-01-28T15:43:26.279198Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = pd.read_csv('/kaggle/input/hms-harmful-brain-activity-classification/train.csv')\nTARGETS = df.columns[-6:]\nprint('Train shape:', df.shape )\nprint('Targets', list(TARGETS))\ndf.head()","metadata":{"execution":{"iopub.status.busy":"2024-01-28T15:43:26.281506Z","iopub.execute_input":"2024-01-28T15:43:26.281906Z","iopub.status.idle":"2024-01-28T15:43:26.601456Z","shell.execute_reply.started":"2024-01-28T15:43:26.281863Z","shell.execute_reply":"2024-01-28T15:43:26.600555Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = df.groupby('eeg_id')[['spectrogram_id','spectrogram_label_offset_seconds']].agg(\n    {'spectrogram_id':'first','spectrogram_label_offset_seconds':'min'})\ntrain.columns = ['spec_id','min']\n\ntmp = df.groupby('eeg_id')[['spectrogram_id','spectrogram_label_offset_seconds']].agg(\n    {'spectrogram_label_offset_seconds':'max'})\ntrain['max'] = tmp\n\ntmp = df.groupby('eeg_id')[['patient_id']].agg('first')\ntrain['patient_id'] = tmp\n\ntmp = df.groupby('eeg_id')[TARGETS].agg('sum')\nfor t in TARGETS:\n    train[t] = tmp[t].values\n    \ny_data = train[TARGETS].values\ny_data = y_data / y_data.sum(axis=1,keepdims=True)\ntrain[TARGETS] = y_data\n\ntmp = df.groupby('eeg_id')[['expert_consensus']].agg('first')\ntrain['target'] = tmp\n\ntrain = train.reset_index()\nprint('Train non-overlapp eeg_id shape:', train.shape )\ntrain.head()","metadata":{"execution":{"iopub.status.busy":"2024-01-28T15:43:26.604172Z","iopub.execute_input":"2024-01-28T15:43:26.604810Z","iopub.status.idle":"2024-01-28T15:43:26.705213Z","shell.execute_reply.started":"2024-01-28T15:43:26.604783Z","shell.execute_reply":"2024-01-28T15:43:26.704300Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\nREAD_SPEC_FILES = False\n\n# READ ALL SPECTROGRAMS\nPATH = '/kaggle/input/hms-harmful-brain-activity-classification/train_spectrograms/'\nfiles = os.listdir(PATH)\nprint(f'There are {len(files)} spectrogram parquets')\n\nif READ_SPEC_FILES:    \n    spectrograms = {}\n    for i,f in enumerate(files):\n        if i%100==0: print(i,', ',end='')\n        tmp = pd.read_parquet(f'{PATH}{f}')\n        name = int(f.split('.')[0])\n        spectrograms[name] = tmp.iloc[:,1:].values\nelse:\n    spectrograms = np.load('/kaggle/input/brain-spectrograms/specs.npy',allow_pickle=True).item()","metadata":{"execution":{"iopub.status.busy":"2024-01-28T15:43:26.706283Z","iopub.execute_input":"2024-01-28T15:43:26.706552Z","iopub.status.idle":"2024-01-28T15:44:38.677279Z","shell.execute_reply.started":"2024-01-28T15:43:26.706527Z","shell.execute_reply":"2024-01-28T15:44:38.676306Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\nREAD_EEG_SPEC_FILES = False\nprint(\"Reading EEGs...\")\nif READ_EEG_SPEC_FILES:\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/brain-eeg-spectrograms/EEG_Spectrograms/{e}.npy')\n        all_eegs[e] = x\nelse:\n    all_eegs = np.load('/kaggle/input/brain-eeg-spectrograms/eeg_specs.npy',allow_pickle=True).item()","metadata":{"execution":{"iopub.status.busy":"2024-01-28T15:44:38.678512Z","iopub.execute_input":"2024-01-28T15:44:38.678819Z","iopub.status.idle":"2024-01-28T15:45:55.450653Z","shell.execute_reply.started":"2024-01-28T15:44:38.678768Z","shell.execute_reply":"2024-01-28T15:45:55.449763Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import albumentations as albu\nTARS = {'Seizure':0, 'LPD':1, 'GPD':2, 'LRDA':3, 'GRDA':4, 'Other':5}\nTARS2 = {x:y for y,x in TARS.items()}\n\nclass DataGenerator(tf.keras.utils.Sequence):\n    'Generates data for Keras'\n    def __init__(self, data, batch_size=32, shuffle=False, augment=False, mode='train',\n                 specs = spectrograms, eeg_specs = all_eegs): \n\n        self.data = data\n        self.batch_size = batch_size\n        self.shuffle = shuffle\n        self.augment = augment\n        self.mode = mode\n        self.specs = specs\n        self.eeg_specs = eeg_specs\n        self.on_epoch_end()\n        \n    def __len__(self):\n        'Denotes the number of batches per epoch'\n        ct = int( np.ceil( len(self.data) / self.batch_size ) )\n        return ct\n\n    def __getitem__(self, index):\n        'Generate one batch of data'\n        indexes = self.indexes[index*self.batch_size:(index+1)*self.batch_size]\n        X, y = self.__data_generation(indexes)\n        if self.augment: X = self.__augment_batch(X) \n        return X, y\n\n    def on_epoch_end(self):\n        'Updates indexes after each epoch'\n        self.indexes = np.arange( len(self.data) )\n        if self.shuffle: np.random.shuffle(self.indexes)\n                        \n    def __data_generation(self, indexes):\n        'Generates data containing batch_size samples' \n        \n        X = np.zeros((len(indexes),128,256,8),dtype='float32')\n        y = np.zeros((len(indexes),6),dtype='float32')\n        img = np.ones((128,256),dtype='float32')\n        \n        for j,i in enumerate(indexes):\n            row = self.data.iloc[i]\n            if self.mode=='test': \n                r = 0\n            else: \n                r = int( (row['min'] + row['max'])//4 )\n\n            for k in range(4):\n                # EXTRACT 300 ROWS OF SPECTROGRAM\n                img = self.specs[row.spec_id][r:r+300,k*100:(k+1)*100].T\n                \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                ep = 1e-6\n                m = np.nanmean(img.flatten())\n                s = np.nanstd(img.flatten())\n                img = (img-m)/(s+ep)\n                img = np.nan_to_num(img, nan=0.0)\n                \n                # CROP TO 256 TIME STEPS\n                X[j,14:-14,:,k] = img[:,22:-22] / 2.0\n        \n            # EEG SPECTROGRAMS\n            img = self.eeg_specs[row.eeg_id]\n            X[j,:,:,4:] = img\n                \n            if self.mode!='test':\n                y[j,] = row[TARGETS]\n            \n        return X,y\n    \n    def __random_transform(self, img):\n        composition = albu.Compose([\n            albu.HorizontalFlip(p=0.5),\n            #albu.CoarseDropout(max_holes=8,max_height=32,max_width=32,fill_value=0,p=0.5),\n        ])\n        return composition(image=img)['image']\n            \n    def __augment_batch(self, img_batch):\n        for i in range(img_batch.shape[0]):\n            img_batch[i, ] = self.__random_transform(img_batch[i, ])\n        return img_batch","metadata":{"execution":{"iopub.status.busy":"2024-01-28T15:45:55.451958Z","iopub.execute_input":"2024-01-28T15:45:55.452238Z","iopub.status.idle":"2024-01-28T15:45:57.159259Z","shell.execute_reply.started":"2024-01-28T15:45:55.452213Z","shell.execute_reply":"2024-01-28T15:45:57.158336Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"gen = DataGenerator(train, batch_size=32, shuffle=False)\nROWS=2; COLS=3; BATCHES=2\n\nfor i,(x,y) in enumerate(gen):\n    plt.figure(figsize=(20,8))\n    for j in range(ROWS):\n        for k in range(COLS):\n            plt.subplot(ROWS,COLS,j*COLS+k+1)\n            t = y[j*COLS+k]\n            img = x[j*COLS+k,:,:,0][::-1,]\n            mn = img.flatten().min()\n            mx = img.flatten().max()\n            img = (img-mn)/(mx-mn)\n            plt.imshow(img)\n            tars = f'[{t[0]:0.2f}'\n            for s in t[1:]: tars += f', {s:0.2f}'\n            eeg = train.eeg_id.values[i*32+j*COLS+k]\n            plt.title(f'EEG = {eeg}\\nTarget = {tars}',size=12)\n            plt.yticks([])\n            plt.ylabel('Frequencies (Hz)',size=14)\n            plt.xlabel('Time (sec)',size=16)\n    plt.show()\n    if i==BATCHES-1: break","metadata":{"execution":{"iopub.status.busy":"2024-01-28T15:45:57.160553Z","iopub.execute_input":"2024-01-28T15:45:57.161343Z","iopub.status.idle":"2024-01-28T15:45:59.915818Z","shell.execute_reply.started":"2024-01-28T15:45:57.161307Z","shell.execute_reply":"2024-01-28T15:45:59.914907Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import math\nLR_START = 1e-6\nLR_MAX = 1e-3\nLR_MIN = 1e-6\nLR_RAMPUP_EPOCHS = 0\nLR_SUSTAIN_EPOCHS = 0\nEPOCHS2 = 15\n\ndef lrfn(epoch):\n    if epoch < LR_RAMPUP_EPOCHS:\n        lr = (LR_MAX - LR_START) / LR_RAMPUP_EPOCHS * epoch + LR_START\n    elif epoch < LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS:\n        lr = LR_MAX\n    else:\n        decay_total_epochs = EPOCHS2 - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS - 1\n        decay_epoch_index = epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS\n        phase = math.pi * decay_epoch_index / decay_total_epochs\n        cosine_decay = 0.5 * (1 + math.cos(phase))\n        lr = (LR_MAX - LR_MIN) * cosine_decay + LR_MIN\n    return lr\n\nrng = [i for i in range(EPOCHS2)]\nlr_y = [lrfn(x) for x in rng]\nplt.figure(figsize=(10, 4))\nplt.plot(rng, lr_y, '-o')\nplt.xlabel('epoch',size=14); plt.ylabel('learning rate',size=14)\nplt.title('Cosine Training Schedule',size=16); plt.show()\n\nLR2 = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose = True)","metadata":{"execution":{"iopub.status.busy":"2024-01-28T15:45:59.917120Z","iopub.execute_input":"2024-01-28T15:45:59.917686Z","iopub.status.idle":"2024-01-28T15:46:00.213283Z","shell.execute_reply.started":"2024-01-28T15:45:59.917654Z","shell.execute_reply":"2024-01-28T15:46:00.212250Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"LR_START = 1e-4\nLR_MAX = 1e-3\nLR_RAMPUP_EPOCHS = 0\nLR_SUSTAIN_EPOCHS = 1\nLR_STEP_DECAY = 0.1\nEVERY = 1\nEPOCHS = 6\n\ndef lrfn(epoch):\n    if epoch < LR_RAMPUP_EPOCHS:\n        lr = (LR_MAX - LR_START) / LR_RAMPUP_EPOCHS * epoch + LR_START\n    elif epoch < LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS:\n        lr = LR_MAX\n    else:\n        lr = LR_MAX * LR_STEP_DECAY**((epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS)//EVERY)\n    return lr\n\nrng = [i for i in range(EPOCHS)]\ny = [lrfn(x) for x in rng]\nplt.figure(figsize=(10, 4))\nplt.plot(rng, y, 'o-'); \nplt.xlabel('epoch',size=14); plt.ylabel('learning rate',size=14)\nplt.title('Step Training Schedule',size=16); plt.show()\n\nLR = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose = True)","metadata":{"execution":{"iopub.status.busy":"2024-01-28T15:46:00.217058Z","iopub.execute_input":"2024-01-28T15:46:00.217320Z","iopub.status.idle":"2024-01-28T15:46:00.432588Z","shell.execute_reply.started":"2024-01-28T15:46:00.217297Z","shell.execute_reply":"2024-01-28T15:46:00.431739Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install --no-index --find-links=/kaggle/input/tf-efficientnet-whl-files /kaggle/input/tf-efficientnet-whl-files/efficientnet-1.1.1-py3-none-any.whl","metadata":{"execution":{"iopub.status.busy":"2024-01-28T15:46:00.433906Z","iopub.execute_input":"2024-01-28T15:46:00.434493Z","iopub.status.idle":"2024-01-28T15:46:13.857503Z","shell.execute_reply.started":"2024-01-28T15:46:00.434457Z","shell.execute_reply":"2024-01-28T15:46:13.856319Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import efficientnet.tfkeras as efn\n\ndef build_model():\n    \n    inp = tf.keras.Input(shape=(128,256,8))\n    base_model = efn.EfficientNetB0(include_top=False, weights=None, input_shape=None)\n    base_model.load_weights('/kaggle/input/tf-efficientnet-imagenet-weights/efficientnet-b0_weights_tf_dim_ordering_tf_kernels_autoaugment_notop.h5')\n    \n    # RESHAPE INPUT 128x256x8 => 512x512x3 MONOTONE IMAGE\n    # KAGGLE SPECTROGRAMS\n    x1 = [inp[:,:,:,i:i+1] for i in range(4)]\n    x1 = tf.keras.layers.Concatenate(axis=1)(x1)\n    # EEG SPECTROGRAMS\n    x2 = [inp[:,:,:,i+4:i+5] for i in range(4)]\n    x2 = tf.keras.layers.Concatenate(axis=1)(x2)\n    # MAKE 512X512X3\n    if USE_KAGGLE_SPECTROGRAMS & USE_EEG_SPECTROGRAMS:\n        x = tf.keras.layers.Concatenate(axis=2)([x1,x2])\n    elif USE_EEG_SPECTROGRAMS: x = x2\n    else: x = x1\n    x = tf.keras.layers.Concatenate(axis=3)([x,x,x])\n    \n    # OUTPUT\n    x = base_model(x)\n    x = tf.keras.layers.GlobalAveragePooling2D()(x)\n    x = tf.keras.layers.Dense(6,activation='softmax', dtype='float32')(x)\n        \n    # COMPILE MODEL\n    model = tf.keras.Model(inputs=inp, outputs=x)\n    opt = tf.keras.optimizers.Adam(learning_rate = 1e-3)\n    loss = tf.keras.losses.KLDivergence()\n\n    model.compile(loss=loss, optimizer = opt) \n        \n    return model","metadata":{"execution":{"iopub.status.busy":"2024-01-28T15:46:13.859124Z","iopub.execute_input":"2024-01-28T15:46:13.859454Z","iopub.status.idle":"2024-01-28T15:46:13.885109Z","shell.execute_reply.started":"2024-01-28T15:46:13.859427Z","shell.execute_reply":"2024-01-28T15:46:13.884204Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import KFold, GroupKFold\nimport tensorflow.keras.backend as K, gc\n\nall_oof = []\nall_true = []\n\ngkf = GroupKFold(n_splits=5)\nfor 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    train_gen = DataGenerator(train.iloc[train_index], shuffle=True, batch_size=32, augment=False)\n    valid_gen = DataGenerator(train.iloc[valid_index], shuffle=False, batch_size=64, mode='valid')\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        model = build_model()\n    if LOAD_MODELS_FROM is None:\n        model.fit(train_gen, verbose=1,\n              validation_data = valid_gen,\n              epochs=EPOCHS, callbacks = [LR])\n        model.save_weights(f'EffNet_v{VER}_f{i}.h5')\n    else:\n        model.load_weights(f'{LOAD_MODELS_FROM}EffNet_v{VER}_f{i}.h5')\n        \n    oof = model.predict(valid_gen, verbose=1)\n    all_oof.append(oof)\n    all_true.append(train.iloc[valid_index][TARGETS].values)\n    \n    del model, oof\n    gc.collect()\n    \nall_oof = np.concatenate(all_oof)\nall_true = np.concatenate(all_true)","metadata":{"execution":{"iopub.status.busy":"2024-01-28T15:46:13.886216Z","iopub.execute_input":"2024-01-28T15:46:13.886495Z","iopub.status.idle":"2024-01-28T15:49:13.815540Z","shell.execute_reply.started":"2024-01-28T15:46:13.886472Z","shell.execute_reply":"2024-01-28T15:49:13.814718Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import sys\nsys.path.append('/kaggle/input/kaggle-kl-div')\nfrom kaggle_kl_div import score\n\noof = pd.DataFrame(all_oof.copy())\noof['id'] = np.arange(len(oof))\n\ntrue = pd.DataFrame(all_true.copy())\ntrue['id'] = np.arange(len(true))\n\ncv = score(solution=true, submission=oof, row_id_column_name='id')\nprint('CV Score KL-Div for EfficientNetB2 =',cv)","metadata":{"execution":{"iopub.status.busy":"2024-01-28T15:49:13.817426Z","iopub.execute_input":"2024-01-28T15:49:13.817725Z","iopub.status.idle":"2024-01-28T15:49:13.892525Z","shell.execute_reply.started":"2024-01-28T15:49:13.817699Z","shell.execute_reply":"2024-01-28T15:49:13.891653Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"del all_eegs, spectrograms; gc.collect()\ntest = pd.read_csv('/kaggle/input/hms-harmful-brain-activity-classification/test.csv')\n# print('Test shape',test.shape)\n# test.head()","metadata":{"execution":{"iopub.status.busy":"2024-01-28T15:49:13.893656Z","iopub.execute_input":"2024-01-28T15:49:13.893938Z","iopub.status.idle":"2024-01-28T15:49:14.117998Z","shell.execute_reply.started":"2024-01-28T15:49:13.893914Z","shell.execute_reply":"2024-01-28T15:49:14.116921Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# READ ALL SPECTROGRAMS\nPATH2 = '/kaggle/input/hms-harmful-brain-activity-classification/test_spectrograms/'\nfiles2 = os.listdir(PATH2)\n# print(f'There are {len(files2)} test spectrogram parquets')\n    \nspectrograms2 = {}\nfor 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 DATALOADER\ntest = test.rename({'spectrogram_id':'spec_id'},axis=1)","metadata":{"execution":{"iopub.status.busy":"2024-01-28T15:49:14.119802Z","iopub.execute_input":"2024-01-28T15:49:14.120077Z","iopub.status.idle":"2024-01-28T15:49:14.419659Z","shell.execute_reply.started":"2024-01-28T15:49:14.120054Z","shell.execute_reply":"2024-01-28T15:49:14.418802Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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\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((128,256,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        \n            # COMPUTE PAIR DIFFERENCES\n            x = eeg[COLS[kk]].values - eeg[COLS[kk+1]].values\n\n            # FILL NANS\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            # 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)//256, \n                  n_fft=1024, n_mels=128, fmin=0, fmax=20, win_length=128)\n\n            # LOG TRANSFORM\n            width = (mel_spec.shape[1]//32)*32\n            mel_spec_db = librosa.power_to_db(mel_spec, ref=np.max).astype(np.float32)[:,:width]\n\n            # STANDARDIZE TO -1 TO 1\n            mel_spec_db = (mel_spec_db+40)/40 \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            plt.title(f'EEG {eeg_id} - Spectrogram {NAMES[k]}')\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.title(f'EEG {eeg_id} Signals')\n        plt.show()\n        print(); print('#'*25); print()\n        \n    return img","metadata":{"execution":{"iopub.status.busy":"2024-01-28T15:49:14.421030Z","iopub.execute_input":"2024-01-28T15:49:14.421394Z","iopub.status.idle":"2024-01-28T15:49:14.445088Z","shell.execute_reply.started":"2024-01-28T15:49:14.421360Z","shell.execute_reply":"2024-01-28T15:49:14.444261Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# READ ALL EEG SPECTROGRAMS\nPATH2 = '/kaggle/input/hms-harmful-brain-activity-classification/test_eegs/'\nDISPLAY = 1\nEEG_IDS2 = test.eeg_id.unique()\nall_eegs2 = {}\n\nprint('Converting Test EEG to Spectrograms...'); print()\nfor 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.status.busy":"2024-01-28T15:49:14.446224Z","iopub.execute_input":"2024-01-28T15:49:14.446544Z","iopub.status.idle":"2024-01-28T15:49:26.437821Z","shell.execute_reply.started":"2024-01-28T15:49:14.446520Z","shell.execute_reply":"2024-01-28T15:49:26.436821Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# INFER EFFICIENTNET ON TEST\npreds = []\nmodel = build_model()\ntest_gen = DataGenerator(test, shuffle=False, batch_size=64, mode='test',\n                         specs = spectrograms2, eeg_specs = all_eegs2)\n\nfor i in range(5):\n    print(f'Fold {i+1}')\n    if LOAD_MODELS_FROM:\n        model.load_weights(f'{LOAD_MODELS_FROM}EffNet_v{VER}_f{i}.h5')\n    else:\n        model.load_weights(f'EffNet_v{VER}_f{i}.h5')\n    pred = model.predict(test_gen, verbose=1)\n    preds.append(pred)\npred = np.mean(preds,axis=0)\nprint()\nprint('Test preds shape',pred.shape)","metadata":{"execution":{"iopub.status.busy":"2024-01-28T15:49:26.439188Z","iopub.execute_input":"2024-01-28T15:49:26.439830Z","iopub.status.idle":"2024-01-28T15:49:34.155415Z","shell.execute_reply.started":"2024-01-28T15:49:26.439803Z","shell.execute_reply":"2024-01-28T15:49:34.154441Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub1 = pd.DataFrame({'eeg_id':test.eeg_id.values})\nsub1[TARGETS] = pred\n# print('Submission shape',sub1.shape)\nsub1.head()","metadata":{"execution":{"iopub.status.busy":"2024-01-28T15:49:34.156535Z","iopub.execute_input":"2024-01-28T15:49:34.156862Z","iopub.status.idle":"2024-01-28T15:49:34.174127Z","shell.execute_reply.started":"2024-01-28T15:49:34.156834Z","shell.execute_reply":"2024-01-28T15:49:34.173115Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"preds_combine = pred\npreds_combine","metadata":{"execution":{"iopub.status.busy":"2024-01-28T15:49:34.175388Z","iopub.execute_input":"2024-01-28T15:49:34.175785Z","iopub.status.idle":"2024-01-28T15:49:34.184507Z","shell.execute_reply.started":"2024-01-28T15:49:34.175734Z","shell.execute_reply":"2024-01-28T15:49:34.183552Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# SANITY CHECK TO CONFIRM PREDICTIONS SUM TO ONE\nsub1.iloc[:,-6:].sum(axis=1)","metadata":{"execution":{"iopub.status.busy":"2024-01-28T15:49:34.185818Z","iopub.execute_input":"2024-01-28T15:49:34.186126Z","iopub.status.idle":"2024-01-28T15:49:34.197742Z","shell.execute_reply.started":"2024-01-28T15:49:34.186095Z","shell.execute_reply":"2024-01-28T15:49:34.196817Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Model 2","metadata":{}},{"cell_type":"code","source":"#https://www.kaggle.com/code/ttahara/hms-hbac-resnet34d-baseline-training\n#https://www.kaggle.com/code/ttahara/hms-hbac-resnet34d-baseline-inference\n#necessary\nimport pandas as pd\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision.transforms as transforms\nimport random\nimport warnings\nwarnings.filterwarnings('ignore')","metadata":{"execution":{"iopub.status.busy":"2024-01-28T15:49:34.198851Z","iopub.execute_input":"2024-01-28T15:49:34.199241Z","iopub.status.idle":"2024-01-28T15:49:38.058890Z","shell.execute_reply.started":"2024-01-28T15:49:34.199211Z","shell.execute_reply":"2024-01-28T15:49:38.058067Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class Config:\n    seed=2024\n    image_transform=transforms.Resize((512, 512))\n    num_folds=5","metadata":{"execution":{"iopub.status.busy":"2024-01-28T15:49:38.060214Z","iopub.execute_input":"2024-01-28T15:49:38.061139Z","iopub.status.idle":"2024-01-28T15:49:38.066038Z","shell.execute_reply.started":"2024-01-28T15:49:38.061104Z","shell.execute_reply":"2024-01-28T15:49:38.065172Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"models=[]\nfor i in range(Config.num_folds):\n    model = torch.load(f'/kaggle/input/hms-baseline-resnet34d-512-512-training-5-folds/HMS_resnet_fold{i}.pth')\n    models.append(model)\nmodel = torch.load(\"/kaggle/input/hms-baseline-resnet34d-512-512-training/HMS_resnet.pth\")\nmodels.append(model)","metadata":{"execution":{"iopub.status.busy":"2024-01-28T15:49:38.067134Z","iopub.execute_input":"2024-01-28T15:49:38.067371Z","iopub.status.idle":"2024-01-28T15:49:44.320400Z","shell.execute_reply.started":"2024-01-28T15:49:38.067351Z","shell.execute_reply":"2024-01-28T15:49:44.319544Z"},"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(Config.seed)","metadata":{"execution":{"iopub.status.busy":"2024-01-28T15:49:44.321659Z","iopub.execute_input":"2024-01-28T15:49:44.321967Z","iopub.status.idle":"2024-01-28T15:49:44.333373Z","shell.execute_reply.started":"2024-01-28T15:49:44.321942Z","shell.execute_reply":"2024-01-28T15:49:44.332404Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df=pd.read_csv(\"/kaggle/input/hms-harmful-brain-activity-classification/test.csv\")\nsubmission=pd.read_csv(\"/kaggle/input/hms-harmful-brain-activity-classification/sample_submission.csv\")\nsubmission=submission.merge(test_df,on='eeg_id',how='left')\nsubmission['path']=submission['spectrogram_id'].apply(lambda x: \"/kaggle/input/hms-harmful-brain-activity-classification/test_spectrograms/\"+str(x)+\".parquet\" )\nsubmission.head()","metadata":{"execution":{"iopub.status.busy":"2024-01-28T15:49:44.334640Z","iopub.execute_input":"2024-01-28T15:49:44.334950Z","iopub.status.idle":"2024-01-28T15:49:44.370593Z","shell.execute_reply.started":"2024-01-28T15:49:44.334925Z","shell.execute_reply":"2024-01-28T15:49:44.369554Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"paths=submission['path'].values\ntest_preds=[]\nfor path in paths:\n    eps=1e-6\n    data=pd.read_parquet(path)\n    data = data.fillna(-1).values[:,1:].T\n    data=data[:,0:300]\n    data=np.clip(data,np.exp(-6),np.exp(10))\n    data= np.log(data)\n    data_mean=data.mean(axis=(0,1))\n    data_std=data.std(axis=(0,1))\n    data=(data-data_mean)/(data_std+eps)\n    data_tensor = torch.unsqueeze(torch.Tensor(data), dim=0)\n    data=Config.image_transform(data_tensor)\n    test_pred=[]\n    for model in models:\n        model.eval()\n        with torch.no_grad():\n            pred=F.softmax(model(data.unsqueeze(0)))[0]\n            pred=pred.detach().cpu().numpy()\n        test_pred.append(pred)\n    test_pred=np.array(test_pred).mean(axis=0)\n    test_preds.append(test_pred)\ntest_preds=np.array(test_preds)\ntest_preds","metadata":{"execution":{"iopub.status.busy":"2024-01-28T15:49:44.376764Z","iopub.execute_input":"2024-01-28T15:49:44.377079Z","iopub.status.idle":"2024-01-28T15:49:46.083291Z","shell.execute_reply.started":"2024-01-28T15:49:44.377055Z","shell.execute_reply":"2024-01-28T15:49:46.082236Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub2=pd.read_csv(\"/kaggle/input/hms-harmful-brain-activity-classification/sample_submission.csv\")\nlabels=['seizure','lpd','gpd','lrda','grda','other']\nfor i in range(len(labels)):\n    sub2[f'{labels[i]}_vote']=test_preds[:,i]\nsub2.head()","metadata":{"execution":{"iopub.status.busy":"2024-01-28T15:49:46.084617Z","iopub.execute_input":"2024-01-28T15:49:46.084928Z","iopub.status.idle":"2024-01-28T15:49:46.102540Z","shell.execute_reply.started":"2024-01-28T15:49:46.084902Z","shell.execute_reply":"2024-01-28T15:49:46.101391Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#  Model 3","metadata":{}},{"cell_type":"code","source":"LOAD_SPEC = True\nif LOAD_SPEC:\n    print(\"Loading 3200 Spectogram Features....\")\n    data = pd.read_parquet(\"/kaggle/input/spectogram-data/heavydata.parquet\")\n    feats = data.columns.values\n    data = data.values\n    data[:, 800:1200] = np.nan_to_num(data[:, 800:1200])\n    data[:, 1200:1600] = np.nan_to_num(data[:, 1200:1600])\n    data[:, 2800:3200] = np.nan_to_num(data[:, 2800:3200])\n    \n    \n    print(\"Loaded all the features from spectograms\")","metadata":{"execution":{"iopub.status.busy":"2024-01-28T15:49:46.104744Z","iopub.execute_input":"2024-01-28T15:49:46.105063Z","iopub.status.idle":"2024-01-28T15:49:49.958584Z","shell.execute_reply.started":"2024-01-28T15:49:46.105039Z","shell.execute_reply":"2024-01-28T15:49:49.957565Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_train = y_data\nY = train['target'].map(TARS).values","metadata":{"execution":{"iopub.status.busy":"2024-01-28T15:49:49.960043Z","iopub.execute_input":"2024-01-28T15:49:49.960434Z","iopub.status.idle":"2024-01-28T15:49:49.969736Z","shell.execute_reply.started":"2024-01-28T15:49:49.960398Z","shell.execute_reply":"2024-01-28T15:49:49.968842Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\ntorch.cuda.empty_cache()\nimport torch.nn as nn\ndef KL_loss(p,q):\n    epsilon=10**(-15)\n    p=torch.clip(p,epsilon,1-epsilon)\n    q = nn.functional.log_softmax(q,dim=1)\n    return torch.mean(torch.sum(p*(torch.log(p)-q),dim=1))","metadata":{"execution":{"iopub.status.busy":"2024-01-28T15:49:49.972219Z","iopub.execute_input":"2024-01-28T15:49:49.972575Z","iopub.status.idle":"2024-01-28T15:49:49.982206Z","shell.execute_reply.started":"2024-01-28T15:49:49.972542Z","shell.execute_reply":"2024-01-28T15:49:49.981291Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\nfrom catboost import CatBoostClassifier, Pool\n#from numba import cuda\nfrom tqdm.auto import tqdm\ntorch.cuda.empty_cache()\nK.clear_session()\nfrom sklearn.model_selection import GroupKFold\ntrain_cat=True\nif train_cat:\n    print(\"Training CatBoost model\")\n    n_splits=5\n    gkf = GroupKFold(n_splits=5)\n    device = 'GPU' if torch.cuda.is_available() else 'CPU'\n    probs=[]\n    true=[]\n    best_score = np.inf\n    print(f\"Running on {device}\")\n    for i, (train_index, valid_index) in enumerate(tqdm(gkf.split(data, Y, train.patient_id), total=n_splits)):\n        cat_model = CatBoostClassifier(task_type=device, loss_function=\"MultiClass\")\n        train_pool = Pool(data = data[train_index, :], label = Y[train_index])\n        valid_pool = Pool(data = data[valid_index, :], label = Y[valid_index])\n    \n        cat_model.fit(train_pool,\n                 verbose=100,\n                 eval_set=valid_pool)\n    \n        prob = cat_model.predict_proba(valid_pool)\n        probs.append(prob)\n        true.append(y_train[valid_index,:])\n        \n        err = float(KL_loss(torch.tensor(prob), torch.tensor(y_train[valid_index, :])))\n        print(f\"Score : {err}\")\n        if err<best_score:\n            cat_model.save_model(\"./bestCATboost.cat\")\n            print(f\"saved the model!\")\n            best_score=err\n    \n        del train_pool, valid_pool, prob\n        gc.collect()\n        \n\nprobs = np.concatenate(probs)\ntrue = np.concatenate(true)","metadata":{"execution":{"iopub.status.busy":"2024-01-28T15:49:49.983360Z","iopub.execute_input":"2024-01-28T15:49:49.983636Z","iopub.status.idle":"2024-01-28T15:58:27.423906Z","shell.execute_reply.started":"2024-01-28T15:49:49.983613Z","shell.execute_reply":"2024-01-28T15:58:27.423072Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nTOP = 25\nif train_cat:\n    feature_importance = cat_model.feature_importances_\n    #print(feature_importance)\n    sorted_idx = np.argsort(feature_importance)\n    fig = plt.figure(figsize=(10, 8))\n    plt.barh(np.arange(len(sorted_idx))[-TOP:], feature_importance[sorted_idx][-TOP:], align='center')\n    plt.yticks(np.arange(len(sorted_idx))[-TOP:], np.array(feats)[sorted_idx][-TOP:])\n    plt.title(f'Feature Importance - Top {TOP}')\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2024-01-28T15:58:27.425411Z","iopub.execute_input":"2024-01-28T15:58:27.425935Z","iopub.status.idle":"2024-01-28T15:58:27.962100Z","shell.execute_reply.started":"2024-01-28T15:58:27.425904Z","shell.execute_reply":"2024-01-28T15:58:27.961256Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nif train_cat:\n    \n    all_probs = pd.DataFrame(probs)\n    all_probs['id'] = np.arange(len(all_probs))\n    \n    all_true = pd.DataFrame(true)\n    all_true['id'] = np.arange(len(all_true))\n    \n    cv = score(solution=all_true, submission=all_probs, row_id_column_name='id')\n    \n    print(f\"CV score for CatBoost Model is : {cv}\")\n    ","metadata":{"execution":{"iopub.status.busy":"2024-01-28T15:58:27.963344Z","iopub.execute_input":"2024-01-28T15:58:27.963628Z","iopub.status.idle":"2024-01-28T15:58:28.021020Z","shell.execute_reply.started":"2024-01-28T15:58:27.963603Z","shell.execute_reply":"2024-01-28T15:58:28.020059Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"base_path = \"/kaggle/input/hms-harmful-brain-activity-classification/\"\nfrom scipy.stats import kurtosis, skew, entropy\nif LOAD_SPEC:\n    test_path = \"/kaggle/input/hms-harmful-brain-activity-classification/test_spectrograms/\"\n    test_csv = pd.read_csv(base_path+\"test.csv\")\n    test_data = np.zeros((len(test_csv), len(feats)))\n    for k in range(len(test_csv)):\n        spec_id = str(test_csv.iloc[k]['spectrogram_id'])\n        spec = pd.read_parquet(test_path+spec_id+\".parquet\")\n        spec = spec.drop(['time'], axis=1).values\n        #mean\n        test_data[k,:400] = np.nanmean(spec, axis=0, keepdims=True)\n    \n        #std\n        test_data[k, 400:800] = np.nanstd(spec, axis=0, keepdims=True)\n    \n        #kurtosis\n        test_data[k, 800:1200] = kurtosis(spec, nan_policy = \"omit\", \n                                     axis=0)\n        #skew\n        test_data[k, 1200:1600] = skew(spec, nan_policy = \"omit\", \n                                     axis=0)\n        #min\n        test_data[k, 1600:2000] = np.nanmin(spec, axis=0, keepdims=True)\n        #max\n        test_data[k, 2000:2400] = np.nanmax(spec, axis=0, keepdims=True)\n        #energy\n        test_data[k, 2400:2800] = np.nansum(spec**2, axis=0, keepdims=True)/len(spec)\n        #entropy\n        spec = np.nan_to_num(spec)\n        test_data[k, 2800:3200] = entropy(spec, axis=0)\n    \n    test_data = np.nan_to_num(test_data)\n    \n    sub3 = pd.read_csv(\"/kaggle/input/hms-harmful-brain-activity-classification/sample_submission.csv\", index_col=False)","metadata":{"execution":{"iopub.status.busy":"2024-01-28T15:58:28.022330Z","iopub.execute_input":"2024-01-28T15:58:28.022671Z","iopub.status.idle":"2024-01-28T15:58:28.098610Z","shell.execute_reply.started":"2024-01-28T15:58:28.022638Z","shell.execute_reply":"2024-01-28T15:58:28.097818Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tqdm.notebook import trange\nif train_cat:\n    cat_preds=[]\n    for i in trange(n_splits):\n        model = CatBoostClassifier(task_type=device)\n        model.load_model(\"./bestCATboost.cat\")\n    \n        test_pool = Pool(data = test_data)\n    \n        cat_pred = model.predict_proba(test_pool)\n        cat_preds.append(cat_pred)\n    \n    cat_pred = np.mean(np.array(cat_preds), axis=0)\n\nsub3[TARGETS] = cat_pred\nprint(cat_pred.sum())","metadata":{"execution":{"iopub.status.busy":"2024-01-28T15:59:08.094961Z","iopub.execute_input":"2024-01-28T15:59:08.095733Z","iopub.status.idle":"2024-01-28T15:59:08.335827Z","shell.execute_reply.started":"2024-01-28T15:59:08.095698Z","shell.execute_reply":"2024-01-28T15:59:08.334804Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(f\"Shape : {sub3.shape}\")\nsub3.head()","metadata":{"execution":{"iopub.status.busy":"2024-01-28T15:59:11.923190Z","iopub.execute_input":"2024-01-28T15:59:11.923924Z","iopub.status.idle":"2024-01-28T15:59:11.937436Z","shell.execute_reply.started":"2024-01-28T15:59:11.923893Z","shell.execute_reply":"2024-01-28T15:59:11.936518Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Subission","metadata":{}},{"cell_type":"code","source":"preds_combine","metadata":{"execution":{"iopub.status.busy":"2024-01-28T15:59:19.093200Z","iopub.execute_input":"2024-01-28T15:59:19.093980Z","iopub.status.idle":"2024-01-28T15:59:19.100400Z","shell.execute_reply.started":"2024-01-28T15:59:19.093949Z","shell.execute_reply":"2024-01-28T15:59:19.099345Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import shutil\nif train_cat:\n    shutil.rmtree('/kaggle/working/catboost_info')\n    os.remove(\"./bestCATboost.cat\")\nsubmission=pd.read_csv(\"/kaggle/input/hms-harmful-brain-activity-classification/sample_submission.csv\")\nlabels=['seizure','lpd','gpd','lrda','grda','other']\nfor i in range(len(labels)):\n    submission[f'{labels[i]}_vote']=(test_preds[:,i] + preds_combine[:, i] + cat_pred[:, i])/3\nsubmission.to_csv(\"submission.csv\",index=None)\ndisplay(submission.head())","metadata":{"execution":{"iopub.status.busy":"2024-01-28T16:02:01.643745Z","iopub.execute_input":"2024-01-28T16:02:01.644154Z","iopub.status.idle":"2024-01-28T16:02:01.669592Z","shell.execute_reply.started":"2024-01-28T16:02:01.644123Z","shell.execute_reply":"2024-01-28T16:02:01.668687Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# SANITY CHECK TO CONFIRM PREDICTIONS SUM TO ONE\nsubmission.iloc[:,-6:].sum(axis=1)","metadata":{"execution":{"iopub.status.busy":"2024-01-28T15:59:28.082250Z","iopub.execute_input":"2024-01-28T15:59:28.082634Z","iopub.status.idle":"2024-01-28T15:59:28.091681Z","shell.execute_reply.started":"2024-01-28T15:59:28.082603Z","shell.execute_reply":"2024-01-28T15:59:28.090641Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}