{"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":"Learning how to use [KerasTuner](https://keras.io/keras_tuner/) to build a better Tensorflow model.\n\n## TODO\n\n- Add kfold option\n\n## Versions\n\n- V13: Trying augmentation. (e.g. experimental.preprocessing.RandomFlip)\n- V12: Added needed reset_index(drop=True)\n- V11: Break out submission results to view intermediate values. Add Kfold value but it's unused.\n- V10: Save model: best_model.save(\"best_model\")\n- V9: Switching back to make_model. Trying max_trials=15\n```python\ntuner = kt.tuners.BayesianOptimization(\n#     make_model_siren,\n    make_model,\n    objective='val_loss',\n    max_trials=5,  # Set to 5 to run quicker, but need 100+ for good results\n    overwrite=True)\n```\n- V8: Siren Submission: LB: 0.667\n- V7: Working on Siren Layer: \n- V6: Full save: max_trials=100\n- V5: Increasing max_trials from 5 to 100. If Quick Save doesn't work, there will be a V6.\n```python\ntuner = kt.tuners.BayesianOptimization(\n    make_model,\n    objective='val_loss',\n    max_trials=5,  # Set to 5 to run quicker, but need 100+ for good results\n    overwrite=True)\n```\n- V4: Tuning filters and units.  LB: 0.702\n```python\n    x = layers.Dense(\n        units=hp.Int('num_dense_units', min_value=16, max_value=64, step=8),\n        activation='relu'\n    )(x)\n```    \n- V3: Documentation\n- V2: Documentation\n- V1: Only tuning Dropout()\n```python\n    x = layers.Dropout(\n        hp.Float('dense_dropout', min_value=0., max_value=0.7)\n    )(x)\n```\n\n## References\n\n- [Keras + KerasTuner best practices](https://www.kaggle.com/fchollet/keras-kerastuner-best-practices)\n- [MoA: Keras + KerasTuner best practices](https://www.kaggle.com/fchollet/moa-keras-kerastuner-best-practices)\n- [Deep Learning with Python, Second Edition](https://www.manning.com/books/deep-learning-with-python-second-edition) - Chapter 13\n- [Jane Street: Neural Network Starter](https://www.kaggle.com/gogo827jz/jane-street-neural-network-starter)\n- [NN Model tuning with Keras Tuner](https://www.kaggle.com/sirishapb/nn-model-tuning-with-keras-tuner)\n","metadata":{"execution":{"iopub.status.busy":"2021-10-06T14:51:45.864214Z","iopub.execute_input":"2021-10-06T14:51:45.864969Z","iopub.status.idle":"2021-10-06T14:51:45.888709Z","shell.execute_reply.started":"2021-10-06T14:51:45.864882Z","shell.execute_reply":"2021-10-06T14:51:45.887418Z"}}},{"cell_type":"markdown","source":"# Load Libraries","metadata":{}},{"cell_type":"code","source":"import os\nimport glob\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\nimport pandas as pd\nimport numpy as np\nfrom pathlib import Path\n\nimport random\nfrom tqdm.notebook import tqdm\nimport pydicom # Handle MRI images\n\nimport cv2  # OpenCV - https://docs.opencv.org/master/d6/d00/tutorial_py_root.html\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn import model_selection\n\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.initializers import RandomUniform\n","metadata":{"execution":{"iopub.status.busy":"2021-10-11T23:40:59.549773Z","iopub.execute_input":"2021-10-11T23:40:59.551770Z","iopub.status.idle":"2021-10-11T23:41:01.509106Z","shell.execute_reply.started":"2021-10-11T23:40:59.551648Z","shell.execute_reply":"2021-10-11T23:41:01.508277Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Load Datasets","metadata":{}},{"cell_type":"code","source":"data_dir = Path('../input/rsna-miccai-brain-tumor-radiogenomic-classification/')\n\nmri_types = [\"FLAIR\", \"T1w\", \"T2w\", \"T1wCE\"]\nexcluded_images = [109, 123, 709] # Bad images\n\ntrain_df = pd.read_csv(data_dir / \"train_labels.csv\")\ntest_df = pd.read_csv(data_dir / \"sample_submission.csv\")\nsample_submission = pd.read_csv(data_dir / \"sample_submission.csv\")\n\ntrain_df = train_df[~train_df.BraTS21ID.isin(excluded_images)].reset_index(drop=True)\n\n","metadata":{"execution":{"iopub.status.busy":"2021-10-11T23:41:01.510786Z","iopub.execute_input":"2021-10-11T23:41:01.511101Z","iopub.status.idle":"2021-10-11T23:41:01.527923Z","shell.execute_reply.started":"2021-10-11T23:41:01.511064Z","shell.execute_reply":"2021-10-11T23:41:01.527297Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# KFold - Future Features","metadata":{}},{"cell_type":"code","source":"def create_folds(data, num_splits):\n    data[\"kfold\"] = -1\n    kf = model_selection.KFold(n_splits=num_splits, shuffle=True, random_state=42)\n    for f, (t, v) in enumerate(kf.split(X=data)):\n        data.loc[v, \"kfold\"] = f\n    return data","metadata":{"execution":{"iopub.status.busy":"2021-10-11T23:41:01.530376Z","iopub.execute_input":"2021-10-11T23:41:01.530565Z","iopub.status.idle":"2021-10-11T23:41:01.537359Z","shell.execute_reply.started":"2021-10-11T23:41:01.530543Z","shell.execute_reply":"2021-10-11T23:41:01.536641Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# EPOCHS=20\nk = 5\n\ntrain_df = create_folds(train_df, k)","metadata":{"execution":{"iopub.status.busy":"2021-10-11T23:41:01.540876Z","iopub.execute_input":"2021-10-11T23:41:01.541124Z","iopub.status.idle":"2021-10-11T23:41:01.551847Z","shell.execute_reply.started":"2021-10-11T23:41:01.541101Z","shell.execute_reply":"2021-10-11T23:41:01.551202Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df.head()","metadata":{"execution":{"iopub.status.busy":"2021-10-11T23:41:01.552960Z","iopub.execute_input":"2021-10-11T23:41:01.553223Z","iopub.status.idle":"2021-10-11T23:41:01.569263Z","shell.execute_reply.started":"2021-10-11T23:41:01.553189Z","shell.execute_reply":"2021-10-11T23:41:01.568321Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Utility Functions","metadata":{}},{"cell_type":"code","source":"def load_dicom(path, size = 224):\n    ''' \n    Reads a DICOM image, standardizes so that the pixel values are between 0 and 1, then rescales to 0 and 255\n    \n    Not super sure if this kind of scaling is appropriate, but everyone seems to do it. \n    '''\n    dicom = pydicom.read_file(path)\n    data = dicom.pixel_array\n    # transform data into black and white scale / grayscale\n#     data = data - np.min(data)\n    if np.max(data) != 0:\n        data = data / np.max(data)\n    data = (data * 255).astype(np.uint8)\n    return cv2.resize(data, (size, size))\n\ndef get_all_image_paths(brats21id, image_type, folder='train'): \n    '''\n    Returns an arry of all the images of a particular type for a particular patient ID\n    '''\n    assert(image_type in mri_types)\n    \n    patient_path = os.path.join(\n        \"../input/rsna-miccai-brain-tumor-radiogenomic-classification/%s/\" % folder, \n        str(brats21id).zfill(5),\n    )\n\n    paths = sorted(\n        glob.glob(os.path.join(patient_path, image_type, \"*\")), \n        key=lambda x: int(x[:-4].split(\"-\")[-1]),\n    )\n    \n    num_images = len(paths)\n    \n    start = int(num_images * 0.25)\n    end = int(num_images * 0.75)\n\n    interval = 3\n    \n    if num_images < 10: \n        interval = 1\n    \n    return np.array(paths[start:end:interval])\n\ndef get_all_images(brats21id, image_type, folder='train', size=225):\n    return [load_dicom(path, size) for path in get_all_image_paths(brats21id, image_type, folder)]\n\ndef get_all_data_for_train(image_type, image_size=32):\n    global train_df\n    \n    X = []\n    y = []\n    train_ids = []\n\n    for i in tqdm(train_df.index):\n        x = train_df.loc[i]\n        images = get_all_images(int(x['BraTS21ID']), image_type, 'train', image_size)\n        label = x['MGMT_value']\n\n        X += images\n        y += [label] * len(images)\n        train_ids += [int(x['BraTS21ID'])] * len(images)\n        assert(len(X) == len(y))\n    return np.array(X), np.array(y), np.array(train_ids)\n\ndef get_all_data_for_test(image_type, image_size=32):\n    global test_df\n    \n    X = []\n    test_ids = []\n\n    for i in tqdm(test_df.index):\n        x = test_df.loc[i]\n        images = get_all_images(int(x['BraTS21ID']), image_type, 'test', image_size)\n        X += images\n        test_ids += [int(x['BraTS21ID'])] * len(images)\n\n    return np.array(X), np.array(test_ids)","metadata":{"execution":{"iopub.status.busy":"2021-10-11T23:41:01.571070Z","iopub.execute_input":"2021-10-11T23:41:01.571603Z","iopub.status.idle":"2021-10-11T23:41:01.588347Z","shell.execute_reply.started":"2021-10-11T23:41:01.571568Z","shell.execute_reply":"2021-10-11T23:41:01.587604Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Load all Images\n```\nX - contains all the images for each patient \ntrainidt - trainidt is a mask vector into X, y for training.  There's a patient id/BraTS21ID corresponding to each image (e.g. (0, 0, 0, 0, 2,2, 3,3,3,3,3,...) )\ntestidt - testidt is a mask vector into X_test for testing\n```","metadata":{}},{"cell_type":"code","source":"X, y, trainidt = get_all_data_for_train('T1wCE', image_size=32)\nX_test, testidt = get_all_data_for_test('T1wCE', image_size=32)","metadata":{"execution":{"iopub.status.busy":"2021-10-11T23:41:01.589536Z","iopub.execute_input":"2021-10-11T23:41:01.590010Z","iopub.status.idle":"2021-10-11T23:43:16.556997Z","shell.execute_reply.started":"2021-10-11T23:41:01.589888Z","shell.execute_reply":"2021-10-11T23:43:16.556128Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Train/Validation Split","metadata":{}},{"cell_type":"code","source":"X_train, X_valid, y_train, y_valid, trainidt_train, trainidt_valid = train_test_split(X, y, trainidt, test_size=0.2, random_state=42)","metadata":{"execution":{"iopub.status.busy":"2021-10-11T23:43:16.558319Z","iopub.execute_input":"2021-10-11T23:43:16.558661Z","iopub.status.idle":"2021-10-11T23:43:16.574230Z","shell.execute_reply.started":"2021-10-11T23:43:16.558623Z","shell.execute_reply":"2021-10-11T23:43:16.573404Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Adding a Dimension","metadata":{}},{"cell_type":"code","source":"X_train = tf.expand_dims(X_train, axis=-1)\nX_valid = tf.expand_dims(X_valid, axis=-1)\nX_train.shape","metadata":{"execution":{"iopub.status.busy":"2021-10-11T23:43:16.575633Z","iopub.execute_input":"2021-10-11T23:43:16.575922Z","iopub.status.idle":"2021-10-11T23:43:18.487130Z","shell.execute_reply.started":"2021-10-11T23:43:16.575872Z","shell.execute_reply":"2021-10-11T23:43:18.486415Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## One-hot encode labels","metadata":{}},{"cell_type":"code","source":"y_train = to_categorical(y_train)\ny_valid = to_categorical(y_valid)","metadata":{"execution":{"iopub.status.busy":"2021-10-11T23:43:18.490002Z","iopub.execute_input":"2021-10-11T23:43:18.490228Z","iopub.status.idle":"2021-10-11T23:43:18.496556Z","shell.execute_reply.started":"2021-10-11T23:43:18.490196Z","shell.execute_reply":"2021-10-11T23:43:18.495812Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Tunable Model","metadata":{}},{"cell_type":"markdown","source":"## Using the SIREN activation layer. Refer to https://vsitzmann.github.io/siren/ for more details.","metadata":{}},{"cell_type":"code","source":"class SineDenseLayer(keras.layers.Layer):\n    # See paper sec. 3.2, final paragraph, and supplement Sec. 1.5 for discussion of omega_0.\n    \n    # If is_first=True, omega_0 is a frequency factor which simply multiplies the activations before the \n    # nonlinearity. Different signals may require different omega_0 in the first layer - this is a \n    # hyperparameter.\n    \n    # If is_first=False, then the weights will be divided by omega_0 so as to keep the magnitude of \n    # activations constant, but boost gradients to the weight matrix (see supplement Sec. 1.5)\n    \n    def __init__(self, features,\n                 is_first=False, omega_0=30):\n        super().__init__()\n        self.omega_0 = omega_0\n        self.is_first = is_first\n        \n        self.features = features\n        \n        if self.is_first:\n            initializer = RandomUniform(-1 / self.features, 1 / self.features)   \n            self.linear = keras.layers.Dense(features, kernel_initializer=initializer)\n    \n        else:\n            initializer = RandomUniform(-np.sqrt(6 / self.features) / self.omega_0, np.sqrt(6 / self.features) / self.omega_0)\n            self.linear = keras.layers.Dense(features, kernel_initializer=initializer)\n     \n\n    def call(self, input):\n        return tf.math.sin(self.omega_0 * self.linear(input))\n    \n#     def forward_with_intermediate(self, input): \n#         # For visualization of activation distributions\n#         intermediate = self.omega_0 * self.linear(input)\n#         return tf.math.sin(intermediate), intermediate\n\nclass SineConvLayer(keras.layers.Layer):\n    # See paper sec. 3.2, final paragraph, and supplement Sec. 1.5 for discussion of omega_0.\n    \n    # If is_first=True, omega_0 is a frequency factor which simply multiplies the activations before the \n    # nonlinearity. Different signals may require different omega_0 in the first layer - this is a \n    # hyperparameter.\n    \n    # If is_first=False, then the weights will be divided by omega_0 so as to keep the magnitude of \n    # activations constant, but boost gradients to the weight matrix (see supplement Sec. 1.5)\n    \n    def __init__(self, features, kernel_size,\n                 is_first=False, omega_0=30):\n        super().__init__()\n        self.omega_0 = omega_0\n        self.is_first = is_first\n        \n        self.features = features\n        \n        if self.is_first:\n            initializer = RandomUniform(-1 / self.features, 1 / self.features)            \n            self.conv = keras.layers.Conv2D(features, kernel_size, kernel_initializer=initializer)\n            \n        else:\n            initializer = RandomUniform(-np.sqrt(6 / self.features) / self.omega_0, np.sqrt(6 / self.features) / self.omega_0)\n            self.conv = keras.layers.Conv2D(features, kernel_size, kernel_initializer=initializer)\n            \n\n    def call(self, input):\n        return tf.math.sin(self.omega_0 * self.conv(input))\n    \n#     def forward_with_intermediate(self, input): \n#         # For visualization of activation distributions\n#         intermediate = self.omega_0 * self.linear(input)\n#         return tf.math.sin(intermediate), intermediate\n\n","metadata":{"execution":{"iopub.status.busy":"2021-10-11T23:43:18.499222Z","iopub.execute_input":"2021-10-11T23:43:18.499408Z","iopub.status.idle":"2021-10-11T23:43:18.513656Z","shell.execute_reply.started":"2021-10-11T23:43:18.499387Z","shell.execute_reply":"2021-10-11T23:43:18.512986Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import keras_tuner as kt\n\n\ndef make_model(hp):\n    inputs = keras.Input(shape=X_train.shape[1:])\n    \n    x = keras.layers.experimental.preprocessing.Rescaling(1.0 / 255)(inputs)\n\n#     num_block = hp.Int('num_block', min_value=2, max_value=5, step=1)\n#     num_filters = hp.Int('num_filters', min_value=32, max_value=128, step=32)\n    \n#     x = keras.layers.Conv2D(64, kernel_size=(4, 4), activation=\"relu\", name=\"Conv_1\")(x)\n    x = keras.layers.Conv2D(filters=hp.Int('units_Conv_1_' + str(0),\n                                            min_value=64,\n                                            max_value=256,\n                                            step=32),\n                            kernel_size=(4, 4),\n                            activation=\"relu\", \n                            name=\"Conv_1\")(x)\n\n    x = keras.layers.MaxPool2D(pool_size=(2, 2))(x)\n\n#     x = keras.layers.Conv2D(32, kernel_size=(2, 2), activation=\"relu\", name=\"Conv_2\")(x)\n    x = keras.layers.Conv2D(filters=hp.Int('units_conv2_' + str(1),\n                                            min_value=16,\n                                            max_value=128,\n                                            step=16),\n                            kernel_size=(2, 2),\n                            activation=\"relu\",\n                            name=\"Conv_2\")(x)\n\n    x = keras.layers.MaxPool2D(pool_size=(1, 1))(x)\n    \n#     for i in range(num_block):\n#         x = keras.layers.Conv2D(num_filters, \n#                                 kernel_size=(4, 4),\n#                                 activation=\"relu\",\n#                                 )(x)\n    \n#         x = keras.layers.MaxPool2D(pool_size=(2, 2))(x)\n\n#     x = keras.layers.Conv2D(32, kernel_size=(2, 2), activation=\"relu\", name=\"Conv_2\")(x)\n#     x = keras.layers.MaxPool2D(pool_size=(1, 1))(x)\n\n#     h = keras.layers.Dropout(0.1)(h)\n    x = layers.Dropout(\n        hp.Float('dense_dropout', min_value=0., max_value=0.7)\n    )(x)\n    x = keras.layers.Flatten()(x)\n#     reduction_type = hp.Choice('reduction_type', ['flatten', 'avg'])\n#     if reduction_type == 'flatten':\n#         x = layers.Flatten()(x)\n#     else:\n#         x = layers.GlobalAveragePooling2D()(x)\n        \n#     x = keras.layers.Dense(32, activation=\"relu\")(x)\n    x = layers.Dense(\n        units=hp.Int('num_dense_units', min_value=16, max_value=64, step=8),\n        activation='relu'\n    )(x)\n\n    outputs = keras.layers.Dense(2, activation=\"softmax\")(x)\n\n    model = keras.Model(inputs, outputs)\n\n    roc_auc = tf.keras.metrics.AUC(name='roc_auc', curve='ROC')\n\n    model.compile(\n        loss=\"categorical_crossentropy\", optimizer=\"adam\", metrics=[roc_auc]\n    )\n    model.summary()\n    return model","metadata":{"execution":{"iopub.status.busy":"2021-10-11T23:43:18.516565Z","iopub.execute_input":"2021-10-11T23:43:18.516792Z","iopub.status.idle":"2021-10-11T23:43:18.572097Z","shell.execute_reply.started":"2021-10-11T23:43:18.516758Z","shell.execute_reply":"2021-10-11T23:43:18.571402Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Augmentation\n\n- https://www.tensorflow.org/guide/keras/preprocessing_layers\n- https://keras.io/examples/vision/image_classification_from_scratch/","metadata":{}},{"cell_type":"code","source":"def make_model_augmented(hp):\n    input_shape = (32, 32, 1)\n    classes = 10\n\n    # Create a data augmentation stage with horizontal flipping, rotations, zooms\n#     data_augmentation = keras.Sequential(\n#         [\n#             layers.experimental.preprocessing.RandomFlip(\"horizontal\"),\n#             layers.experimental.preprocessing.RandomRotation(0.1),\n#             layers.experimental.preprocessing.RandomZoom(0.1),\n#         ]\n#     )\n    \n    data_augmentation = keras.Sequential(\n    [\n        layers.experimental.preprocessing.RandomFlip(\"horizontal\"),\n        layers.experimental.preprocessing.RandomRotation(0.1),\n    ]\n)\n\n    shape=X_train.shape[1:]\n    print(f\"shape={shape}\") # shape=(32, 32, 1)\n    \n    inputs = keras.Input(shape=input_shape)\n    x = data_augmentation(inputs)\n\n    x = keras.layers.experimental.preprocessing.Rescaling(1.0 / 255)(x)\n#     x = layers.experimental.preprocessing.RandomFlip(\"horizontal\")(x),\n#     x = layers.experimental.preprocessing.RandomRotation(0.1)(x),\n#     x = layers.experimental.preprocessing.RandomZoom(\n#         height_factor = 0.2,\n#         width_factor = -0.3,\n#         fill_mode = \"constant\",\n#         interpolation = \"bilinear\",\n#         seed = 42\n#     )(x),\n#     num_block = hp.Int('num_block', min_value=2, max_value=5, step=1)\n#     num_filters = hp.Int('num_filters', min_value=32, max_value=128, step=32)\n    \n#     x = keras.layers.Conv2D(64, kernel_size=(4, 4), activation=\"relu\", name=\"Conv_1\")(x)\n    x = keras.layers.Conv2D(filters=hp.Int('units_Conv_1_' + str(0),\n                                            min_value=64,\n                                            max_value=256,\n                                            step=32),\n                            kernel_size=(4, 4),\n                            activation=\"relu\", \n                            name=\"Conv_1\")(x)\n\n    x = keras.layers.MaxPool2D(pool_size=(2, 2))(x)\n\n#     x = keras.layers.Conv2D(32, kernel_size=(2, 2), activation=\"relu\", name=\"Conv_2\")(x)\n    x = keras.layers.Conv2D(filters=hp.Int('units_conv2_' + str(1),\n                                            min_value=16,\n                                            max_value=128,\n                                            step=16),\n                            kernel_size=(2, 2),\n                            activation=\"relu\",\n                            name=\"Conv_2\")(x)\n\n    x = keras.layers.MaxPool2D(pool_size=(1, 1))(x)\n    \n#     for i in range(num_block):\n#         x = keras.layers.Conv2D(num_filters, \n#                                 kernel_size=(4, 4),\n#                                 activation=\"relu\",\n#                                 )(x)\n    \n#         x = keras.layers.MaxPool2D(pool_size=(2, 2))(x)\n\n#     x = keras.layers.Conv2D(32, kernel_size=(2, 2), activation=\"relu\", name=\"Conv_2\")(x)\n#     x = keras.layers.MaxPool2D(pool_size=(1, 1))(x)\n\n#     h = keras.layers.Dropout(0.1)(h)\n    x = layers.Dropout(\n        hp.Float('dense_dropout', min_value=0., max_value=0.7)\n    )(x)\n    x = keras.layers.Flatten()(x)\n#     reduction_type = hp.Choice('reduction_type', ['flatten', 'avg'])\n#     if reduction_type == 'flatten':\n#         x = layers.Flatten()(x)\n#     else:\n#         x = layers.GlobalAveragePooling2D()(x)\n        \n#     x = keras.layers.Dense(32, activation=\"relu\")(x)\n    x = layers.Dense(\n        units=hp.Int('num_dense_units', min_value=16, max_value=64, step=8),\n        activation='relu'\n    )(x)\n\n    outputs = keras.layers.Dense(2, activation=\"softmax\")(x)\n\n    model = keras.Model(inputs, outputs)\n\n    roc_auc = tf.keras.metrics.AUC(name='roc_auc', curve='ROC')\n\n    model.compile(\n        loss=\"categorical_crossentropy\", optimizer=\"adam\", metrics=[roc_auc]\n    )\n    model.summary()\n    return model","metadata":{"execution":{"iopub.status.busy":"2021-10-12T00:08:23.947084Z","iopub.execute_input":"2021-10-12T00:08:23.947427Z","iopub.status.idle":"2021-10-12T00:08:23.963443Z","shell.execute_reply.started":"2021-10-12T00:08:23.947395Z","shell.execute_reply":"2021-10-12T00:08:23.962716Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import keras_tuner as kt\n\n\ndef make_model_siren(hp):\n    inputs = keras.Input(shape=X_train.shape[1:])\n    \n    x = keras.layers.experimental.preprocessing.Rescaling(1.0 / 255)(inputs)\n\n    x = SineConvLayer(features=hp.Int('features_conv_1', min_value=64, max_value=256, step=32),\n                      kernel_size=hp.Int('kernel_conv_1', min_value=2, max_value=7, step=1),\n                      is_first=True, \n                      omega_0=hp.Int('omega_0_conv_1', min_value=10, max_value=50, step=5))(x)\n    \n    x = keras.layers.MaxPool2D(pool_size=(2, 2))(x)\n\n    x = SineConvLayer(features=hp.Int('features_conv_2', min_value=16, max_value=128, step=16),\n                      kernel_size=hp.Int('kernel_conv_2', min_value=2, max_value=7, step=1),\n                      is_first=False, \n                      omega_0=hp.Int('omega_0_conv_2', min_value=10, max_value=50, step=5))(x)\n\n    x = keras.layers.MaxPool2D(pool_size=(1, 1))(x)\n    \n    x = layers.Dropout(\n        hp.Float('dense_dropout', min_value=0., max_value=0.7)\n    )(x)\n    x = keras.layers.Flatten()(x)\n    x = SineDenseLayer(features=hp.Int('features_dense_1', min_value=64, max_value=256, step=32),\n                      is_first=False, \n                      omega_0=hp.Int('omega_0_dense_1', min_value=10, max_value=50, step=5))(x)\n\n    outputs = keras.layers.Dense(2, activation=\"softmax\")(x)\n\n    model = keras.Model(inputs, outputs)\n\n    roc_auc = tf.keras.metrics.AUC(name='roc_auc', curve='ROC')\n\n    model.compile(\n        loss=\"categorical_crossentropy\", optimizer=\"adam\", metrics=[roc_auc]\n    )\n    model.summary()\n    return model","metadata":{"execution":{"iopub.status.busy":"2021-10-11T23:43:18.590512Z","iopub.execute_input":"2021-10-11T23:43:18.590818Z","iopub.status.idle":"2021-10-11T23:43:18.606028Z","shell.execute_reply.started":"2021-10-11T23:43:18.590783Z","shell.execute_reply":"2021-10-11T23:43:18.605098Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Hyperparameter Search","metadata":{}},{"cell_type":"code","source":"tuner = kt.tuners.BayesianOptimization(\n#     make_model_siren,\n#     make_model,\n    make_model_augmented,\n    objective='val_loss',\n    max_trials=5,  # Set to 5 to run quicker, but need 100+ for good results\n    overwrite=True)\n\ncallbacks=[keras.callbacks.EarlyStopping(monitor='val_roc_acc', mode='max', patience=3, baseline=0.9)]\n\ntuner.search(X_train, y_train, validation_split=0.2, callbacks=callbacks, verbose=1, epochs=20)","metadata":{"execution":{"iopub.status.busy":"2021-10-12T00:08:36.272255Z","iopub.execute_input":"2021-10-12T00:08:36.272806Z","iopub.status.idle":"2021-10-12T00:09:45.348518Z","shell.execute_reply.started":"2021-10-12T00:08:36.272769Z","shell.execute_reply":"2021-10-12T00:09:45.345845Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Find the best epoch value","metadata":{}},{"cell_type":"code","source":"best_hp = tuner.get_best_hyperparameters()[0]\nbest_model = make_model(best_hp)","metadata":{"execution":{"iopub.status.busy":"2021-10-11T23:43:20.668163Z","iopub.status.idle":"2021-10-11T23:43:20.668484Z","shell.execute_reply.started":"2021-10-11T23:43:20.668322Z","shell.execute_reply":"2021-10-11T23:43:20.668338Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Save Model","metadata":{}},{"cell_type":"code","source":"best_model.save(\"best_model\")","metadata":{"execution":{"iopub.status.busy":"2021-10-11T23:43:20.669657Z","iopub.status.idle":"2021-10-11T23:43:20.670160Z","shell.execute_reply.started":"2021-10-11T23:43:20.669942Z","shell.execute_reply":"2021-10-11T23:43:20.669966Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = best_model.fit(X_train, y_train, validation_split=0.2, epochs=50)","metadata":{"execution":{"iopub.status.busy":"2021-10-11T23:43:20.671531Z","iopub.status.idle":"2021-10-11T23:43:20.672221Z","shell.execute_reply.started":"2021-10-11T23:43:20.671971Z","shell.execute_reply":"2021-10-11T23:43:20.671995Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Predictions on Validation Set","metadata":{}},{"cell_type":"code","source":"y_pred = best_model.predict(X_valid)\n\npred = np.argmax(y_pred, axis=1)\n\nresult = pd.DataFrame(trainidt_valid)\nresult[1] = pred\n\nresult.columns = [\"BraTS21ID\", \"MGMT_value\"]\nresult2 = result.groupby(\"BraTS21ID\", as_index=False).mean()\nresult2","metadata":{"execution":{"iopub.status.busy":"2021-10-11T23:43:20.673639Z","iopub.status.idle":"2021-10-11T23:43:20.678075Z","shell.execute_reply.started":"2021-10-11T23:43:20.677805Z","shell.execute_reply":"2021-10-11T23:43:20.677831Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"result2 = result2.merge(train_df, on=\"BraTS21ID\")\nresult2","metadata":{"execution":{"iopub.status.busy":"2021-10-11T23:43:20.679172Z","iopub.status.idle":"2021-10-11T23:43:20.679605Z","shell.execute_reply.started":"2021-10-11T23:43:20.679370Z","shell.execute_reply":"2021-10-11T23:43:20.679393Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"auc = roc_auc_score(\n    result2.MGMT_value_y,\n    result2.MGMT_value_x,\n)\nprint(f\"Validation AUC={auc}\")\n","metadata":{"execution":{"iopub.status.busy":"2021-10-11T23:43:20.681411Z","iopub.status.idle":"2021-10-11T23:43:20.684038Z","shell.execute_reply.started":"2021-10-11T23:43:20.683764Z","shell.execute_reply":"2021-10-11T23:43:20.683789Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Predictions on the Test Set","metadata":{}},{"cell_type":"code","source":"y_pred = best_model.predict(X_test)\n\npred = np.argmax(y_pred, axis=1) #\n\nresult = pd.DataFrame(testidt)\nresult[1] = pred\npred","metadata":{"execution":{"iopub.status.busy":"2021-10-11T23:43:20.685162Z","iopub.status.idle":"2021-10-11T23:43:20.685662Z","shell.execute_reply.started":"2021-10-11T23:43:20.685421Z","shell.execute_reply":"2021-10-11T23:43:20.685444Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Submission File","metadata":{}},{"cell_type":"code","source":"result.columns=['BraTS21ID','MGMT_value']\n\nresult2 = result.groupby('BraTS21ID',as_index=False).mean()\nresult2['BraTS21ID'] = sample_submission['BraTS21ID']\n\nresult2","metadata":{"execution":{"iopub.status.busy":"2021-10-11T23:43:20.688418Z","iopub.status.idle":"2021-10-11T23:43:20.689327Z","shell.execute_reply.started":"2021-10-11T23:43:20.689085Z","shell.execute_reply":"2021-10-11T23:43:20.689109Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Rounding... 0.907866 -> 0.9\nresult2['MGMT_value'] = result2['MGMT_value'].apply(lambda x:round(x*10)/10)\n# result2['MGMT_value'] = result2['MGMT_value'] # No rounding\nresult2.to_csv('submission.csv',index=False)\nresult2","metadata":{"execution":{"iopub.status.busy":"2021-10-11T23:43:20.692404Z","iopub.status.idle":"2021-10-11T23:43:20.692903Z","shell.execute_reply.started":"2021-10-11T23:43:20.692659Z","shell.execute_reply":"2021-10-11T23:43:20.692682Z"},"trusted":true},"execution_count":null,"outputs":[]}]}