{"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},{"sourceId":8510886,"sourceType":"datasetVersion","datasetId":5080437},{"sourceId":8517589,"sourceType":"datasetVersion","datasetId":5085361},{"sourceId":8517619,"sourceType":"datasetVersion","datasetId":5085380}],"dockerImageVersionId":30120,"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":"!git clone https://github.com/Omid-Nejati/MedViT","metadata":{"execution":{"iopub.status.busy":"2024-06-03T02:12:52.809558Z","iopub.execute_input":"2024-06-03T02:12:52.809815Z","iopub.status.idle":"2024-06-03T02:12:54.683956Z","shell.execute_reply.started":"2024-06-03T02:12:52.809791Z","shell.execute_reply":"2024-06-03T02:12:54.682974Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install torchsummary","metadata":{"execution":{"iopub.status.busy":"2024-06-03T02:12:54.685522Z","iopub.execute_input":"2024-06-03T02:12:54.685827Z","iopub.status.idle":"2024-06-03T02:13:03.246453Z","shell.execute_reply.started":"2024-06-03T02:12:54.685793Z","shell.execute_reply":"2024-06-03T02:13:03.245446Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport sys\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\n\nimport torchvision.utils\nfrom torchvision import models\nimport torchvision.datasets as dsets\nimport torchvision.transforms as transforms","metadata":{"execution":{"iopub.status.busy":"2024-06-03T02:13:03.248755Z","iopub.execute_input":"2024-06-03T02:13:03.249165Z","iopub.status.idle":"2024-06-03T02:13:04.672813Z","shell.execute_reply.started":"2024-06-03T02:13:03.249121Z","shell.execute_reply":"2024-06-03T02:13:04.67208Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install timm\n!pip install einops","metadata":{"execution":{"iopub.status.busy":"2024-06-03T02:13:04.674359Z","iopub.execute_input":"2024-06-03T02:13:04.674647Z","iopub.status.idle":"2024-06-03T02:13:21.543049Z","shell.execute_reply.started":"2024-06-03T02:13:04.674618Z","shell.execute_reply":"2024-06-03T02:13:21.542Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"package_path = \"/kaggle/input/medvit-for-brain-tumor/MedViT\"\nimport sys \nsys.path.append(package_path)","metadata":{"execution":{"iopub.status.busy":"2024-06-03T02:13:21.544621Z","iopub.execute_input":"2024-06-03T02:13:21.544944Z","iopub.status.idle":"2024-06-03T02:13:21.549636Z","shell.execute_reply.started":"2024-06-03T02:13:21.544899Z","shell.execute_reply":"2024-06-03T02:13:21.548684Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from MedViT import MedViT_base","metadata":{"execution":{"iopub.status.busy":"2024-06-03T02:13:21.550753Z","iopub.execute_input":"2024-06-03T02:13:21.55105Z","iopub.status.idle":"2024-06-03T02:13:22.483249Z","shell.execute_reply.started":"2024-06-03T02:13:21.55102Z","shell.execute_reply":"2024-06-03T02:13:22.482095Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"MedViT_base","metadata":{"execution":{"iopub.status.busy":"2024-06-03T02:13:22.484823Z","iopub.execute_input":"2024-06-03T02:13:22.48513Z","iopub.status.idle":"2024-06-03T02:13:22.493035Z","shell.execute_reply.started":"2024-06-03T02:13:22.485099Z","shell.execute_reply":"2024-06-03T02:13:22.492172Z"},"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\n\nfrom sklearn.model_selection import StratifiedKFold","metadata":{"execution":{"iopub.status.busy":"2024-06-03T02:13:22.495549Z","iopub.execute_input":"2024-06-03T02:13:22.495864Z","iopub.status.idle":"2024-06-03T02:13:23.563541Z","shell.execute_reply.started":"2024-06-03T02:13:22.495836Z","shell.execute_reply":"2024-06-03T02:13:23.562741Z"},"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    \n    cnn_features = 256\n    lstm_hidden = 32\n    \n    n_fold = 3\n    n_epochs = 50","metadata":{"execution":{"iopub.status.busy":"2024-06-03T02:13:23.565264Z","iopub.execute_input":"2024-06-03T02:13:23.565547Z","iopub.status.idle":"2024-06-03T02:13:23.623024Z","shell.execute_reply.started":"2024-06-03T02:13:23.565522Z","shell.execute_reply":"2024-06-03T02:13:23.622078Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Model","metadata":{}},{"cell_type":"code","source":"# net = efficientnet_pytorch.EfficientNet.from_name(\"efficientnet-b0\")\n# checkpoint = torch.load(\"../input/efficientnet-pytorch/efficientnet-b0-08094119.pth\")\n# net.load_state_dict(checkpoint)\n# n_features = net._fc.in_features\n# n_features","metadata":{"execution":{"iopub.status.busy":"2024-06-03T02:13:23.624309Z","iopub.execute_input":"2024-06-03T02:13:23.624597Z","iopub.status.idle":"2024-06-03T02:13:23.633486Z","shell.execute_reply.started":"2024-06-03T02:13:23.624568Z","shell.execute_reply":"2024-06-03T02:13:23.632646Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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_pytorch.EfficientNet.from_name(\"efficientnet-b0\")\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\n# # class MedViTModel(nn.Module):\n# #     def __init__(self):\n# #         super().__init__()\n# #         # Assuming MedViT class is defined and takes the necessary arguments\n# #         self.medvit = MedViTmodel(img_size=CFG.img_size, num_classes=CFG.cnn_features)\n    \n# #     def forward(self, x):\n# #         out = self.medvit(x)\n# #         return out\n\n# class Model(nn.Module):\n#     def __init__(self):\n#         super(Model, self).__init__()\n#         self.cnn = CNN()\n#         self.rnn = nn.LSTM(CFG.cnn_features, CFG.lstm_hidden, 2, batch_first=True)\n#         self.fc = nn.Linear(CFG.lstm_hidden, 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#         output, (hn, cn) = self.rnn(r_in)\n        \n#         out = self.fc(hn[-1])\n#         return out","metadata":{"execution":{"iopub.status.busy":"2024-06-03T02:13:23.634689Z","iopub.execute_input":"2024-06-03T02:13:23.635118Z","iopub.status.idle":"2024-06-03T02:13:23.643895Z","shell.execute_reply.started":"2024-06-03T02:13:23.63508Z","shell.execute_reply":"2024-06-03T02:13:23.643159Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def load_medvit_weights(model, weight_path):\n    state_dict = torch.load(weight_path)\n    model.load_state_dict(state_dict, strict=False)\n    return model\n","metadata":{"execution":{"iopub.status.busy":"2024-06-03T02:13:23.644974Z","iopub.execute_input":"2024-06-03T02:13:23.645256Z","iopub.status.idle":"2024-06-03T02:13:23.657274Z","shell.execute_reply.started":"2024-06-03T02:13:23.645229Z","shell.execute_reply":"2024-06-03T02:13:23.656455Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class MedViTModel(nn.Module):\n    def __init__(self):\n        super(MedViTModel, self).__init__()\n        self.map = nn.Conv2d(in_channels=4, out_channels=3, kernel_size=1)  # Chuyển đổi từ 4 kênh xuống 3 kênh\n        self.net = MedViT_base(num_classes=CFG.cnn_features)\n        self.net = load_medvit_weights(self.net, \"/kaggle/input/medvit-base-model/MedViT_base_im1k.pth\")  # Load trọng số\n\n        # Đóng băng tất cả các lớp\n        for param in self.net.parameters():\n            param.requires_grad = False\n\n        # Mở khóa vài lớp cuối cùng\n        for param in list(self.net.parameters())[-3:]: \n            param.requires_grad = 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 = MedViTModel()\n        self.rnn = nn.LSTM(CFG.cnn_features, CFG.lstm_hidden, 2, batch_first=True)\n        self.fc = nn.Linear(CFG.lstm_hidden, 1, bias=True)\n\n    def forward(self, x):\n        # x shape: BxTxCxHxW\n        batch_size, timesteps, C, H, W = x.size()\n        # Reshape để đưa vào MedViT\n        c_in = x.view(batch_size * timesteps, C, H, W)\n        c_out = self.cnn(c_in)\n        # Reshape để đưa vào LSTM\n        r_in = c_out.view(batch_size, timesteps, -1)\n        output, (hn, cn) = self.rnn(r_in)\n        # Lấy trạng thái ẩn cuối cùng của LSTM và đưa vào fully connected layer\n        out = self.fc(hn[-1])\n        return out","metadata":{"execution":{"iopub.status.busy":"2024-06-03T02:13:23.658511Z","iopub.execute_input":"2024-06-03T02:13:23.658858Z","iopub.status.idle":"2024-06-03T02:13:23.671112Z","shell.execute_reply.started":"2024-06-03T02:13:23.65883Z","shell.execute_reply":"2024-06-03T02:13:23.67033Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# !pip install torchinfo","metadata":{"execution":{"iopub.status.busy":"2024-06-03T02:13:23.672048Z","iopub.execute_input":"2024-06-03T02:13:23.672334Z","iopub.status.idle":"2024-06-03T02:13:23.691879Z","shell.execute_reply.started":"2024-06-03T02:13:23.672298Z","shell.execute_reply":"2024-06-03T02:13:23.691147Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# from torchinfo import summary","metadata":{"execution":{"iopub.status.busy":"2024-06-03T02:13:23.693134Z","iopub.execute_input":"2024-06-03T02:13:23.693499Z","iopub.status.idle":"2024-06-03T02:13:23.702751Z","shell.execute_reply.started":"2024-06-03T02:13:23.693464Z","shell.execute_reply":"2024-06-03T02:13:23.70198Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# # Khởi tạo mô hình\n# device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n# model = Model().to(device)\n\n# # In ra chi tiết các tham số của mô hình để xác minh\n# from torchinfo import summary\n# summary(model, input_size=(8, CFG.n_frames, 4, CFG.img_size, CFG.img_size), col_names=[\"input_size\", \"output_size\", \"num_params\", \"kernel_size\", \"mult_adds\"])","metadata":{"execution":{"iopub.status.busy":"2024-06-03T02:13:23.703908Z","iopub.execute_input":"2024-06-03T02:13:23.704292Z","iopub.status.idle":"2024-06-03T02:13:23.712575Z","shell.execute_reply.started":"2024-06-03T02:13:23.704255Z","shell.execute_reply":"2024-06-03T02:13:23.711823Z"},"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-06-03T02:13:23.713635Z","iopub.execute_input":"2024-06-03T02:13:23.713911Z","iopub.status.idle":"2024-06-03T02:13:23.722385Z","shell.execute_reply.started":"2024-06-03T02:13:23.713884Z","shell.execute_reply":"2024-06-03T02:13:23.721599Z"},"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-06-03T02:13:23.723389Z","iopub.execute_input":"2024-06-03T02:13:23.723652Z","iopub.status.idle":"2024-06-03T02:13:23.735939Z","shell.execute_reply.started":"2024-06-03T02:13:23.723628Z","shell.execute_reply":"2024-06-03T02:13:23.735131Z"},"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-06-03T02:13:23.737029Z","iopub.execute_input":"2024-06-03T02:13:23.737311Z","iopub.status.idle":"2024-06-03T02:13:23.751687Z","shell.execute_reply.started":"2024-06-03T02:13:23.737273Z","shell.execute_reply":"2024-06-03T02:13:23.750745Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import albumentations as A\nfrom albumentations.pytorch import ToTensorV2\n\n#Data augmentation\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-06-03T02:13:23.752743Z","iopub.execute_input":"2024-06-03T02:13:23.753047Z","iopub.status.idle":"2024-06-03T02:13:24.721165Z","shell.execute_reply.started":"2024-06-03T02:13:23.75302Z","shell.execute_reply":"2024-06-03T02:13:24.720368Z"},"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-06-03T02:13:24.722569Z","iopub.execute_input":"2024-06-03T02:13:24.722969Z","iopub.status.idle":"2024-06-03T02:13:24.726575Z","shell.execute_reply.started":"2024-06-03T02:13:24.722914Z","shell.execute_reply":"2024-06-03T02:13:24.725654Z"},"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-06-03T02:13:24.727835Z","iopub.execute_input":"2024-06-03T02:13:24.728216Z","iopub.status.idle":"2024-06-03T02:13:24.757059Z","shell.execute_reply.started":"2024-06-03T02:13:24.728178Z","shell.execute_reply":"2024-06-03T02:13:24.756242Z"},"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-06-03T02:13:24.759802Z","iopub.execute_input":"2024-06-03T02:13:24.760117Z","iopub.status.idle":"2024-06-03T02:13:24.763751Z","shell.execute_reply.started":"2024-06-03T02:13:24.760088Z","shell.execute_reply":"2024-06-03T02:13:24.762605Z"},"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-06-03T02:13:24.765201Z","iopub.execute_input":"2024-06-03T02:13:24.765491Z","iopub.status.idle":"2024-06-03T02:13:24.773473Z","shell.execute_reply.started":"2024-06-03T02:13:24.765464Z","shell.execute_reply":"2024-06-03T02:13:24.772731Z"},"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(\"Score\")\n        plt.xlabel(\"Training Epochs\")\n        plt.ylabel(\"Acc\")\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=\"Validation\")\n        plt.plot(self.hist['val_score'], label=\"Train\")\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-06-03T02:13:24.774638Z","iopub.execute_input":"2024-06-03T02:13:24.774916Z","iopub.status.idle":"2024-06-03T02:13:24.803782Z","shell.execute_reply.started":"2024-06-03T02:13:24.774889Z","shell.execute_reply":"2024-06-03T02:13:24.802919Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(len(df))","metadata":{"execution":{"iopub.status.busy":"2024-06-03T02:13:24.804854Z","iopub.execute_input":"2024-06-03T02:13:24.805124Z","iopub.status.idle":"2024-06-03T02:13:24.817501Z","shell.execute_reply.started":"2024-06-03T02:13:24.805101Z","shell.execute_reply":"2024-06-03T02:13:24.816527Z"},"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-06-03T02:13:24.818584Z","iopub.execute_input":"2024-06-03T02:13:24.818868Z","iopub.status.idle":"2024-06-03T02:13:24.834896Z","shell.execute_reply.started":"2024-06-03T02:13:24.818841Z","shell.execute_reply":"2024-06-03T02:13:24.834015Z"},"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-06-03T02:13:24.836036Z","iopub.execute_input":"2024-06-03T02:13:24.836313Z","iopub.status.idle":"2024-06-03T02:13:24.84566Z","shell.execute_reply.started":"2024-06-03T02:13:24.836276Z","shell.execute_reply":"2024-06-03T02:13:24.844686Z"},"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-06-03T02:18:42.67957Z","iopub.execute_input":"2024-06-03T02:18:42.679964Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":" trainer = '/kaggle/working/best-model-2.pth'\n\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\nlosses.append(loss)\nscores.append(score)\n    \ntrainer.plot_loss()\ntrainer.plot_score()\n\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\")","metadata":{"execution":{"iopub.status.busy":"2024-06-03T02:18:40.741862Z","iopub.status.idle":"2024-06-03T02:18:40.742357Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load the saved model\nmodel_path = '/kaggle/working/best-model-1.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\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-06-03T02:18:40.743384Z","iopub.status.idle":"2024-06-03T02:18:40.743782Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}