{"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":"## EDA with Animations and Modeling for getting started\n\n### Tips:\n#### only use \"FLAIR\" and \"T1w\" data get better score than use 4 types(0.617 vs 0.428?)\n#### maybe 4 types data contain more information,so the model needs more epochs to train?\n\nby the way,this notebook is really helpful https://www.kaggle.com/ihelon/brain-tumor-eda-with-animations-and-modeling","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-08-03T11:29:23.499555Z","iopub.execute_input":"2021-08-03T11:29:23.499922Z","iopub.status.idle":"2021-08-03T11:29:24.669117Z","shell.execute_reply.started":"2021-08-03T11:29:23.499845Z","shell.execute_reply":"2021-08-03T11:29:24.668282Z"},"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":"code","source":"# to see the train\ntrain_df = pd.read_csv(\"../input/rsna-miccai-brain-tumor-radiogenomic-classification/train_labels.csv\")\ntrain_df","metadata":{"execution":{"iopub.status.busy":"2021-08-03T11:29:24.670666Z","iopub.execute_input":"2021-08-03T11:29:24.671147Z","iopub.status.idle":"2021-08-03T11:29:24.704997Z","shell.execute_reply.started":"2021-08-03T11:29:24.671110Z","shell.execute_reply":"2021-08-03T11:29:24.704074Z"},"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-08-03T11:29:24.706792Z","iopub.execute_input":"2021-08-03T11:29:24.707141Z","iopub.status.idle":"2021-08-03T11:29:24.836549Z","shell.execute_reply.started":"2021-08-03T11:29:24.707106Z","shell.execute_reply":"2021-08-03T11:29:24.835649Z"},"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):\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),#读取train目录下的文件夹路径\n    )\n    for i, t in enumerate(types, 1):#start=1 意味着索引从1开始\n        t_paths = sorted(\n            glob.glob(os.path.join(patient_path, t, \"*\")), #'*'表示匹配任意字符串\n            key=lambda x: int(x[:-4].split(\"-\")[-1]),#通过dcm文件名排序\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} BraTS21ID: {brats21id}\", fontsize=16)\n    plt.show()\n\ndef mul_samples(\n    brats21id, \n    slice_i,\n    mgmt_value,\n    types=(\"FLAIR\", \"T1w\", \"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),#读取train目录下的文件夹路径\n    )\n    t_paths1 = sorted(\n            glob.glob(os.path.join(patient_path, \"FLAIR\", \"*\")), #'*'表示匹配任意字符串\n            key=lambda x: int(x[:-4].split(\"-\")[-1]),#通过dcm文件名排序\n        )\n    t_paths2 = sorted(\n            glob.glob(os.path.join(patient_path, \"T1w\", \"*\")), #'*'表示匹配任意字符串\n            key=lambda x: int(x[:-4].split(\"-\")[-1]),#通过dcm文件名排序\n        )\n    data1 = cv2.resize(load_dicom(t_paths1[int(len(t_paths1) * slice_i)]),(256,256))/255\n    data2 = cv2.resize(load_dicom(t_paths2[int(len(t_paths2) * slice_i)]),(256,256))/255\n    print(data1.max())\n    print(data1.min())\n    data = data1 * data2\n    plt.imshow(data, cmap=\"gray\")\n    plt.show()\n\n","metadata":{"execution":{"iopub.status.busy":"2021-08-03T11:29:24.838312Z","iopub.execute_input":"2021-08-03T11:29:24.838662Z","iopub.status.idle":"2021-08-03T11:29:24.852818Z","shell.execute_reply.started":"2021-08-03T11:29:24.838626Z","shell.execute_reply":"2021-08-03T11:29:24.851834Z"},"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.3)\nmul_samples(brats21id=_brats21id, mgmt_value=_mgmt_value, slice_i=0.3)","metadata":{"execution":{"iopub.status.busy":"2021-08-03T11:29:24.854283Z","iopub.execute_input":"2021-08-03T11:29:24.854632Z","iopub.status.idle":"2021-08-03T11:29:28.902108Z","shell.execute_reply.started":"2021-08-03T11:29:24.854584Z","shell.execute_reply":"2021-08-03T11:29:28.901301Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Submissions are evaluated on [area under the ROC curve](https://en.wikipedia.org/wiki/Receiver_operating_characteristic) between the predicted probability and the observed target.","metadata":{}},{"cell_type":"code","source":"from sklearn.metrics import roc_auc_score, roc_curve, auc\n\nlist_y_true = [\n    [1., 1., 1., 1., 1., 1., 0., 0., 0., 0., 0., 0.],\n    [1., 1., 1., 1., 1., 1., 0., 0., 0., 0., 0., 0.],\n    [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 0.], #  IMBALANCE\n]\nlist_y_pred = [\n    [0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5],\n    [0.9, 0.9, 0.9, 0.9, 0.1, 0.9, 0.9, 0.1, 0.9, 0.1, 0.1, 0.5],\n    [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], #  IMBALANCE\n]\n\nfor y_true, y_pred in zip(list_y_true, list_y_pred):\n    fpr, tpr, _ = roc_curve(y_true, y_pred)\n    roc_auc = auc(fpr, tpr)\n\n    plt.figure(figsize=(5, 5))\n    plt.plot(fpr, tpr, color='darkorange', lw=2, label='ROC curve (area = %0.2f)' % roc_auc)\n    plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')\n    plt.xlim([-0.01, 1.0])\n    plt.ylim([0.0, 1.05])\n    plt.xlabel('False Positive Rate')\n    plt.ylabel('True Positive Rate')\n    plt.title('Receiver operating characteristic example')\n    plt.legend(loc=\"lower right\")\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2021-08-03T11:29:28.903471Z","iopub.execute_input":"2021-08-03T11:29:28.903958Z","iopub.status.idle":"2021-08-03T11:29:29.467621Z","shell.execute_reply.started":"2021-08-03T11:29:28.903920Z","shell.execute_reply":"2021-08-03T11:29:29.466848Z"},"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# submission.to_csv(\"submission.csv\", index=False)\nsubmission","metadata":{"execution":{"iopub.status.busy":"2021-08-03T11:29:29.468935Z","iopub.execute_input":"2021-08-03T11:29:29.469267Z","iopub.status.idle":"2021-08-03T11:29:29.488221Z","shell.execute_reply.started":"2021-08-03T11:29:29.469232Z","shell.execute_reply":"2021-08-03T11:29:29.487503Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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.data import Dataset,DataLoader\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-08-03T11:29:29.491013Z","iopub.execute_input":"2021-08-03T11:29:29.491330Z","iopub.status.idle":"2021-08-03T11:29:30.751696Z","shell.execute_reply.started":"2021-08-03T11:29:29.491304Z","shell.execute_reply":"2021-08-03T11:29:30.750824Z"},"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.2, \n    random_state=42, \n    stratify=train_df[\"MGMT_value\"],\n)","metadata":{"execution":{"iopub.status.busy":"2021-08-03T11:29:30.753593Z","iopub.execute_input":"2021-08-03T11:29:30.753975Z","iopub.status.idle":"2021-08-03T11:29:30.765150Z","shell.execute_reply.started":"2021-08-03T11:29:30.753939Z","shell.execute_reply":"2021-08-03T11:29:30.764372Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class DataRetriever(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        targets = []\n        for t in (\"FLAIR\", \"T1w\", \"T1wCE\",\"T2w\"): # \"FLAIR\", \"T1w\", \"T1wCE\",\"T2w\"\n#         for t in (\"FLAIR\", \"T1w\"): # \"FLAIR\", \"T1w\", \"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\n            x = len(t_paths)\n            if x < 10:\n                r = range(x)\n            else:\n                r = range(0,x,x//10)#for single person choose 10 pics.\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        for i in range(3):\n            channel_t = channels[i] * channels[i+1]\n            channels.append(channel_t)\n            \n        y = torch.tensor(self.targets[index], dtype=torch.float)\n        \n        return {\"X\": torch.tensor(channels).float(), \"y\": y}\n\n","metadata":{"execution":{"iopub.status.busy":"2021-08-03T11:29:30.766879Z","iopub.execute_input":"2021-08-03T11:29:30.767238Z","iopub.status.idle":"2021-08-03T11:29:30.777270Z","shell.execute_reply.started":"2021-08-03T11:29:30.767195Z","shell.execute_reply":"2021-08-03T11:29:30.776191Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"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-08-03T11:29:30.778726Z","iopub.execute_input":"2021-08-03T11:29:30.779172Z","iopub.status.idle":"2021-08-03T11:29:30.789523Z","shell.execute_reply.started":"2021-08-03T11:29:30.779136Z","shell.execute_reply":"2021-08-03T11:29:30.788794Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# plt.figure(figsize=(16, 6))\n# for i in range(2):\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-08-03T11:29:30.790838Z","iopub.execute_input":"2021-08-03T11:29:30.791179Z","iopub.status.idle":"2021-08-03T11:29:30.798122Z","shell.execute_reply.started":"2021-08-03T11:29:30.791143Z","shell.execute_reply":"2021-08-03T11:29:30.797164Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data_retriever[100][\"X\"].shape#使用了三通道数据","metadata":{"execution":{"iopub.status.busy":"2021-08-03T11:29:30.799383Z","iopub.execute_input":"2021-08-03T11:29:30.799770Z","iopub.status.idle":"2021-08-03T11:29:31.277580Z","shell.execute_reply.started":"2021-08-03T11:29:30.799728Z","shell.execute_reply":"2021-08-03T11:29:31.276816Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class Model(nn.Module):#efficientnet-pytorch\n    def __init__(self):\n        super().__init__()\n        self.conv1 = torch.nn.Conv2d(7,56,kernel_size=3,padding=1,stride=1)\n        self.conv2 = torch.nn.Conv2d(56,3,kernel_size=3,padding=1,stride=1)\n        self.net = efficientnet_pytorch.EfficientNet.from_name(\"efficientnet-b4\")\n        checkpoint = torch.load(\"../input/efficientnet-pytorch/efficientnet-b4-e116e8b3.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.conv1(x)\n        out = self.conv2(out)\n        out = self.net(out)\n        return out","metadata":{"execution":{"iopub.status.busy":"2021-08-03T11:30:20.845097Z","iopub.execute_input":"2021-08-03T11:30:20.845433Z","iopub.status.idle":"2021-08-03T11:30:20.853489Z","shell.execute_reply.started":"2021-08-03T11:30:20.845401Z","shell.execute_reply":"2021-08-03T11:30:20.852691Z"},"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-08-03T11:29:31.292035Z","iopub.execute_input":"2021-08-03T11:29:31.292351Z","iopub.status.idle":"2021-08-03T11:29:31.301946Z","shell.execute_reply.started":"2021-08-03T11:29:31.292325Z","shell.execute_reply":"2021-08-03T11:29:31.300976Z"},"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 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-08-03T11:29:31.303244Z","iopub.execute_input":"2021-08-03T11:29:31.303558Z","iopub.status.idle":"2021-08-03T11:29:31.323719Z","shell.execute_reply.started":"2021-08-03T11:29:31.303533Z","shell.execute_reply":"2021-08-03T11:29:31.322705Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\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 = DataLoader(\n    train_data_retriever,\n    batch_size=8,\n    shuffle=True,\n    num_workers=8,\n)\n\nvalid_loader = DataLoader(\n    valid_data_retriever, \n    batch_size=8,\n    shuffle=False,\n    num_workers=8,\n)\n\nmodel = Model()\n# if os.path.exist('./best-model-1.pth'):\n#     model = torch.load('./best-model-1.pth')\n\nmodel.to(device)\n\noptimizer = torch.optim.Adadelta(model.parameters(), lr=0.001)\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    50, \n    train_loader, \n    valid_loader, \n    f\"best-model-1.pth\", \n    100,\n)\n","metadata":{"execution":{"iopub.status.busy":"2021-08-03T11:30:27.026044Z","iopub.execute_input":"2021-08-03T11:30:27.026361Z","iopub.status.idle":"2021-08-03T11:30:52.202776Z","shell.execute_reply.started":"2021-08-03T11:30:27.026330Z","shell.execute_reply":"2021-08-03T11:30:52.200488Z"},"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+1}.pth\")\n    model.load_state_dict(checkpoint[\"model_state_dict\"])\n    model.eval()\n    \n    models.append(model)","metadata":{"execution":{"iopub.status.busy":"2021-08-03T11:29:54.170767Z","iopub.status.idle":"2021-08-03T11:29:54.171343Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"len(models)","metadata":{"execution":{"iopub.status.busy":"2021-08-03T11:29:54.172655Z","iopub.status.idle":"2021-08-03T11:29:54.173213Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# original test data load function\nclass DataRetriever(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'): # \"FLAIR\", \"T1w\", \"T1wCE\",\"T2w\"\n        for t in (\"FLAIR\", \"T1w\", \"T1wCE\",\"T2w\"): # \"FLAIR\", \"T1w\", \"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            \n            x = len(t_paths)\n            if x < 10:\n                r = range(x)\n            else:\n                r = range(0,x,x//10)#for single person choose 10 pics.\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        for i in range(3):\n            channel_t = channels[i] * channels[i+1]\n            channels.append(channel_t)\n        \n        return {\"X\": torch.tensor(channels).float(), \"id\": _id}","metadata":{"execution":{"iopub.status.busy":"2021-08-03T11:29:54.174508Z","iopub.status.idle":"2021-08-03T11:29:54.175071Z"},"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 = DataLoader(\n    test_data_retriever,\n    batch_size=4,\n    shuffle=False,\n    num_workers=8,\n)","metadata":{"execution":{"iopub.status.busy":"2021-08-03T11:29:54.176519Z","iopub.status.idle":"2021-08-03T11:29:54.177082Z"},"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        tmp_pred = torch.sigmoid(model(batch[\"X\"].to(device))).cpu().numpy().squeeze()\n        y_pred.extend(tmp_pred)\n        ids.extend(batch[\"id\"].numpy().tolist())","metadata":{"execution":{"iopub.status.busy":"2021-08-03T11:29:54.178542Z","iopub.status.idle":"2021-08-03T11:29:54.179117Z"},"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-08-03T11:29:54.180516Z","iopub.status.idle":"2021-08-03T11:29:54.181085Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission","metadata":{"execution":{"iopub.status.busy":"2021-08-03T11:29:54.182482Z","iopub.status.idle":"2021-08-03T11:29:54.183212Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## WORK IN PROGRESS...","metadata":{}}]}