{"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\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Input, Dense, Dropout, BatchNormalization, Conv2D, MaxPooling2D, AveragePooling2D, concatenate, \\\n    Activation, ZeroPadding2D\nfrom tensorflow.keras.layers import add, Flatten\nfrom tensorflow.keras.utils import plot_model\nfrom tensorflow.keras.metrics import top_k_categorical_accuracy\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.models import load_model\nimport os","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2021-10-15T21:51:27.792206Z","iopub.execute_input":"2021-10-15T21:51:27.792523Z","iopub.status.idle":"2021-10-15T21:51:33.777592Z","shell.execute_reply.started":"2021-10-15T21:51:27.792439Z","shell.execute_reply":"2021-10-15T21:51:33.776973Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\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)]\ndef 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))","metadata":{"execution":{"iopub.status.busy":"2021-10-15T21:51:33.778779Z","iopub.execute_input":"2021-10-15T21:51:33.779099Z","iopub.status.idle":"2021-10-15T21:51:33.815004Z","shell.execute_reply.started":"2021-10-15T21:51:33.779073Z","shell.execute_reply":"2021-10-15T21:51:33.814263Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_all_image_paths(brats21id, image_type, folder='train'): \n    '''\n    Returns an array 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    if num_images > 10:\n        start = int(num_images * 0.25)\n        end = int(num_images * 0.75)\n\n    if num_images < 10: \n        start = int(num_images * 0)\n        end = int(num_images * 1)\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)]\nIMAGE_SIZE = 224\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\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)\n\nX_test, testidt = get_all_data_for_test('T1wCE')\n","metadata":{"execution":{"iopub.status.busy":"2021-10-15T21:51:33.816299Z","iopub.execute_input":"2021-10-15T21:51:33.816661Z","iopub.status.idle":"2021-10-15T21:52:26.916983Z","shell.execute_reply.started":"2021-10-15T21:51:33.816614Z","shell.execute_reply":"2021-10-15T21:52:26.916142Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"file_path = '../input/mri-best-model-2dcnn/best_model.h5'","metadata":{"execution":{"iopub.status.busy":"2021-10-15T21:54:26.332672Z","iopub.execute_input":"2021-10-15T21:54:26.3334Z","iopub.status.idle":"2021-10-15T21:54:26.336808Z","shell.execute_reply.started":"2021-10-15T21:54:26.333355Z","shell.execute_reply":"2021-10-15T21:54:26.336286Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_best = tf.keras.models.load_model(filepath=file_path)","metadata":{"execution":{"iopub.status.busy":"2021-10-15T22:06:49.992407Z","iopub.execute_input":"2021-10-15T22:06:49.992758Z","iopub.status.idle":"2021-10-15T22:06:56.962835Z","shell.execute_reply.started":"2021-10-15T22:06:49.992723Z","shell.execute_reply":"2021-10-15T22:06:56.961869Z"},"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']\n# result2['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-10-15T21:56:11.928256Z","iopub.execute_input":"2021-10-15T21:56:11.92884Z","iopub.status.idle":"2021-10-15T22:06:43.583336Z","shell.execute_reply.started":"2021-10-15T21:56:11.928806Z","shell.execute_reply":"2021-10-15T22:06:43.582213Z"},"trusted":true},"execution_count":null,"outputs":[]}]}