{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"Training Notebook for the G2Net competition. This implements a Bi-directional GRU using Keras, using preprocessed spectrogram.\n\nThis uses Yasufumi Nakama's spectrogram preprocessing notebooks and datasets:\n* Train: [Notebook](https://www.kaggle.com/yasufuminakama/g2net-spectrogram-generation-train), [Dataset](https://www.kaggle.com/yasufuminakama/g2net-n-mels-128-train-images)\n* Test: [Notebook](https://www.kaggle.com/yasufuminakama/g2net-spectrogram-generation-test), [Dataset](https://www.kaggle.com/yasufuminakama/g2net-n-mels-128-test-images)","metadata":{}},{"cell_type":"code","source":"import os\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nimport tensorflow as tf\nfrom tensorflow.keras import layers","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2021-07-03T03:16:26.413427Z","iopub.execute_input":"2021-07-03T03:16:26.413854Z","iopub.status.idle":"2021-07-03T03:16:33.151936Z","shell.execute_reply.started":"2021-07-03T03:16:26.413757Z","shell.execute_reply":"2021-07-03T03:16:33.150906Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class CustomDataset(tf.keras.utils.Sequence):\n    def __init__(self, df, directory, batch_size=32, random_state=42, shuffle=True, target=True, ext='.npy'):\n        np.random.seed(random_state)\n        \n        self.directory = directory\n        self.df = df\n        self.shuffle = shuffle\n        self.target = target\n        self.batch_size = batch_size\n        self.ext = ext\n        \n        self.on_epoch_end()\n    \n    def __len__(self):\n        return np.ceil(self.df.shape[0] / self.batch_size).astype(int)\n    \n    def __getitem__(self, idx):\n        start_idx = idx * self.batch_size\n        batch = self.df[start_idx: start_idx + self.batch_size]\n        \n        signals = []\n\n        for fname in batch.id:\n            path = os.path.join(self.directory, fname + self.ext)\n            data = np.load(path)\n            signals.append(data)\n        \n        signals = np.stack(signals).astype('float32')\n        \n        if self.target:\n            return signals, batch.target.values\n        else:\n            return signals\n    \n    def on_epoch_end(self):\n        if self.shuffle:\n            self.df = self.df.sample(frac=1).reset_index(drop=True)","metadata":{"execution":{"iopub.status.busy":"2021-07-03T03:16:33.153412Z","iopub.execute_input":"2021-07-03T03:16:33.153704Z","iopub.status.idle":"2021-07-03T03:16:33.16447Z","shell.execute_reply.started":"2021-07-03T03:16:33.153676Z","shell.execute_reply":"2021-07-03T03:16:33.163412Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def build_model():\n    inputs = layers.Input(shape=(27, 128))\n\n    gru1 = layers.Bidirectional(layers.GRU(128, return_sequences=True), name='gru_1')\n    gru2 = layers.Bidirectional(layers.GRU(128, return_sequences=True), name='gru_2')\n    pool1 = layers.GlobalAveragePooling1D(name='avg_pool')\n    pool2 = layers.GlobalMaxPooling1D(name='max_pool')\n\n    x = gru1(inputs)\n    x = gru2(x)\n    x = tf.keras.layers.Concatenate()([pool1(x), pool2(x)])\n    \n    x = layers.Dense(256, activation=\"relu\")(x)\n    x = layers.Dense(128, activation=\"relu\")(x)\n    x = layers.Dense(1, activation=\"sigmoid\", name=\"sigmoid\")(x)\n\n    model = tf.keras.Model(inputs=inputs, outputs=x)\n    \n    return model","metadata":{"execution":{"iopub.status.busy":"2021-07-03T03:17:21.556284Z","iopub.execute_input":"2021-07-03T03:17:21.556646Z","iopub.status.idle":"2021-07-03T03:17:21.565654Z","shell.execute_reply.started":"2021-07-03T03:17:21.556617Z","shell.execute_reply":"2021-07-03T03:17:21.564924Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = pd.read_csv('../input/g2net-gravitational-wave-detection/training_labels.csv')\nsub = pd.read_csv('../input/g2net-gravitational-wave-detection/sample_submission.csv')\ntrain.head()","metadata":{"execution":{"iopub.status.busy":"2021-07-03T03:16:34.934666Z","iopub.execute_input":"2021-07-03T03:16:34.934995Z","iopub.status.idle":"2021-07-03T03:16:35.589837Z","shell.execute_reply.started":"2021-07-03T03:16:34.934967Z","shell.execute_reply":"2021-07-03T03:16:35.588848Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample_df = train.sample(frac=1).reset_index(drop=True)\n\nsplit = int(sample_df.shape[0] * 0.8)\ntrain_df = sample_df[:split]\nvalid_df = sample_df[split:]","metadata":{"execution":{"iopub.status.busy":"2021-07-03T03:16:35.591145Z","iopub.execute_input":"2021-07-03T03:16:35.59146Z","iopub.status.idle":"2021-07-03T03:16:35.742501Z","shell.execute_reply.started":"2021-07-03T03:16:35.591435Z","shell.execute_reply":"2021-07-03T03:16:35.741531Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_dset = CustomDataset(\n    train_df, '../input/g2net-n-mels-128-train-images', batch_size=64)\n\nvalid_dset = CustomDataset(\n    valid_df, '../input/g2net-n-mels-128-train-images', batch_size=64, shuffle=False)\n\ntest_dset = CustomDataset(\n    sub, \"../input/g2net-n-mels-128-test-images\", batch_size=64, target=False, shuffle=False)","metadata":{"execution":{"iopub.status.busy":"2021-07-03T03:16:35.931012Z","iopub.execute_input":"2021-07-03T03:16:35.931355Z","iopub.status.idle":"2021-07-03T03:16:36.039844Z","shell.execute_reply.started":"2021-07-03T03:16:35.931328Z","shell.execute_reply":"2021-07-03T03:16:36.038945Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = build_model()\nmodel.compile(\"adam\", loss=\"binary_crossentropy\", metrics=[tf.keras.metrics.AUC()])\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2021-07-03T03:17:24.392467Z","iopub.execute_input":"2021-07-03T03:17:24.392922Z","iopub.status.idle":"2021-07-03T03:17:25.25408Z","shell.execute_reply.started":"2021-07-03T03:17:24.392892Z","shell.execute_reply":"2021-07-03T03:17:25.253125Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ckpt = tf.keras.callbacks.ModelCheckpoint(\n    \"model_weights.h5\", save_best_only=True, save_weights_only=True,\n)\n\ntrain_history = model.fit(\n    train_dset, \n    use_multiprocessing=True, \n    workers=4, \n    epochs=10,\n    validation_data=valid_dset,\n    callbacks=[ckpt],\n)","metadata":{"execution":{"iopub.status.busy":"2021-07-03T03:17:29.930594Z","iopub.execute_input":"2021-07-03T03:17:29.93096Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.load_weights('model_weights.h5')","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_pred = model.predict(\n    test_dset, use_multiprocessing=True, workers=4, verbose=1\n)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub['target'] = y_pred\nsub.to_csv('submission.csv', index=False)","metadata":{},"execution_count":null,"outputs":[]}]}