{"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":"# RSNA-MICCAI Brain Tumor Radiogenomic Classification - Exploratory Data Analysis and Modeling\n\n\n### Predict the status of a genetic biomarker important for brain cancer treatment\n\nQuick Exploratory Data Analysis for [RSNA-MICCAI Brain Tumor Radiogenomic Classification](https://www.kaggle.com/c/rsna-miccai-brain-tumor-radiogenomic-classification) challenge    \n\n\n","metadata":{}},{"cell_type":"markdown","source":"The work uses some ideas from next great works:\n- https://www.kaggle.com/avloss/eda-with-animation - animation technique","metadata":{}},{"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","metadata":{"execution":{"iopub.status.busy":"2021-09-08T16:02:17.622641Z","iopub.execute_input":"2021-09-08T16:02:17.623032Z","iopub.status.idle":"2021-09-08T16:02:18.805268Z","shell.execute_reply.started":"2021-09-08T16:02:17.622955Z","shell.execute_reply":"2021-09-08T16:02:18.804498Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**train/** - folder containing the training files, with each top-level folder representing a subject  \n**train_labels.csv** - file containing the target MGMT_value for each subject in the training data (e.g. the presence of MGMT promoter methylation)   \n**test/** - the test files, which use the same structure as train/; your task is to predict the MGMT_value for each subject in the test data. NOTE: the total size of the rerun test set (Public and Private) is ~5x the size of the Public test set   \n**sample_submission.csv** - a sample submission file in the correct format","metadata":{}},{"cell_type":"markdown","source":"<a id=\"2\"></a>\n<h2 style='background:darkviolet; border:0; color:white'><center>Data Visualization<center><h2>","metadata":{"execution":{"iopub.status.busy":"2021-07-14T06:41:32.077425Z","iopub.execute_input":"2021-07-14T06:41:32.077767Z","iopub.status.idle":"2021-07-14T06:41:32.0845Z","shell.execute_reply.started":"2021-07-14T06:41:32.077737Z","shell.execute_reply":"2021-07-14T06:41:32.082683Z"}}},{"cell_type":"code","source":"train_df = pd.read_csv(\"../input/rsna-miccai-brain-tumor-radiogenomic-classification/train_labels.csv\")\ntrain_df","metadata":{"execution":{"iopub.status.busy":"2021-09-08T16:02:18.806585Z","iopub.execute_input":"2021-09-08T16:02:18.806908Z","iopub.status.idle":"2021-09-08T16:02:18.841273Z","shell.execute_reply.started":"2021-09-08T16:02:18.806876Z","shell.execute_reply":"2021-09-08T16:02:18.840387Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(5, 5))\nsns.countplot(data=train_df, x=\"MGMT_value\");","metadata":{"execution":{"iopub.status.busy":"2021-09-08T16:02:18.843045Z","iopub.execute_input":"2021-09-08T16:02:18.843407Z","iopub.status.idle":"2021-09-08T16:02:18.975421Z","shell.execute_reply.started":"2021-09-08T16:02:18.843372Z","shell.execute_reply":"2021-09-08T16:02:18.974554Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def load_dicom(path):\n    dicom = pydicom.read_file(path)\n    data = dicom.pixel_array\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 data\n\n\ndef visualize_sample(\n    brats21id, \n    slice_i,\n    mgmt_value,\n    #types=(\"FLAIR\", \"T1w\", \"T1wCE\", \"T2w\")\n    types=(\"FLAIR\", \"T1wCE\", \"T2w\")\n):\n    plt.figure(figsize=(16, 5))\n    patient_path = os.path.join(\n        \"../input/rsna-miccai-brain-tumor-radiogenomic-classification/train/\", \n        str(brats21id).zfill(5),\n    )\n    for i, t in enumerate(types, 1):\n        t_paths = sorted(\n            glob.glob(os.path.join(patient_path, t, \"*\")), \n            key=lambda x: int(x[:-4].split(\"-\")[-1]),\n        )\n        data = load_dicom(t_paths[int(len(t_paths) * slice_i)])\n        plt.subplot(1, 4, i)\n        plt.imshow(data, cmap=\"gray\")\n        plt.title(f\"{t}\", fontsize=16)\n        plt.axis(\"off\")\n\n    plt.suptitle(f\"MGMT_value: {mgmt_value}\", fontsize=16)\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2021-09-08T16:02:18.977030Z","iopub.execute_input":"2021-09-08T16:02:18.977374Z","iopub.status.idle":"2021-09-08T16:02:18.988196Z","shell.execute_reply.started":"2021-09-08T16:02:18.977338Z","shell.execute_reply":"2021-09-08T16:02:18.987409Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for i in random.sample(range(train_df.shape[0]), 10):\n    _brats21id = train_df.iloc[i][\"BraTS21ID\"]\n    _mgmt_value = train_df.iloc[i][\"MGMT_value\"]\n    visualize_sample(brats21id=_brats21id, mgmt_value=_mgmt_value, slice_i=0.5)","metadata":{"execution":{"iopub.status.busy":"2021-09-08T16:02:18.989412Z","iopub.execute_input":"2021-09-08T16:02:18.989808Z","iopub.status.idle":"2021-09-08T16:02:22.910351Z","shell.execute_reply.started":"2021-09-08T16:02:18.989774Z","shell.execute_reply":"2021-09-08T16:02:22.909602Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from matplotlib import animation, rc\nrc('animation', html='jshtml')\n\n\ndef create_animation(ims):\n    fig = plt.figure(figsize=(6, 6))\n    plt.axis('off')\n    im = plt.imshow(ims[0], cmap=\"gray\")\n\n    def animate_func(i):\n        im.set_array(ims[i])\n        return [im]\n\n    return animation.FuncAnimation(fig, animate_func, frames = len(ims), interval = 1000//24)","metadata":{"execution":{"iopub.status.busy":"2021-09-08T16:02:22.911564Z","iopub.execute_input":"2021-09-08T16:02:22.911897Z","iopub.status.idle":"2021-09-08T16:02:22.917461Z","shell.execute_reply.started":"2021-09-08T16:02:22.911861Z","shell.execute_reply":"2021-09-08T16:02:22.916669Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def load_dicom_line(path):\n    t_paths = sorted(\n        glob.glob(os.path.join(path, \"*\")), \n        key=lambda x: int(x[:-4].split(\"-\")[-1]),\n    )\n    images = []\n    for filename in t_paths:\n        data = load_dicom(filename)\n        if data.max() == 0:\n            continue\n        images.append(data)\n        \n    return images","metadata":{"execution":{"iopub.status.busy":"2021-09-08T16:02:22.918721Z","iopub.execute_input":"2021-09-08T16:02:22.919244Z","iopub.status.idle":"2021-09-08T16:02:22.932240Z","shell.execute_reply.started":"2021-09-08T16:02:22.919200Z","shell.execute_reply":"2021-09-08T16:02:22.931485Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"20\"></a>\n<h2 style='background:darkviolet; border:0; color:white'><center>Sample Submission<center><h2>","metadata":{}},{"cell_type":"code","source":"submission = pd.read_csv(\"../input/rsna-miccai-brain-tumor-radiogenomic-classification/sample_submission.csv\")\n# submission.to_csv(\"submission.csv\", index=False)\nsubmission","metadata":{"execution":{"iopub.status.busy":"2021-09-08T16:02:22.935087Z","iopub.execute_input":"2021-09-08T16:02:22.935480Z","iopub.status.idle":"2021-09-08T16:02:22.956296Z","shell.execute_reply.started":"2021-09-08T16:02:22.935451Z","shell.execute_reply":"2021-09-08T16:02:22.955483Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"100\"></a>\n<h2 style='background:darkviolet; border:0; color:white'><center>Modeling<center><h2>","metadata":{}},{"cell_type":"code","source":"package_path = \"../input/efficientnet-pytorch/EfficientNet-PyTorch/EfficientNet-PyTorch-master/\"\nimport sys \nsys.path.append(package_path)\n\nimport time\n\nimport torch\nfrom torch import nn\nfrom torch.utils import data as torch_data\nfrom sklearn import model_selection as sk_model_selection\nfrom torch.nn import functional as torch_functional\nimport efficientnet_pytorch\n\nfrom sklearn.model_selection import StratifiedKFold","metadata":{"execution":{"iopub.status.busy":"2021-09-08T16:02:22.957916Z","iopub.execute_input":"2021-09-08T16:02:22.958280Z","iopub.status.idle":"2021-09-08T16:02:24.235573Z","shell.execute_reply.started":"2021-09-08T16:02:22.958244Z","shell.execute_reply":"2021-09-08T16:02:24.234762Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def set_seed(seed):\n    random.seed(seed)\n    os.environ[\"PYTHONHASHSEED\"] = str(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    if torch.cuda.is_available():\n        torch.cuda.manual_seed_all(seed)\n        torch.backends.cudnn.deterministic = True\n\n\nset_seed(42)","metadata":{"execution":{"iopub.status.busy":"2021-09-08T16:02:24.238483Z","iopub.execute_input":"2021-09-08T16:02:24.238753Z","iopub.status.idle":"2021-09-08T16:02:24.298443Z","shell.execute_reply.started":"2021-09-08T16:02:24.238727Z","shell.execute_reply":"2021-09-08T16:02:24.297712Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = pd.read_csv(\"../input/rsna-miccai-brain-tumor-radiogenomic-classification/train_labels.csv\")\ndf_train, df_valid = sk_model_selection.train_test_split(\n    df, \n    test_size=0.15, \n    random_state=42, \n    stratify=train_df[\"MGMT_value\"],\n)","metadata":{"execution":{"iopub.status.busy":"2021-09-08T16:02:24.301132Z","iopub.execute_input":"2021-09-08T16:02:24.301388Z","iopub.status.idle":"2021-09-08T16:02:24.312436Z","shell.execute_reply.started":"2021-09-08T16:02:24.301363Z","shell.execute_reply":"2021-09-08T16:02:24.311613Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class DataRetriever(torch_data.Dataset):\n    def __init__(self, paths, targets):\n        self.paths = paths\n        self.targets = targets\n          \n    def __len__(self):\n        return len(self.paths)\n    \n    def __getitem__(self, index):\n        _id = self.paths[index]\n        patient_path = f\"../input/rsna-miccai-brain-tumor-radiogenomic-classification/train/{str(_id).zfill(5)}/\"\n        channels = []\n        #for t in (\"FLAIR\", \"T1w\", \"T1wCE\"): # \"T2w\"\n        # T1w가 이미지가 적은편임.\n        for t in (\"FLAIR\", \"T1wCE\", \"T2w\"): # (32, 2, 257, 257) but expected (32, 3, 3, 3)\n            t_paths = sorted(\n                glob.glob(os.path.join(patient_path, t, \"*\")), \n                key=lambda x: int(x[:-4].split(\"-\")[-1]),\n            )\n            # start, end = int(len(t_paths) * 0.475), int(len(t_paths) * 0.525)\n            x = len(t_paths)\n            #print(\"x : \", x)\n            if x < 10:\n                r = range(x)\n            else:\n                # original\n                #d = x // 5  # 이미지를 sampling해서 average 하는 경우에는 많은 이미지가 들어가면 overfitting 되기 쉽다.\n                #r = range(d, x - d, d)\n                \n                # step sampling approach 눈물...\n                step = x // 10\n                mid = x // 2\n                down = 0.2\n                up = 1.05\n                r = []\n                idx = 0\n                #step = list(range(x, -x, ))\n                #for i in range():\n                while True:\n                    if index <= mid:\n                        step = int(np.ceil(step*down))\n                    else:\n                        step = int(np.ceil(step*up))\n                    if step == 0:\n                        step = 1\n                    idx = idx + step\n                    if idx >= x:\n                        break\n                    r.append(idx)\n                \n                #print(\"range : \", r)\n                #ex = [index for index in r if index > x]\n                #print(\"exception : \", ex)\n                # 25% ~ 75% (IQR)\n                #r = range(int(0.25*x), int(0.75*x))\n                \n                # full-range\n                #r = range(x)\n                \n            channel = []\n            # for i in range(start, end + 1):\n            for i in r:\n                channel.append(cv2.resize(load_dicom(t_paths[i]), (256, 256)) / 255)\n            channel = np.mean(channel, axis=0)\n            channels.append(channel)\n            \n        y = torch.tensor(self.targets[index], dtype=torch.float)\n        \n        return {\"X\": torch.tensor(channels).float(), \"y\": y}","metadata":{"execution":{"iopub.status.busy":"2021-09-08T16:02:24.315671Z","iopub.execute_input":"2021-09-08T16:02:24.315912Z","iopub.status.idle":"2021-09-08T16:02:24.327243Z","shell.execute_reply.started":"2021-09-08T16:02:24.315888Z","shell.execute_reply":"2021-09-08T16:02:24.326247Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data_retriever = DataRetriever(\n    df_train[\"BraTS21ID\"].values, \n    df_train[\"MGMT_value\"].values, \n)\n\nvalid_data_retriever = DataRetriever(\n    df_valid[\"BraTS21ID\"].values, \n    df_valid[\"MGMT_value\"].values,\n)","metadata":{"execution":{"iopub.status.busy":"2021-09-08T16:02:24.328936Z","iopub.execute_input":"2021-09-08T16:02:24.329667Z","iopub.status.idle":"2021-09-08T16:02:24.340363Z","shell.execute_reply.started":"2021-09-08T16:02:24.329627Z","shell.execute_reply":"2021-09-08T16:02:24.339587Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# NOTE : 다 쓰면 오히려 뿌옇게 나온다.\nplt.figure(figsize=(16, 6))\nfor i in range(3):\n    plt.subplot(1, 3, i + 1)\n    plt.imshow(train_data_retriever[100][\"X\"].numpy()[i], cmap=\"gray\")","metadata":{"execution":{"iopub.status.busy":"2021-09-08T16:02:24.341703Z","iopub.execute_input":"2021-09-08T16:02:24.342041Z","iopub.status.idle":"2021-09-08T16:02:38.132646Z","shell.execute_reply.started":"2021-09-08T16:02:24.342008Z","shell.execute_reply":"2021-09-08T16:02:38.131838Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class Model(nn.Module): # change b7 to b0 to b7\n    def __init__(self):\n        super().__init__()\n        self.net = efficientnet_pytorch.EfficientNet.from_name(\"efficientnet-b7\")\n        #self.net = efficientnet_pytorch.EfficientNet.from_name(\"efficientnet-b0\")\n        #checkpoint = torch.load(\"../input/efficientnet-pytorch/efficientnet-b0-08094119.pth\")\n        checkpoint = torch.load(\"../input/efficientnet-pytorch/efficientnet-b7-dcc49843.pth\")\n        self.net.load_state_dict(checkpoint)\n        n_features = self.net._fc.in_features\n        self.net._fc = nn.Linear(in_features=n_features, out_features=1, bias=True)\n    \n    def forward(self, x):\n        out = self.net(x)\n        return out","metadata":{"execution":{"iopub.status.busy":"2021-09-08T16:02:38.133923Z","iopub.execute_input":"2021-09-08T16:02:38.134255Z","iopub.status.idle":"2021-09-08T16:02:38.140468Z","shell.execute_reply.started":"2021-09-08T16:02:38.134219Z","shell.execute_reply":"2021-09-08T16:02:38.139518Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class LossMeter:\n    def __init__(self):\n        self.avg = 0\n        self.n = 0\n\n    def update(self, val):\n        self.n += 1\n        # incremental update\n        self.avg = val / self.n + (self.n - 1) / self.n * self.avg\n\n        \nclass AccMeter:\n    def __init__(self):\n        self.avg = 0\n        self.n = 0\n        \n    def update(self, y_true, y_pred):\n        y_true = y_true.cpu().numpy().astype(int)\n        y_pred = y_pred.cpu().numpy() >= 0\n        last_n = self.n\n        self.n += len(y_true)\n        true_count = np.sum(y_true == y_pred)\n        # incremental update\n        self.avg = true_count / self.n + last_n / self.n * self.avg","metadata":{"execution":{"iopub.status.busy":"2021-09-08T16:02:38.141780Z","iopub.execute_input":"2021-09-08T16:02:38.142118Z","iopub.status.idle":"2021-09-08T16:02:38.152595Z","shell.execute_reply.started":"2021-09-08T16:02:38.142080Z","shell.execute_reply":"2021-09-08T16:02:38.151660Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class Trainer:\n    def __init__(\n        self, \n        model, \n        device, \n        optimizer, \n        criterion, \n        loss_meter, \n        score_meter\n    ):\n        self.model = model\n        self.device = device\n        self.optimizer = optimizer\n        self.criterion = criterion\n        self.loss_meter = loss_meter\n        self.score_meter = score_meter\n        \n        self.best_valid_score = -np.inf\n        self.n_patience = 0\n        \n        self.messages = {\n            \"epoch\": \"[Epoch {}: {}] loss: {:.5f}, score: {:.5f}, time: {} s\",\n            \"checkpoint\": \"The score improved from {:.5f} to {:.5f}. Save model to '{}'\",\n            \"patience\": \"\\nValid score didn't improve last {} epochs.\"\n        }\n    \n    def fit(self, epochs, train_loader, valid_loader, save_path, patience):        \n        for n_epoch in range(1, epochs + 1):\n            self.info_message(\"EPOCH: {}\", n_epoch)\n            \n            train_loss, train_score, train_time = self.train_epoch(train_loader)\n            valid_loss, valid_score, valid_time = self.valid_epoch(valid_loader)\n            \n            self.info_message(\n                self.messages[\"epoch\"], \"Train\", n_epoch, train_loss, train_score, train_time\n            )\n            \n            self.info_message(\n                self.messages[\"epoch\"], \"Valid\", n_epoch, valid_loss, valid_score, valid_time\n            )\n\n            if True:\n#             if self.best_valid_score < valid_score:\n                self.info_message(\n                    self.messages[\"checkpoint\"], self.best_valid_score, valid_score, save_path\n                )\n                self.best_valid_score = valid_score\n                self.save_model(n_epoch, save_path)\n                self.n_patience = 0\n            else:\n                self.n_patience += 1\n            \n            if self.n_patience >= patience:\n                self.info_message(self.messages[\"patience\"], patience)\n                break\n            \n    def train_epoch(self, train_loader):\n        self.model.train()\n        t = time.time()\n        train_loss = self.loss_meter()\n        train_score = self.score_meter()\n        \n        for step, batch in enumerate(train_loader, 1):\n            X = batch[\"X\"].to(self.device)\n            targets = batch[\"y\"].to(self.device)\n            self.optimizer.zero_grad()\n            outputs = self.model(X).squeeze(1)\n            \n            loss = self.criterion(outputs, targets)\n            loss.backward()\n\n            train_loss.update(loss.detach().item())\n            train_score.update(targets, outputs.detach())\n\n            self.optimizer.step()\n            \n            _loss, _score = train_loss.avg, train_score.avg\n            message = 'Train Step {}/{}, train_loss: {:.5f}, train_score: {:.5f}'\n            self.info_message(message, step, len(train_loader), _loss, _score, end=\"\\r\")\n        \n        return train_loss.avg, train_score.avg, int(time.time() - t)\n    \n    def valid_epoch(self, valid_loader):\n        self.model.eval()\n        t = time.time()\n        valid_loss = self.loss_meter()\n        valid_score = self.score_meter()\n\n        for step, batch in enumerate(valid_loader, 1):\n            with torch.no_grad():\n                X = batch[\"X\"].to(self.device)\n                targets = batch[\"y\"].to(self.device)\n\n                outputs = self.model(X).squeeze(1)\n                loss = self.criterion(outputs, targets)\n\n                valid_loss.update(loss.detach().item())\n                valid_score.update(targets, outputs)\n                \n            _loss, _score = valid_loss.avg, valid_score.avg\n            message = 'Valid Step {}/{}, valid_loss: {:.5f}, valid_score: {:.5f}'\n            self.info_message(message, step, len(valid_loader), _loss, _score, end=\"\\r\")\n        \n        return valid_loss.avg, valid_score.avg, int(time.time() - t)\n    \n    def save_model(self, n_epoch, save_path):\n        torch.save(\n            {\n                \"model_state_dict\": self.model.state_dict(),\n                \"optimizer_state_dict\": self.optimizer.state_dict(),\n                \"best_valid_score\": self.best_valid_score,\n                \"n_epoch\": n_epoch,\n            },\n            save_path,\n        )\n    \n    @staticmethod\n    def info_message(message, *args, end=\"\\n\"):\n        print(message.format(*args), end=end)","metadata":{"execution":{"iopub.status.busy":"2021-09-08T16:02:38.153770Z","iopub.execute_input":"2021-09-08T16:02:38.154121Z","iopub.status.idle":"2021-09-08T16:02:38.175733Z","shell.execute_reply.started":"2021-09-08T16:02:38.154084Z","shell.execute_reply":"2021-09-08T16:02:38.174790Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nbatch_size = 8 # change 8 to 16 to 32 to 64\n\ntrain_data_retriever = DataRetriever(\n    df_train[\"BraTS21ID\"].values, \n    df_train[\"MGMT_value\"].values, \n)\n\nvalid_data_retriever = DataRetriever(\n    df_valid[\"BraTS21ID\"].values, \n    df_valid[\"MGMT_value\"].values,\n)\n\ntrain_loader = torch_data.DataLoader(\n    train_data_retriever,\n    batch_size=batch_size, \n    shuffle=True,\n    num_workers=8,\n)\n\nvalid_loader = torch_data.DataLoader(\n    valid_data_retriever, \n    batch_size=batch_size, \n    shuffle=False,\n    num_workers=8,\n)\n\nmodel = Model()\nmodel.to(device)\n\noptimizer = torch.optim.Adam(model.parameters(), lr=3e-4)\ncriterion = torch_functional.binary_cross_entropy_with_logits\n\ntrainer = Trainer(\n    model, \n    device, \n    optimizer, \n    criterion, \n    LossMeter, \n    AccMeter\n)\n\nhistory = trainer.fit(\n    15, # epoch 8을 넘어가는 순간부터 overfitting 됨. # batch_size가 커져도 overfitting됨.\n    train_loader, \n    valid_loader, \n    f\"best-model-0.pth\",\n    100,\n)","metadata":{"execution":{"iopub.status.busy":"2021-09-08T16:02:38.176934Z","iopub.execute_input":"2021-09-08T16:02:38.177348Z","iopub.status.idle":"2021-09-08T17:01:00.052095Z","shell.execute_reply.started":"2021-09-08T16:02:38.177314Z","shell.execute_reply":"2021-09-08T17:01:00.051115Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"models = []\nfor i in range(1):\n    model = Model()\n    model.to(device)\n    \n    checkpoint = torch.load(f\"best-model-{i}.pth\")\n    model.load_state_dict(checkpoint[\"model_state_dict\"])\n    model.eval()\n    \n    models.append(model)","metadata":{"execution":{"iopub.status.busy":"2021-09-08T13:49:27.797203Z","iopub.execute_input":"2021-09-08T13:49:27.797878Z","iopub.status.idle":"2021-09-08T13:49:28.386305Z","shell.execute_reply.started":"2021-09-08T13:49:27.797826Z","shell.execute_reply":"2021-09-08T13:49:28.384969Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class DataRetriever(torch_data.Dataset):\n    def __init__(self, paths):\n        self.paths = paths\n          \n    def __len__(self):\n        return len(self.paths)\n    \n    def __getitem__(self, index):\n        _id = self.paths[index]\n        patient_path = f\"../input/rsna-miccai-brain-tumor-radiogenomic-classification/test/{str(_id).zfill(5)}/\"\n        channels = []\n        #for t in (\"FLAIR\", \"T1w\", \"T1wCE\"): # \"T2w\"\n        for t in (\"FLAIR\", \"T1wCE\", \"T2w\"):\n            t_paths = sorted(\n                glob.glob(os.path.join(patient_path, t, \"*\")), \n                key=lambda x: int(x[:-4].split(\"-\")[-1]),\n            )\n            # start, end = int(len(t_paths) * 0.475), int(len(t_paths) * 0.525)\n            x = len(t_paths)\n            if x < 10:\n                r = range(x)\n            else:\n                d = x // 5\n                r = range(d, x - d, d)\n                \n            channel = []\n            # for i in range(start, end + 1):\n            for i in r:\n                channel.append(cv2.resize(load_dicom(t_paths[i]), (256, 256)) / 255)\n            channel = np.mean(channel, axis=0)\n            channels.append(channel)\n        \n        return {\"X\": torch.tensor(channels).float(), \"id\": _id}","metadata":{"execution":{"iopub.status.busy":"2021-09-08T13:49:28.391334Z","iopub.execute_input":"2021-09-08T13:49:28.391655Z","iopub.status.idle":"2021-09-08T13:49:28.403808Z","shell.execute_reply.started":"2021-09-08T13:49:28.391623Z","shell.execute_reply":"2021-09-08T13:49:28.402104Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission = pd.read_csv(\"../input/rsna-miccai-brain-tumor-radiogenomic-classification/sample_submission.csv\")\n\ntest_data_retriever = DataRetriever(\n    submission[\"BraTS21ID\"].values, \n)\n\ntest_loader = torch_data.DataLoader(\n    test_data_retriever,\n    batch_size=batch_size,\n    shuffle=False,\n    num_workers=8,\n)","metadata":{"execution":{"iopub.status.busy":"2021-09-08T13:49:28.406255Z","iopub.execute_input":"2021-09-08T13:49:28.406810Z","iopub.status.idle":"2021-09-08T13:49:28.428862Z","shell.execute_reply.started":"2021-09-08T13:49:28.406764Z","shell.execute_reply":"2021-09-08T13:49:28.427526Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_pred = []\nids = []\n\nfor e, batch in enumerate(test_loader):\n    print(f\"{e}/{len(test_loader)}\", end=\"\\r\")\n    with torch.no_grad():\n        tmp_pred = np.zeros((batch[\"X\"].shape[0], ))\n        for model in models:\n            tmp_res = torch.sigmoid(model(batch[\"X\"].to(device))).cpu().numpy().squeeze()\n            tmp_pred += tmp_res\n        y_pred.extend(tmp_pred)\n        ids.extend(batch[\"id\"].numpy().tolist())","metadata":{"execution":{"iopub.status.busy":"2021-09-08T13:49:28.430373Z","iopub.execute_input":"2021-09-08T13:49:28.430841Z","iopub.status.idle":"2021-09-08T13:49:36.487939Z","shell.execute_reply.started":"2021-09-08T13:49:28.430796Z","shell.execute_reply":"2021-09-08T13:49:36.486778Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission = pd.DataFrame({\"BraTS21ID\": ids, \"MGMT_value\": y_pred})\nsubmission.to_csv(\"submission.csv\", index=False)","metadata":{"execution":{"iopub.status.busy":"2021-09-08T13:49:36.492003Z","iopub.execute_input":"2021-09-08T13:49:36.492388Z","iopub.status.idle":"2021-09-08T13:49:36.502246Z","shell.execute_reply.started":"2021-09-08T13:49:36.492355Z","shell.execute_reply":"2021-09-08T13:49:36.500855Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(5, 5))\nplt.hist(submission[\"MGMT_value\"]);","metadata":{"execution":{"iopub.status.busy":"2021-09-08T13:49:36.504382Z","iopub.execute_input":"2021-09-08T13:49:36.504980Z","iopub.status.idle":"2021-09-08T13:49:36.717977Z","shell.execute_reply.started":"2021-09-08T13:49:36.504935Z","shell.execute_reply":"2021-09-08T13:49:36.716838Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission","metadata":{"execution":{"iopub.status.busy":"2021-09-08T13:49:36.720004Z","iopub.execute_input":"2021-09-08T13:49:36.720450Z","iopub.status.idle":"2021-09-08T13:49:36.738156Z","shell.execute_reply.started":"2021-09-08T13:49:36.720404Z","shell.execute_reply":"2021-09-08T13:49:36.736409Z"},"trusted":true},"execution_count":null,"outputs":[]}]}