{"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":"code","source":"import os\nimport json\nimport glob\nimport random\nimport collections\n\nimport numpy as np\nimport pandas as pd\nimport pydicom\nfrom pydicom.pixel_data_handlers.util import apply_voi_lut\nimport cv2\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport random\nfrom tqdm.notebook import tqdm\n\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras import layers\n\n\n\nTYPES = [\"FLAIR\", \"T1w\", \"T2w\", \"T1wCE\"]\nWHITE_THRESHOLD = 10 # out of 255\nEXCLUDE = [109, 123, 709]\n\n\ntrain_df = pd.read_csv(\"../input/rsna-miccai-brain-tumor-radiogenomic-classification/train_labels.csv\")\ntest_df = pd.read_csv('../input/rsna-miccai-brain-tumor-radiogenomic-classification/sample_submission.csv')\ntrain_df = train_df[~train_df.BraTS21ID.isin(EXCLUDE)]","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2021-09-03T12:06:21.542769Z","iopub.execute_input":"2021-09-03T12:06:21.543175Z","iopub.status.idle":"2021-09-03T12:06:28.469003Z","shell.execute_reply.started":"2021-09-03T12:06:21.543138Z","shell.execute_reply":"2021-09-03T12:06:28.467826Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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    Note 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    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 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","metadata":{"execution":{"iopub.status.busy":"2021-09-03T12:06:32.464707Z","iopub.execute_input":"2021-09-03T12:06:32.465108Z","iopub.status.idle":"2021-09-03T12:06:32.477596Z","shell.execute_reply.started":"2021-09-03T12:06:32.465047Z","shell.execute_reply":"2021-09-03T12:06:32.475826Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMAGE_SIZE = 128\n\ndef get_all_data_for_train(image_type):\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):\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-09-03T12:06:36.451441Z","iopub.execute_input":"2021-09-03T12:06:36.451811Z","iopub.status.idle":"2021-09-03T12:06:36.46164Z","shell.execute_reply.started":"2021-09-03T12:06:36.451779Z","shell.execute_reply":"2021-09-03T12:06:36.460404Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X, y, trainidt = get_all_data_for_train('T1wCE')\nX_test, testidt = get_all_data_for_test('T1wCE')\nX.shape, y.shape, trainidt.shape","metadata":{"execution":{"iopub.status.busy":"2021-09-03T12:06:39.57787Z","iopub.execute_input":"2021-09-03T12:06:39.57829Z","iopub.status.idle":"2021-09-03T12:09:51.736413Z","shell.execute_reply.started":"2021-09-03T12:06:39.578256Z","shell.execute_reply":"2021-09-03T12:09:51.735067Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X.shape, y.shape","metadata":{"execution":{"iopub.status.busy":"2021-09-03T12:09:53.891719Z","iopub.execute_input":"2021-09-03T12:09:53.892127Z","iopub.status.idle":"2021-09-03T12:09:53.899786Z","shell.execute_reply.started":"2021-09-03T12:09:53.892069Z","shell.execute_reply":"2021-09-03T12:09:53.898398Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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.1, random_state=40)\n\nsplit = int(X.shape[0] * 0.9)\n\n# X_train = X[:split]\n# X_valid = X[split:]\n\n# y_train = y[:split]\n# y_valid = y[split:]\n\n# trainidt_train = trainidt[:split]\n# trainidt_valid = trainidt[split:]\n\nX_train = tf.expand_dims(X_train, axis=-1)\nX_valid = tf.expand_dims(X_valid, axis=-1)\n\ny_train = to_categorical(y_train)\ny_valid = to_categorical(y_valid)\n\nX_train.shape, y_train.shape, X_valid.shape, y_valid.shape, trainidt_train.shape, trainidt_valid.shape","metadata":{"execution":{"iopub.status.busy":"2021-09-03T12:09:55.780338Z","iopub.execute_input":"2021-09-03T12:09:55.780737Z","iopub.status.idle":"2021-09-03T12:09:58.605301Z","shell.execute_reply.started":"2021-09-03T12:09:55.780704Z","shell.execute_reply":"2021-09-03T12:09:58.6042Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\n","metadata":{"execution":{"iopub.status.busy":"2021-09-03T12:10:03.758601Z","iopub.execute_input":"2021-09-03T12:10:03.758968Z","iopub.status.idle":"2021-09-03T12:10:03.763882Z","shell.execute_reply.started":"2021-09-03T12:10:03.758936Z","shell.execute_reply":"2021-09-03T12:10:03.76264Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"global_average_layer = tf.keras.layers.GlobalAveragePooling2D()","metadata":{"execution":{"iopub.status.busy":"2021-09-03T12:10:07.988837Z","iopub.execute_input":"2021-09-03T12:10:07.989269Z","iopub.status.idle":"2021-09-03T12:10:08.003117Z","shell.execute_reply.started":"2021-09-03T12:10:07.98923Z","shell.execute_reply":"2021-09-03T12:10:08.00185Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_augmentation = tf.keras.Sequential([\n  tf.keras.layers.experimental.preprocessing.RandomFlip('horizontal'),\n  tf.keras.layers.experimental.preprocessing.RandomRotation(0.2),\n])","metadata":{"execution":{"iopub.status.busy":"2021-09-03T12:10:09.601759Z","iopub.execute_input":"2021-09-03T12:10:09.602153Z","iopub.status.idle":"2021-09-03T12:10:09.63381Z","shell.execute_reply.started":"2021-09-03T12:10:09.602108Z","shell.execute_reply":"2021-09-03T12:10:09.632749Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow_hub as tfhub\nimport tensorflow_addons as tfa","metadata":{"execution":{"iopub.status.busy":"2021-09-03T12:10:11.688068Z","iopub.execute_input":"2021-09-03T12:10:11.688486Z","iopub.status.idle":"2021-09-03T12:10:12.20633Z","shell.execute_reply.started":"2021-09-03T12:10:11.688452Z","shell.execute_reply":"2021-09-03T12:10:12.205217Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"np.random.seed(0)\nrandom.seed(12)\ntf.random.set_seed(12)\n\ninpt = keras.Input(shape=X_train.shape[1:])\ninp = tf.keras.layers.Concatenate()([inpt, inpt, inpt])  \n\nh = keras.layers.experimental.preprocessing.Rescaling(1./255)(inp)\n# h = data_augmentation(h)\n\n# convolutional layer!\n# h = keras.layers.Conv2D(3, kernel_size=(3, 3),activation=\"relu\", name=\"Conv_1\", padding=\"same\")(h) \n# h = tf.keras.layers.BatchNormalization(axis=-1)(h)\nh = tfhub.KerasLayer('../input/efficientnetv2-tfhub-weight-files/tfhub_models/efficientnetv2-m-21k/feature_vector', trainable=True)(h)\n\n# h = keras.layers.Flatten()(h) \n# h = global_average_layer(h)\nh = keras.layers.Dropout(0.4)(h)\nh = keras.layers.Dense(128, activation='relu')(h)   \n\noutput = keras.layers.Dense(2, activation=\"softmax\")(h)\n\nmodel = keras.Model(inpt, output)\n\nfrom keras.optimizers import SGD\n# opt = SGD(lr=0.1)\n\ncheckpoint_filepath = 'best_model.h5'\nmodel_checkpoint_callback = tf.keras.callbacks.ModelCheckpoint(\nfilepath=checkpoint_filepath,\nsave_weights_only=False,\nmonitor='val_loss',\nmode='max',\nsave_best_only=True,\nsave_freq='epoch')\nreduce_lr = tf.keras.callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.5,\n                              patience=2, min_lr=0.00001)\n# lr_schedule = tf.optimizers.schedules.ExponentialDecay(1e-4, 100, 0.9)\n# wd_schedule = tf.optimizers.schedules.ExponentialDecay(5e-5, 100, 0.9)\n# opt = tfa.optimizers.AdamW(learning_rate=lr_schedule, weight_decay=lambda : None)\n# opt.weight_decay = lambda : wd_schedule(opt.iterations)\n\n\nmodel.compile(loss='categorical_crossentropy',\n             optimizer=tf.keras.optimizers.Adam(learning_rate = 0.0001),\n             metrics=[tf.keras.metrics.AUC()])\n\nhistory = model.fit(x=X_train, y = y_train, epochs=10, callbacks=[model_checkpoint_callback,reduce_lr], validation_data= (X_valid, y_valid))","metadata":{"execution":{"iopub.status.busy":"2021-09-03T12:10:21.803578Z","iopub.execute_input":"2021-09-03T12:10:21.803977Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_best = tf.keras.models.load_model(filepath=checkpoint_filepath,custom_objects={'KerasLayer': tfhub.KerasLayer})","metadata":{"execution":{"iopub.status.busy":"2021-09-03T09:07:49.572394Z","iopub.execute_input":"2021-09-03T09:07:49.57273Z","iopub.status.idle":"2021-09-03T09:08:10.152032Z","shell.execute_reply.started":"2021-09-03T09:07:49.572699Z","shell.execute_reply":"2021-09-03T09:08:10.151157Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_pred = model_best.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()\n\nresult2 = result2.merge(train_df, on='BraTS21ID')\nroc_auc_score(result2.MGMT_value_y, result2.MGMT_value_x,)","metadata":{"execution":{"iopub.status.busy":"2021-09-03T09:08:22.255389Z","iopub.execute_input":"2021-09-03T09:08:22.255715Z","iopub.status.idle":"2021-09-03T09:08:30.457411Z","shell.execute_reply.started":"2021-09-03T09:08:22.255684Z","shell.execute_reply":"2021-09-03T09:08:30.456214Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"len(result2)","metadata":{"execution":{"iopub.status.busy":"2021-09-03T08:49:09.703775Z","iopub.execute_input":"2021-09-03T08:49:09.704121Z","iopub.status.idle":"2021-09-03T08:49:09.712673Z","shell.execute_reply.started":"2021-09-03T08:49:09.704089Z","shell.execute_reply":"2021-09-03T08:49:09.711821Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample = pd.read_csv('../input/rsna-miccai-brain-tumor-radiogenomic-classification/sample_submission.csv')\n\ny_pred = model_best.predict(X_test)\n\npred = np.argmax(y_pred, axis=1)\n\nresult=pd.DataFrame(testidt)\nresult[1]=pred\n\nresult.columns=['BraTS21ID','MGMT_value']\nresult2 = result.groupby('BraTS21ID',as_index=False).mean()\nresult2['BraTS21ID'] = sample['BraTS21ID']\nresult2['MGMT_value'] = result2['MGMT_value'].apply(lambda x:round(x*10)/10)\nresult2.to_csv('submission.csv',index=False)\nresult2","metadata":{"execution":{"iopub.status.busy":"2021-09-03T08:49:11.699684Z","iopub.execute_input":"2021-09-03T08:49:11.70004Z","iopub.status.idle":"2021-09-03T08:49:18.627522Z","shell.execute_reply.started":"2021-09-03T08:49:11.70001Z","shell.execute_reply":"2021-09-03T08:49:18.62659Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}