{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.7.10","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":29653,"databundleVersionId":2420395,"sourceType":"competition"},{"sourceId":848739,"sourceType":"datasetVersion","datasetId":251095},{"sourceId":2425289,"sourceType":"datasetVersion","datasetId":1467572}],"dockerImageVersionId":30121,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Import things","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2021-07-18T04:22:55.955919Z","iopub.execute_input":"2021-07-18T04:22:55.956524Z","iopub.status.idle":"2021-07-18T04:22:56.527271Z","shell.execute_reply.started":"2021-07-18T04:22:55.956406Z","shell.execute_reply":"2021-07-18T04:22:56.526277Z"}}},{"cell_type":"code","source":"!pip install efficientnet-pytorch","metadata":{"execution":{"iopub.status.busy":"2024-05-28T16:25:57.072736Z","iopub.execute_input":"2024-05-28T16:25:57.073118Z","iopub.status.idle":"2024-05-28T16:26:07.458657Z","shell.execute_reply.started":"2024-05-28T16:25:57.073085Z","shell.execute_reply":"2024-05-28T16:26:07.457815Z"},"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 os\nimport glob\nimport time\nimport random\n\nimport numpy as np\nimport pandas as pd\n\nimport pydicom\nfrom pydicom.pixel_data_handlers.util import apply_voi_lut\nimport cv2\nimport matplotlib.pyplot as plt\n\nimport torch\nfrom torch import nn\nfrom torch.utils import data as torch_data\nfrom torch.nn import functional as F\nfrom torch.utils.data import Dataset, DataLoader\n\nimport efficientnet_pytorch\nfrom efficientnet_pytorch import EfficientNet\n\nfrom sklearn.model_selection import StratifiedKFold","metadata":{"execution":{"iopub.status.busy":"2024-05-28T16:31:10.947624Z","iopub.execute_input":"2024-05-28T16:31:10.948352Z","iopub.status.idle":"2024-05-28T16:31:10.959673Z","shell.execute_reply.started":"2024-05-28T16:31:10.948300Z","shell.execute_reply":"2024-05-28T16:31:10.958644Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nseed = 123\n\ndef seed_everything(seed):\n    random.seed(seed)\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed(seed)\n    torch.backends.cudnn.deterministic = True\n    torch.backends.cudnn.benchmark = True\n\nseed_everything(seed)\n\nclass CFG:\n    img_size = 256\n    n_frames = 10\n    cnn_features = 256\n    transformer_hidden = 256\n    transformer_layers = 4\n    n_fold = 5\n    n_epochs = 10\n","metadata":{"execution":{"iopub.status.busy":"2024-05-28T16:31:11.308811Z","iopub.execute_input":"2024-05-28T16:31:11.309162Z","iopub.status.idle":"2024-05-28T16:31:11.317088Z","shell.execute_reply.started":"2024-05-28T16:31:11.309134Z","shell.execute_reply":"2024-05-28T16:31:11.316001Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Model","metadata":{}},{"cell_type":"code","source":"class CNN(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.map = nn.Conv2d(in_channels=4, out_channels=3, kernel_size=1)\n        self.net = EfficientNet.from_name(\"efficientnet-b0\")\n        # Uncomment and modify the following lines if you have a specific checkpoint to load\n        # checkpoint = torch.load(\"../input/efficientnet-pytorch/efficientnet-b0-08094119.pth\")\n        # self.net.load_state_dict(checkpoint)\n        \n        n_features = self.net._fc.in_features\n        self.net._fc = nn.Linear(in_features=n_features, out_features=CFG.cnn_features, bias=True)\n    \n    def forward(self, x):\n        x = F.relu(self.map(x))\n        out = self.net(x)\n        return out\n\nclass Model(nn.Module):\n    def __init__(self):\n        super(Model, self).__init__()\n        self.cnn = CNN()\n        \n        encoder_layers = nn.TransformerEncoderLayer(d_model=CFG.cnn_features, nhead=8, dim_feedforward=CFG.transformer_hidden, dropout=0.1)\n        self.transformer_encoder = nn.TransformerEncoder(encoder_layers, num_layers=CFG.transformer_layers)\n        \n        self.fc = nn.Linear(CFG.cnn_features, 1, bias=True)\n\n    def forward(self, x):\n        # x shape: BxTxCxHxW\n        batch_size, timesteps, C, H, W = x.size()\n        c_in = x.view(batch_size * timesteps, C, H, W)\n        c_out = self.cnn(c_in)\n        r_in = c_out.view(batch_size, timesteps, -1)\n        \n        # TransformerEncoder expects input of shape (T, B, C)\n        r_in = r_in.permute(1, 0, 2)\n        transformer_out = self.transformer_encoder(r_in)\n        \n        # Taking the mean of the transformer outputs for each time step\n        out = transformer_out.mean(dim=0)\n        out = self.fc(out)\n        return out\n","metadata":{"execution":{"iopub.status.busy":"2024-05-28T16:31:12.205934Z","iopub.execute_input":"2024-05-28T16:31:12.206273Z","iopub.status.idle":"2024-05-28T16:31:12.218465Z","shell.execute_reply.started":"2024-05-28T16:31:12.206246Z","shell.execute_reply":"2024-05-28T16:31:12.217364Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# model = Model()\n# x = torch.zeros((1, 15, 4, 256, 256))\n# t = time.time()\n# out = model(x)\n# print(time.time()-t)\n# print(out.shape)","metadata":{"execution":{"iopub.status.busy":"2024-05-28T16:31:12.552193Z","iopub.execute_input":"2024-05-28T16:31:12.552527Z","iopub.status.idle":"2024-05-28T16:31:12.556208Z","shell.execute_reply.started":"2024-05-28T16:31:12.552497Z","shell.execute_reply":"2024-05-28T16:31:12.555199Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Data Processing","metadata":{}},{"cell_type":"code","source":"def load_image(path):\n    image = cv2.imread(path, 0)\n    if image is None:\n        return np.zeros((CFG.img_size, CFG.img_size))\n    \n    image = cv2.resize(image, (CFG.img_size, CFG.img_size)) / 255\n    return image.astype('f')\n\ndef uniform_temporal_subsample(x, num_samples):\n    '''\n        Moddified from https://github.com/facebookresearch/pytorchvideo/blob/d7874f788bc00a7badfb4310a912f6e531ffd6d3/pytorchvideo/transforms/functional.py#L19\n        Args:\n            x: input list\n            num_samples: The number of equispaced samples to be selected\n        Returns:\n            Output list     \n    '''\n    t = len(x)\n    indices = torch.linspace(0, t - 1, num_samples)\n    indices = torch.clamp(indices, 0, t - 1).long()\n    return [x[i] for i in indices]","metadata":{"execution":{"iopub.status.busy":"2024-05-28T16:31:13.207276Z","iopub.execute_input":"2024-05-28T16:31:13.207620Z","iopub.status.idle":"2024-05-28T16:31:13.214653Z","shell.execute_reply.started":"2024-05-28T16:31:13.207590Z","shell.execute_reply":"2024-05-28T16:31:13.213685Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class DataRetriever(Dataset):\n    def __init__(self, paths, targets, transform=None):\n        self.paths = paths\n        self.targets = targets\n        self.transform = transform\n          \n    def __len__(self):\n        return len(self.paths)\n    \n    def read_video(self, vid_paths):\n        video = [load_image(path) for path in vid_paths]\n        if self.transform:\n            seed = random.randint(0,99999)\n            for i in range(len(video)):\n                random.seed(seed)\n                video[i] = self.transform(image=video[i])[\"image\"]\n        \n        video = [torch.tensor(frame, dtype=torch.float32) for frame in video]\n        if len(video)==0:\n            video = torch.zeros(CFG.n_frames, CFG.img_size, CFG.img_size)\n        else:\n            video = torch.stack(video) # T * C * H * W\n#         video = torch.transpose(video, 0, 1) # C * T * H * W\n        return video\n    \n    def __getitem__(self, index):\n        _id = self.paths[index]\n        patient_path = f\"../input/rsna-miccai-png/train/{str(_id).zfill(5)}/\"\n        channels = []\n        for t in [\"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            num_samples = CFG.n_frames\n            if len(t_paths) < num_samples:\n                in_frames_path = t_paths\n            else:\n                in_frames_path = uniform_temporal_subsample(t_paths, num_samples)\n            \n            channel = self.read_video(in_frames_path)\n            if channel.shape[0] == 0:\n                print(\"1 channel empty\")\n                channel = torch.zeros(num_samples, CFG.img_size, CFG.img_size)\n            channels.append(channel)\n            \n        channels = torch.stack(channels).transpose(0,1)\n        \n        y = torch.tensor(self.targets[index], dtype=torch.float)\n        return {\"X\": channels.float(), \"y\": y}","metadata":{"execution":{"iopub.status.busy":"2024-05-28T16:31:13.548557Z","iopub.execute_input":"2024-05-28T16:31:13.548910Z","iopub.status.idle":"2024-05-28T16:31:13.563281Z","shell.execute_reply.started":"2024-05-28T16:31:13.548879Z","shell.execute_reply":"2024-05-28T16:31:13.562226Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import albumentations as A\nfrom albumentations.pytorch import ToTensorV2\n\ntrain_transform = A.Compose([\n                                A.HorizontalFlip(p=0.5),\n                                A.ShiftScaleRotate(\n                                    shift_limit=0.0625, \n                                    scale_limit=0.1, \n                                    rotate_limit=10, \n                                    p=0.5\n                                ),\n                                A.RandomBrightnessContrast(p=0.5),\n                            ])\nvalid_transform = A.Compose([\n                            ])","metadata":{"execution":{"iopub.status.busy":"2024-05-28T16:31:13.880485Z","iopub.execute_input":"2024-05-28T16:31:13.880857Z","iopub.status.idle":"2024-05-28T16:31:13.886712Z","shell.execute_reply.started":"2024-05-28T16:31:13.880822Z","shell.execute_reply":"2024-05-28T16:31:13.885761Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# data = DataRetriever(\n#         train_df[\"BraTS21ID\"].values, \n#         train_df[\"MGMT_value\"].values\n#     )\n# data[0]['X'].shape","metadata":{"execution":{"iopub.status.busy":"2024-05-28T16:31:14.200371Z","iopub.execute_input":"2024-05-28T16:31:14.200700Z","iopub.status.idle":"2024-05-28T16:31:14.204520Z","shell.execute_reply.started":"2024-05-28T16:31:14.200672Z","shell.execute_reply":"2024-05-28T16:31:14.203544Z"},"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.head(10)","metadata":{"execution":{"iopub.status.busy":"2024-05-28T16:31:14.544362Z","iopub.execute_input":"2024-05-28T16:31:14.544698Z","iopub.status.idle":"2024-05-28T16:31:14.559826Z","shell.execute_reply.started":"2024-05-28T16:31:14.544670Z","shell.execute_reply":"2024-05-28T16:31:14.559025Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# train_data = TrainDataRetriever(\n#     train_df[\"BraTS21ID\"].values, \n#     train_df[\"MGMT_value\"].values)\n# for idx, dat in enumerate(train_data):\n#     print('{} {} {}'.format(idx, dat['video'].shape, dat['label']))","metadata":{"execution":{"iopub.status.busy":"2024-05-28T16:31:14.909248Z","iopub.execute_input":"2024-05-28T16:31:14.909603Z","iopub.status.idle":"2024-05-28T16:31:14.913194Z","shell.execute_reply.started":"2024-05-28T16:31:14.909570Z","shell.execute_reply":"2024-05-28T16:31:14.912248Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Training","metadata":{}},{"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":"2024-05-28T16:31:15.515445Z","iopub.execute_input":"2024-05-28T16:31:15.515820Z","iopub.status.idle":"2024-05-28T16:31:15.524039Z","shell.execute_reply.started":"2024-05-28T16:31:15.515756Z","shell.execute_reply":"2024-05-28T16:31:15.523040Z"},"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        self.hist = {'val_loss':[],\n                     'val_score':[],\n                     'train_loss':[],\n                     'train_score':[]\n                    }\n        \n        self.best_valid_score = -np.inf\n        self.best_valid_loss = 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            self.hist['val_loss'].append(valid_loss)\n            self.hist['train_loss'].append(train_loss)\n            self.hist['val_score'].append(valid_score)\n            self.hist['train_score'].append(train_score)\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.best_valid_loss = valid_loss\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        return self.best_valid_loss, self.best_valid_score\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 plot_loss(self):\n        plt.title(\"Loss\")\n        plt.xlabel(\"Training Epochs\")\n        plt.ylabel(\"Loss\")\n\n        plt.plot(self.hist['train_loss'], label=\"Train\")\n        plt.plot(self.hist['val_loss'], label=\"Validation\")\n        plt.legend()\n        plt.show()\n    \n    def plot_score(self):\n        plt.title(\"Score\")\n        plt.xlabel(\"Training Epochs\")\n        plt.ylabel(\"Acc\")\n\n        plt.plot(self.hist['train_score'], label=\"Train\")\n        plt.plot(self.hist['val_score'], label=\"Validation\")\n        plt.legend()\n        plt.show()\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":"2024-05-28T16:31:15.833892Z","iopub.execute_input":"2024-05-28T16:31:15.834252Z","iopub.status.idle":"2024-05-28T16:31:15.864192Z","shell.execute_reply.started":"2024-05-28T16:31:15.834217Z","shell.execute_reply":"2024-05-28T16:31:15.863179Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n\n# train valid test\n# 0.8   0.1   0.1\n\n# df_train_valid, test_df = train_test_split(df, test_size=0.2/(1+0.2), random_state=42)\n# print(len(df_train_valid), len(test_df))\n\ndf_train_valid, test_df = train_test_split(df, test_size=0.1, random_state=42, stratify=df['MGMT_value'])\n\n# Next, split the train_valid set into 88.9% train and 11.1% valid,\n# which will result in train being 80% of the original and valid being 10% of the original\ntrain_df, valid_df = train_test_split(df_train_valid, test_size=0.1111, random_state=42, stratify=df_train_valid['MGMT_value'])\n\nprint(f\"Train size: {len(train_df)}\")\nprint(f\"Validation size: {len(valid_df)}\")\nprint(f\"Test size: {len(test_df)}\")","metadata":{"execution":{"iopub.status.busy":"2024-05-28T16:31:16.171551Z","iopub.execute_input":"2024-05-28T16:31:16.171914Z","iopub.status.idle":"2024-05-28T16:31:16.185795Z","shell.execute_reply.started":"2024-05-28T16:31:16.171879Z","shell.execute_reply":"2024-05-28T16:31:16.184694Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# df_train_valid = df_train_valid.reset_index().drop('index', axis=1)\n# df_train_valid.head()\ndf_train_valid = pd.concat([train_df, valid_df]).reset_index(drop=True)\ndf_train_valid.head()","metadata":{"execution":{"iopub.status.busy":"2024-05-28T16:31:16.524553Z","iopub.execute_input":"2024-05-28T16:31:16.524915Z","iopub.status.idle":"2024-05-28T16:31:16.534875Z","shell.execute_reply.started":"2024-05-28T16:31:16.524882Z","shell.execute_reply":"2024-05-28T16:31:16.533955Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"skf = StratifiedKFold(n_splits=CFG.n_fold)\n\nstart_time = time.time()\n\nlosses = []\nscores = []\n\nfor fold, (train_index, val_index) in enumerate(skf.split(np.zeros(len(df_train_valid)), df_train_valid['MGMT_value']), 1):\n    print('-'*30)\n    print(f\"Fold {fold}\")\n    \n    train_df = df_train_valid.loc[train_index]\n    val_df = df_train_valid.loc[val_index]\n    \n#     print(len(train_df), len(val_df))\n    \n    train_retriever = DataRetriever(\n        train_df[\"BraTS21ID\"].values, \n        train_df[\"MGMT_value\"].values,\n        train_transform\n    )\n    \n    val_retriever = DataRetriever(\n        val_df[\"BraTS21ID\"].values, \n        val_df[\"MGMT_value\"].values\n    )\n    \n    train_loader = torch_data.DataLoader(\n        train_retriever,\n        batch_size=2,\n        shuffle=True,\n        num_workers=8,\n    )\n    valid_loader = torch_data.DataLoader(\n        val_retriever, \n        batch_size=2,\n        shuffle=False,\n        num_workers=8,\n    )\n    \n    model = Model()\n    model.to(device)\n    \n    optimizer = torch.optim.Adam(model.parameters(), lr=0.0001)\n    criterion = F.binary_cross_entropy_with_logits\n    \n    trainer = Trainer(\n        model, \n        device, \n        optimizer, \n        criterion, \n        LossMeter, \n        AccMeter\n    )\n    loss, score = trainer.fit(\n        CFG.n_epochs, \n        train_loader, \n        valid_loader, \n        f\"best-model-{fold}.pth\", \n        100,\n    )\n    losses.append(loss)\n    scores.append(score)\n    \n    trainer.plot_loss()\n    trainer.plot_score()\n    \nelapsed_time = time.time() - start_time\nprint('\\nTraining complete in {:.0f}m {:.0f}s'.format(elapsed_time // 60, elapsed_time % 60))\nprint('Avg loss {}'.format(np.mean(losses)))\nprint('Avg score {}'.format(np.mean(scores)))","metadata":{"execution":{"iopub.status.busy":"2024-05-28T16:31:17.002631Z","iopub.execute_input":"2024-05-28T16:31:17.002995Z","iopub.status.idle":"2024-05-28T17:11:02.856264Z","shell.execute_reply.started":"2024-05-28T16:31:17.002963Z","shell.execute_reply":"2024-05-28T17:11:02.855311Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load the saved model\nmodel_path = '/kaggle/working/best-model-2.pth'\ncheckpoint = torch.load(model_path)\n\n# Initialize the model\nmodel = Model()\nmodel.to(device)\n\n# Load the model state dictionary from the checkpoint\nmodel.load_state_dict(checkpoint[\"model_state_dict\"])\n\n# Prepare the test data\ntest_retriever = DataRetriever(\n    test_df[\"BraTS21ID\"].values, \n    test_df[\"MGMT_value\"].values\n)\n\ntest_loader = torch_data.DataLoader(\n    test_retriever, \n    batch_size= 1,\n    shuffle=False,\n    num_workers=8,\n)\n\n# Set optimizer with weight decay (L2 regularization)\noptimizer = torch.optim.Adam(model.parameters(), lr=0.0001)\ncriterion = F.binary_cross_entropy_with_logits\n\n# Trainer instance\ntrainer = Trainer(\n    model, \n    device, \n    optimizer, \n    criterion, \n    LossMeter, \n    AccMeter\n)\n\n# Evaluate the model on the test set\n_, test_score, test_time = trainer.valid_epoch(test_loader)\nprint(f\"Test Accuracy: {test_score:.5f}\")\nprint(f\"Test Time: {test_time:.2f} seconds\")\n","metadata":{"execution":{"iopub.status.busy":"2024-05-28T17:41:53.123435Z","iopub.execute_input":"2024-05-28T17:41:53.123800Z","iopub.status.idle":"2024-05-28T17:41:56.292082Z","shell.execute_reply.started":"2024-05-28T17:41:53.123753Z","shell.execute_reply":"2024-05-28T17:41:56.290938Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}