{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","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":6127,"sourceType":"modelInstanceVersion","modelInstanceId":4598}],"dockerImageVersionId":30698,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# ***Dependencies and libraries***","metadata":{}},{"cell_type":"markdown","source":"## ***Dependencies***","metadata":{}},{"cell_type":"code","source":"!pip install keras","metadata":{"execution":{"iopub.status.busy":"2024-05-24T11:33:36.698216Z","iopub.execute_input":"2024-05-24T11:33:36.698593Z","iopub.status.idle":"2024-05-24T11:33:49.262468Z","shell.execute_reply.started":"2024-05-24T11:33:36.698563Z","shell.execute_reply":"2024-05-24T11:33:49.261441Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## ***Libraries***","metadata":{}},{"cell_type":"code","source":"import os\nos.environ[\"KERAS_BACKEND\"] = \"jax\" # you can also use tensorflow or torch\n\nimport keras_cv\nimport keras\nfrom keras import ops\nimport tensorflow as tf\n\nimport cv2\nimport pandas as pd\nimport numpy as np\nfrom glob import glob\nfrom tqdm.notebook import tqdm\nimport joblib\n\nimport matplotlib.pyplot as plt ","metadata":{"execution":{"iopub.status.busy":"2024-05-24T11:38:31.382479Z","iopub.execute_input":"2024-05-24T11:38:31.382862Z","iopub.status.idle":"2024-05-24T11:38:31.388874Z","shell.execute_reply.started":"2024-05-24T11:38:31.382830Z","shell.execute_reply":"2024-05-24T11:38:31.387764Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"TensorFlow:\", tf.__version__)\nprint(\"Keras:\", keras.__version__)\nprint(\"KerasCV:\", keras_cv.__version__)","metadata":{"execution":{"iopub.status.busy":"2024-05-24T11:33:49.276065Z","iopub.execute_input":"2024-05-24T11:33:49.276507Z","iopub.status.idle":"2024-05-24T11:33:49.291838Z","shell.execute_reply.started":"2024-05-24T11:33:49.276481Z","shell.execute_reply":"2024-05-24T11:33:49.290834Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"keras.utils.set_random_seed(29)","metadata":{"execution":{"iopub.status.busy":"2024-05-24T11:33:49.293978Z","iopub.execute_input":"2024-05-24T11:33:49.294234Z","iopub.status.idle":"2024-05-24T11:33:49.304977Z","shell.execute_reply.started":"2024-05-24T11:33:49.294210Z","shell.execute_reply":"2024-05-24T11:33:49.304040Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# ***Development***","metadata":{}},{"cell_type":"markdown","source":"## ***Define path and variables***","metadata":{}},{"cell_type":"code","source":"BASE_PATH = \"/kaggle/input/hms-harmful-brain-activity-classification\"\nSPEC_DIR = \"/tmp/dataset/hms-hbac\"\nos.makedirs(SPEC_DIR+'/train_spectrograms', exist_ok=True)\nos.makedirs(SPEC_DIR+'/test_spectrograms', exist_ok=True)","metadata":{"execution":{"iopub.status.busy":"2024-05-24T11:33:49.306965Z","iopub.execute_input":"2024-05-24T11:33:49.307231Z","iopub.status.idle":"2024-05-24T11:33:49.315529Z","shell.execute_reply.started":"2024-05-24T11:33:49.307208Z","shell.execute_reply":"2024-05-24T11:33:49.314749Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"verbose = 1  # Verbosity\nseed = 29  # Random seed\npreset = \"efficientnetv2_b2_imagenet\"  # Name of pretrained classifier\nimage_size = [400, 300]  # Input image size\nepochs = 13 # Training epochs\nbatch_size = 64  # Batch size\nlr_mode = \"cos\" # LR scheduler mode from one of \"cos\", \"step\", \"exp\"\ndrop_remainder = True  # Drop incomplete batches\nnum_classes = 6 # Number of classes in the dataset\nfold = 0 # Which fold to set as validation data\nclass_names = ['Seizure', 'LPD', 'GPD', 'LRDA','GRDA', 'Other']\nlabel2name = dict(enumerate(class_names))\nname2label = {v:k for k, v in label2name.items()}\nTARGETS = ['seizure_vote', 'lpd_vote', 'gpd_vote', 'lrda_vote', 'grda_vote', 'other_vote']","metadata":{"execution":{"iopub.status.busy":"2024-05-24T11:33:49.316567Z","iopub.execute_input":"2024-05-24T11:33:49.316844Z","iopub.status.idle":"2024-05-24T11:33:49.325870Z","shell.execute_reply.started":"2024-05-24T11:33:49.316822Z","shell.execute_reply":"2024-05-24T11:33:49.325029Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## ***Load Data***","metadata":{}},{"cell_type":"markdown","source":"# ***Training***","metadata":{}},{"cell_type":"code","source":"# Train + Valid\ndf = pd.read_csv(f'{BASE_PATH}/train.csv')\ndf['eeg_path'] = f'{BASE_PATH}/train_eegs/'+df['eeg_id'].astype(str)+'.parquet'\ndf['spec_path'] = f'{BASE_PATH}/train_spectrograms/'+df['spectrogram_id'].astype(str)+'.parquet'\ndf['spec2_path'] = f'{SPEC_DIR}/train_spectrograms/'+df['spectrogram_id'].astype(str)+'.npy'\ndf['class_name'] = df.expert_consensus.copy()\ndf['class_label'] = df.expert_consensus.map(name2label)\ndisplay(df.head(2))\n\n# Test\ntest_df = pd.read_csv(f'{BASE_PATH}/test.csv')\ntest_df['eeg_path'] = f'{BASE_PATH}/test_eegs/'+test_df['eeg_id'].astype(str)+'.parquet'\ntest_df['spec_path'] = f'{BASE_PATH}/test_spectrograms/'+test_df['spectrogram_id'].astype(str)+'.parquet'\ntest_df['spec2_path'] = f'{SPEC_DIR}/test_spectrograms/'+test_df['spectrogram_id'].astype(str)+'.npy'\ndisplay(test_df.head(2))\n","metadata":{"execution":{"iopub.status.busy":"2024-05-24T11:39:17.396151Z","iopub.execute_input":"2024-05-24T11:39:17.396822Z","iopub.status.idle":"2024-05-24T11:39:17.857543Z","shell.execute_reply.started":"2024-05-24T11:39:17.396790Z","shell.execute_reply":"2024-05-24T11:39:17.856615Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Define a function to process a single eeg_id\ndef process_spec(spec_id, split=\"train\"):\n    spec_path = f\"{BASE_PATH}/{split}_spectrograms/{spec_id}.parquet\"\n    spec = pd.read_parquet(spec_path)\n    spec = spec.fillna(0).values[:, 1:].T # fill NaN values with 0, transpose for (Time, Freq) -> (Freq, Time)\n    spec = spec.astype(\"float32\")\n    np.save(f\"{SPEC_DIR}/{split}_spectrograms/{spec_id}.npy\", spec)\n\n# Get unique spec_ids of train and valid data\nspec_ids = df[\"spectrogram_id\"].unique()\n\n# Parallelize the processing using joblib for training data\n_ = joblib.Parallel(n_jobs=-1, backend=\"loky\")(\n    joblib.delayed(process_spec)(spec_id, \"train\")\n    for spec_id in tqdm(spec_ids, total=len(spec_ids))\n)\n\n# Get unique spec_ids of test data\ntest_spec_ids = test_df[\"spectrogram_id\"].unique()\n\n# Parallelize the processing using joblib for test data\n_ = joblib.Parallel(n_jobs=-1, backend=\"loky\")(\n    joblib.delayed(process_spec)(spec_id, \"test\")\n    for spec_id in tqdm(test_spec_ids, total=len(test_spec_ids))\n)","metadata":{"execution":{"iopub.status.busy":"2024-05-24T11:39:53.536110Z","iopub.execute_input":"2024-05-24T11:39:53.536979Z","iopub.status.idle":"2024-05-24T11:43:02.169122Z","shell.execute_reply.started":"2024-05-24T11:39:53.536943Z","shell.execute_reply":"2024-05-24T11:43:02.168162Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def build_augmenter(dim=[400, 300]):\n    augmenters = [\n        keras_cv.layers.MixUp(alpha=2.0),\n        keras_cv.layers.RandomCutout(height_factor=(1.0, 1.0),\n                                     width_factor=(0.06, 0.1)), # freq-masking\n        keras_cv.layers.RandomCutout(height_factor=(0.06, 0.1),\n                                     width_factor=(1.0, 1.0)), # time-masking\n    ]\n    \n    def augment(img, label):\n        data = {\"images\":img, \"labels\":label}\n        for augmenter in augmenters:\n            if tf.random.uniform([]) < 0.5:\n                data = augmenter(data, training=True)\n        return data[\"images\"], data[\"labels\"]\n    \n    return augment\n\n\ndef build_decoder(with_labels=True, target_size=[400, 300], dtype=32):\n    def decode_signal(path, offset=None):\n        # Read .npy files and process the signal\n        file_bytes = tf.io.read_file(path)\n        sig = tf.io.decode_raw(file_bytes, tf.float32)\n        sig = sig[1024//dtype:]  # Remove header tag\n        sig = tf.reshape(sig, [400, -1])\n        \n        # Extract labeled subsample from full spectrogram using \"offset\"\n        if offset is not None: \n            offset = offset // 2  # Only odd values are given\n            sig = sig[:, offset:offset+300]\n            \n            # Pad spectrogram to ensure the same input shape of [400, 300]\n            pad_size = tf.math.maximum(0, 300 - tf.shape(sig)[1])\n            sig = tf.pad(sig, [[0, 0], [0, pad_size]])\n            sig = tf.reshape(sig, [400, 300])\n        \n        # Log spectrogram \n        sig = tf.clip_by_value(sig, tf.math.exp(-4.0), tf.math.exp(8.0)) # avoid 0 in log\n        sig = tf.math.log(sig)\n        \n        # Normalize spectrogram\n        sig -= tf.math.reduce_mean(sig)\n        sig /= tf.math.reduce_std(sig) + 1e-6\n        \n        # Mono channel to 3 channels to use \"ImageNet\" weights\n        sig = tf.tile(sig[..., None], [1, 1, 3])\n        return sig\n    \n    def decode_label(label):\n        label = tf.one_hot(label, num_classes)\n        label = tf.cast(label, tf.float32)\n        label = tf.reshape(label, [num_classes])\n        return label\n    \n    def decode_with_labels(path, offset=None, label=None):\n        sig = decode_signal(path, offset)\n        label = decode_label(label)\n        return (sig, label)\n    \n    return decode_with_labels if with_labels else decode_signal\n\n\ndef build_dataset(paths, offsets=None, labels=None, batch_size=32, cache=True,\n                  decode_fn=None, augment_fn=None,\n                  augment=False, repeat=True, shuffle=1024, \n                  cache_dir=\"\", drop_remainder=False):\n    if cache_dir != \"\" and cache is True:\n        os.makedirs(cache_dir, exist_ok=True)\n    \n    if decode_fn is None:\n        decode_fn = build_decoder(labels is not None)\n    \n    if augment_fn is None:\n        augment_fn = build_augmenter()\n    \n    AUTO = tf.data.experimental.AUTOTUNE\n    slices = (paths, offsets) if labels is None else (paths, offsets, labels)\n    \n    ds = tf.data.Dataset.from_tensor_slices(slices)\n    ds = ds.map(decode_fn, num_parallel_calls=AUTO)\n    ds = ds.cache(cache_dir) if cache else ds\n    ds = ds.repeat() if repeat else ds\n    if shuffle: \n        ds = ds.shuffle(shuffle, seed=29)\n        opt = tf.data.Options()\n        opt.experimental_deterministic = False\n        ds = ds.with_options(opt)\n    ds = ds.batch(batch_size, drop_remainder=drop_remainder)\n    ds = ds.map(augment_fn, num_parallel_calls=AUTO) if augment else ds\n    ds = ds.prefetch(AUTO)\n    return ds\n","metadata":{"execution":{"iopub.status.busy":"2024-05-24T11:43:02.171478Z","iopub.execute_input":"2024-05-24T11:43:02.171834Z","iopub.status.idle":"2024-05-24T11:43:02.202905Z","shell.execute_reply.started":"2024-05-24T11:43:02.171802Z","shell.execute_reply":"2024-05-24T11:43:02.201697Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import StratifiedGroupKFold\n\nsgkf = StratifiedGroupKFold(n_splits=5, shuffle=True, random_state=29)\ndf[\"fold\"] = -1\ndf.reset_index(drop=True, inplace=True)\nfor fold, (train_idx, valid_idx) in enumerate(\n    sgkf.split(df, y=df[\"class_name\"], groups=df[\"patient_id\"])\n):\n    df.loc[valid_idx, \"fold\"] = fold\ndf.groupby([\"fold\", \"class_name\"])[[\"eeg_id\"]].count().T\n","metadata":{"execution":{"iopub.status.busy":"2024-05-24T11:43:32.634477Z","iopub.execute_input":"2024-05-24T11:43:32.634826Z","iopub.status.idle":"2024-05-24T11:43:34.137396Z","shell.execute_reply.started":"2024-05-24T11:43:32.634801Z","shell.execute_reply":"2024-05-24T11:43:34.136342Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample_df = df.groupby(\"spectrogram_id\").head(1).reset_index(drop=True)\ntrain_df = sample_df[sample_df.fold != 0]\nvalid_df = sample_df[sample_df.fold == 0]\nprint(f\"# Num Train: {len(train_df)} | Num Valid: {len(valid_df)}\")\n\ntrain_paths = train_df.spec2_path.values\ntrain_offsets = train_df.spectrogram_label_offset_seconds.values.astype(int)\ntrain_labels = train_df.class_label.values\ntrain_ds = build_dataset(train_paths, train_offsets, train_labels, batch_size=64,\n                         repeat=True, shuffle=True, augment=True, cache=True)\n\nvalid_paths = valid_df.spec2_path.values\nvalid_offsets = valid_df.spectrogram_label_offset_seconds.values.astype(int)\nvalid_labels = valid_df.class_label.values\nvalid_ds = build_dataset(valid_paths, valid_offsets, valid_labels, batch_size=64,\n                         repeat=False, shuffle=False, augment=False, cache=True)","metadata":{"execution":{"iopub.status.busy":"2024-05-24T11:44:00.640957Z","iopub.execute_input":"2024-05-24T11:44:00.641366Z","iopub.status.idle":"2024-05-24T11:44:01.281841Z","shell.execute_reply.started":"2024-05-24T11:44:00.641331Z","shell.execute_reply":"2024-05-24T11:44:01.280850Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"LOSS = keras.losses.KLDivergence()","metadata":{"execution":{"iopub.status.busy":"2024-05-24T11:44:02.911357Z","iopub.execute_input":"2024-05-24T11:44:02.911770Z","iopub.status.idle":"2024-05-24T11:44:02.916801Z","shell.execute_reply.started":"2024-05-24T11:44:02.911736Z","shell.execute_reply":"2024-05-24T11:44:02.915767Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Build Classifier\nmodel = keras_cv.models.ImageClassifier.from_preset(\n    'efficientnetv2_b2_imagenet', num_classes=6\n)\n\n# Compile the model  \nmodel.compile(optimizer=keras.optimizers.Adam(learning_rate=1e-4),\n              loss=LOSS)\n\n# Model Sumamry\nmodel.summary()\n","metadata":{"execution":{"iopub.status.busy":"2024-05-24T11:44:04.935622Z","iopub.execute_input":"2024-05-24T11:44:04.936363Z","iopub.status.idle":"2024-05-24T11:44:09.479289Z","shell.execute_reply.started":"2024-05-24T11:44:04.936331Z","shell.execute_reply":"2024-05-24T11:44:09.478154Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import math\n\ndef get_lr_callback(batch_size=8, mode='cos', epochs=10, plot=False):\n    lr_start, lr_max, lr_min = 5e-5, 6e-6 * batch_size, 1e-5\n    lr_ramp_ep, lr_sus_ep, lr_decay = 3, 0, 0.75\n\n    def lrfn(epoch):  # Learning rate update function\n        if epoch < lr_ramp_ep: lr = (lr_max - lr_start) / lr_ramp_ep * epoch + lr_start\n        elif epoch < lr_ramp_ep + lr_sus_ep: lr = lr_max\n        elif mode == 'exp': lr = (lr_max - lr_min) * lr_decay**(epoch - lr_ramp_ep - lr_sus_ep) + lr_min\n        elif mode == 'step': lr = lr_max * lr_decay**((epoch - lr_ramp_ep - lr_sus_ep) // 2)\n        elif mode == 'cos':\n            decay_total_epochs, decay_epoch_index = epochs - lr_ramp_ep - lr_sus_ep + 3, epoch - lr_ramp_ep - lr_sus_ep\n            phase = math.pi * decay_epoch_index / decay_total_epochs\n            lr = (lr_max - lr_min) * 0.5 * (1 + math.cos(phase)) + lr_min\n        return lr\n\n    if plot:  # Plot lr curve if plot is True\n        plt.figure(figsize=(10, 5))\n        plt.plot(np.arange(epochs), [lrfn(epoch) for epoch in np.arange(epochs)], marker='o')\n        plt.xlabel('epoch'); plt.ylabel('lr')\n        plt.title('LR Scheduler')\n        plt.show()\n\n    return keras.callbacks.LearningRateScheduler(lrfn, verbose=False)  # Create lr callback\n","metadata":{"execution":{"iopub.status.busy":"2024-05-24T11:44:12.382798Z","iopub.execute_input":"2024-05-24T11:44:12.383137Z","iopub.status.idle":"2024-05-24T11:44:12.393861Z","shell.execute_reply.started":"2024-05-24T11:44:12.383112Z","shell.execute_reply":"2024-05-24T11:44:12.392926Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"lr_cb = get_lr_callback(64, mode=lr_mode, plot=True)","metadata":{"execution":{"iopub.status.busy":"2024-05-24T11:44:19.096866Z","iopub.execute_input":"2024-05-24T11:44:19.097248Z","iopub.status.idle":"2024-05-24T11:44:19.388139Z","shell.execute_reply.started":"2024-05-24T11:44:19.097217Z","shell.execute_reply":"2024-05-24T11:44:19.387242Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ckpt_cb = keras.callbacks.ModelCheckpoint(\"best_model.keras\",\n                                         monitor='val_loss',\n                                         save_best_only=True,\n                                         save_weights_only=False,\n                                         mode='min')","metadata":{"execution":{"iopub.status.busy":"2024-05-24T11:44:21.996891Z","iopub.execute_input":"2024-05-24T11:44:21.997605Z","iopub.status.idle":"2024-05-24T11:44:22.001935Z","shell.execute_reply.started":"2024-05-24T11:44:21.997570Z","shell.execute_reply":"2024-05-24T11:44:22.001028Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit(\n    train_ds, \n    epochs=13,\n    callbacks=[lr_cb, ckpt_cb], \n    steps_per_epoch=len(train_df)//64,\n    validation_data=valid_ds, \n    verbose=1\n)\n","metadata":{"execution":{"iopub.status.busy":"2024-05-24T12:16:21.663651Z","iopub.execute_input":"2024-05-24T12:16:21.664053Z","iopub.status.idle":"2024-05-24T12:40:27.398715Z","shell.execute_reply.started":"2024-05-24T12:16:21.664022Z","shell.execute_reply":"2024-05-24T12:40:27.397918Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.load_weights(\"best_model.keras\")","metadata":{"execution":{"iopub.status.busy":"2024-05-24T12:40:37.334020Z","iopub.execute_input":"2024-05-24T12:40:37.334438Z","iopub.status.idle":"2024-05-24T12:40:44.757305Z","shell.execute_reply.started":"2024-05-24T12:40:37.334405Z","shell.execute_reply":"2024-05-24T12:40:44.755827Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_paths = test_df.spec2_path.values\ntest_ds = build_dataset(test_paths, batch_size=min(64, len(test_df)),\n                         repeat=False, shuffle=False, cache=False, augment=False)\n","metadata":{"execution":{"iopub.status.busy":"2024-05-24T12:40:44.812916Z","iopub.execute_input":"2024-05-24T12:40:44.813250Z","iopub.status.idle":"2024-05-24T12:40:44.854863Z","shell.execute_reply.started":"2024-05-24T12:40:44.813192Z","shell.execute_reply":"2024-05-24T12:40:44.854102Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"preds = model.predict(test_ds)\n","metadata":{"execution":{"iopub.status.busy":"2024-05-24T12:40:45.987698Z","iopub.execute_input":"2024-05-24T12:40:45.988075Z","iopub.status.idle":"2024-05-24T12:40:46.440752Z","shell.execute_reply.started":"2024-05-24T12:40:45.988044Z","shell.execute_reply":"2024-05-24T12:40:46.439836Z"},"trusted":true},"execution_count":null,"outputs":[]}]}