{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":30892,"databundleVersionId":2715462,"sourceType":"competition"}],"dockerImageVersionId":30580,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"!pip install torchsummary\n!pip install torchgeometry","metadata":{"execution":{"iopub.status.busy":"2023-11-15T13:40:03.407003Z","iopub.execute_input":"2023-11-15T13:40:03.407280Z","iopub.status.idle":"2023-11-15T13:40:30.051720Z","shell.execute_reply.started":"2023-11-15T13:40:03.407255Z","shell.execute_reply":"2023-11-15T13:40:30.050420Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install segmentation-models-pytorch","metadata":{"execution":{"iopub.status.busy":"2023-11-15T13:54:37.193060Z","iopub.execute_input":"2023-11-15T13:54:37.194191Z","iopub.status.idle":"2023-11-15T13:54:56.623148Z","shell.execute_reply.started":"2023-11-15T13:54:37.194152Z","shell.execute_reply":"2023-11-15T13:54:56.622090Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from torchsummary import summary\nfrom torchgeometry.losses import one_hot\nimport os\nimport pandas as pd\nimport numpy as np\nfrom PIL import Image\nimport cv2\nimport time\nimport imageio\nimport matplotlib.pyplot as plt\nimport time\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.optim import lr_scheduler\nfrom torch import Tensor\nfrom torch.utils.data import Dataset, DataLoader, random_split\nfrom torchvision.transforms import Resize, PILToTensor, ToPILImage, Compose, InterpolationMode\nfrom collections import OrderedDict\nimport wandb","metadata":{"execution":{"iopub.status.busy":"2023-11-15T13:47:32.939683Z","iopub.execute_input":"2023-11-15T13:47:32.940659Z","iopub.status.idle":"2023-11-15T13:47:32.947343Z","shell.execute_reply.started":"2023-11-15T13:47:32.940624Z","shell.execute_reply":"2023-11-15T13:47:32.946346Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!nvidia-smi -L","metadata":{"execution":{"iopub.status.busy":"2023-11-15T13:47:35.335958Z","iopub.execute_input":"2023-11-15T13:47:35.336323Z","iopub.status.idle":"2023-11-15T13:47:36.308580Z","shell.execute_reply.started":"2023-11-15T13:47:35.336292Z","shell.execute_reply":"2023-11-15T13:47:36.307434Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\ndevice","metadata":{"execution":{"iopub.status.busy":"2023-11-15T13:47:37.519584Z","iopub.execute_input":"2023-11-15T13:47:37.519969Z","iopub.status.idle":"2023-11-15T13:47:37.603156Z","shell.execute_reply.started":"2023-11-15T13:47:37.519937Z","shell.execute_reply":"2023-11-15T13:47:37.602189Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Number of class in the data set (3: neoplastic, non neoplastic, background)\nnum_classes = 3\n\n# Number of epoch\nepochs = 15\n\n# Hyperparameters for training \nlearning_rate = 0.001\nbatch_size = 4\ndisplay_step = 50\n\n# Model path\ncheckpoint_path = '/kaggle/working/unet_model.pth'\npretrained_path = \"/kaggle/input/unet-checkpoint/unet_model.pth\"\n# Initialize lists to keep track of loss and accuracy\nloss_epoch_array = []\ntrain_accuracy = []\ntest_accuracy = []\nvalid_accuracy = []","metadata":{"execution":{"iopub.status.busy":"2023-11-15T13:47:39.150500Z","iopub.execute_input":"2023-11-15T13:47:39.150866Z","iopub.status.idle":"2023-11-15T13:47:39.156149Z","shell.execute_reply.started":"2023-11-15T13:47:39.150834Z","shell.execute_reply":"2023-11-15T13:47:39.155289Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torchvision.transforms as transforms","metadata":{"execution":{"iopub.status.busy":"2023-11-15T13:47:41.224406Z","iopub.execute_input":"2023-11-15T13:47:41.225104Z","iopub.status.idle":"2023-11-15T13:47:41.229459Z","shell.execute_reply.started":"2023-11-15T13:47:41.225067Z","shell.execute_reply":"2023-11-15T13:47:41.228496Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"transform = Compose([\n    Resize((512, 512), interpolation=InterpolationMode.BILINEAR),\n    transforms.RandomVerticalFlip(p=0.5),\n    transforms.RandomHorizontalFlip(p=0.5),\n    transforms.RandomRotation(degrees=20),\n    transforms.ColorJitter(),\n    PILToTensor()\n])","metadata":{"execution":{"iopub.status.busy":"2023-11-15T13:49:16.252395Z","iopub.execute_input":"2023-11-15T13:49:16.253095Z","iopub.status.idle":"2023-11-15T13:49:16.258190Z","shell.execute_reply.started":"2023-11-15T13:49:16.253060Z","shell.execute_reply":"2023-11-15T13:49:16.257412Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"val_transform = Compose([\n    Resize((512, 512), interpolation=InterpolationMode.BILINEAR),\n    PILToTensor()\n])","metadata":{"execution":{"iopub.status.busy":"2023-11-15T13:49:20.782010Z","iopub.execute_input":"2023-11-15T13:49:20.782617Z","iopub.status.idle":"2023-11-15T13:49:20.787007Z","shell.execute_reply.started":"2023-11-15T13:49:20.782574Z","shell.execute_reply":"2023-11-15T13:49:20.786038Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class UNetDataClass(Dataset):\n    def __init__(self, images_path, masks_path, transform):\n        super(UNetDataClass, self).__init__()\n        \n        images_list = os.listdir(images_path)\n        masks_list = os.listdir(masks_path)\n        \n        images_list = [images_path + image_name for image_name in images_list]\n        masks_list = [masks_path + mask_name for mask_name in masks_list]\n        \n        self.images_list = images_list\n        self.masks_list = masks_list\n        self.transform = transform\n        \n    def __getitem__(self, index):\n        img_path = self.images_list[index]\n        mask_path = self.masks_list[index]\n        \n        # Open image and mask\n        data = Image.open(img_path)\n        label = Image.open(mask_path)\n        \n        # Normalize\n        data = self.transform(data) / 255\n        label = self.transform(label) / 255\n        \n        label = torch.where(label>0.65, 1.0, 0.0)\n        \n        label[2, :, :] = 0.0001\n        label = torch.argmax(label, 0).type(torch.int64)\n        \n        return data, label\n    \n    def __len__(self):\n        return len(self.images_list)","metadata":{"execution":{"iopub.status.busy":"2023-11-15T13:49:25.818179Z","iopub.execute_input":"2023-11-15T13:49:25.818929Z","iopub.status.idle":"2023-11-15T13:49:25.827681Z","shell.execute_reply.started":"2023-11-15T13:49:25.818894Z","shell.execute_reply":"2023-11-15T13:49:25.826740Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"images_path = \"/kaggle/input/bkai-igh-neopolyp/train/train/\"\nmasks_path =  \"/kaggle/input/bkai-igh-neopolyp/train_gt/train_gt/\"","metadata":{"execution":{"iopub.status.busy":"2023-11-15T13:49:31.835437Z","iopub.execute_input":"2023-11-15T13:49:31.835813Z","iopub.status.idle":"2023-11-15T13:49:31.840655Z","shell.execute_reply.started":"2023-11-15T13:49:31.835782Z","shell.execute_reply":"2023-11-15T13:49:31.839530Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from torch.utils.data import ConcatDataset\nnot_aug_dataset = UNetDataClass(images_path= images_path,\n                             masks_path= masks_path,\n                             transform = val_transform)\naug_dataset = UNetDataClass(images_path= images_path,\n                             masks_path= masks_path,\n                             transform = transform)\nunet_dataset = ConcatDataset([not_aug_dataset, aug_dataset])\nprint(len(unet_dataset))","metadata":{"execution":{"iopub.status.busy":"2023-11-15T13:49:43.644016Z","iopub.execute_input":"2023-11-15T13:49:43.644745Z","iopub.status.idle":"2023-11-15T13:49:43.769704Z","shell.execute_reply.started":"2023-11-15T13:49:43.644712Z","shell.execute_reply":"2023-11-15T13:49:43.768833Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_size = 0.8\nvalid_size = 0.2","metadata":{"execution":{"iopub.status.busy":"2023-11-15T13:49:54.663581Z","iopub.execute_input":"2023-11-15T13:49:54.664317Z","iopub.status.idle":"2023-11-15T13:49:54.668396Z","shell.execute_reply.started":"2023-11-15T13:49:54.664286Z","shell.execute_reply":"2023-11-15T13:49:54.667417Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_set, valid_set = random_split(unet_dataset, \n                                    [int(train_size * len(unet_dataset)) , \n                                     int(valid_size * len(unet_dataset))])","metadata":{"execution":{"iopub.status.busy":"2023-11-15T13:50:21.593336Z","iopub.execute_input":"2023-11-15T13:50:21.593749Z","iopub.status.idle":"2023-11-15T13:50:21.652421Z","shell.execute_reply.started":"2023-11-15T13:50:21.593715Z","shell.execute_reply":"2023-11-15T13:50:21.651433Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(len(train_set))","metadata":{"execution":{"iopub.status.busy":"2023-11-15T13:50:33.749342Z","iopub.execute_input":"2023-11-15T13:50:33.750318Z","iopub.status.idle":"2023-11-15T13:50:33.756700Z","shell.execute_reply.started":"2023-11-15T13:50:33.750267Z","shell.execute_reply":"2023-11-15T13:50:33.755497Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_dataloader = DataLoader(train_set, batch_size=8, shuffle=True)\nvalid_dataloader = DataLoader(valid_set, batch_size=8, shuffle=True)","metadata":{"execution":{"iopub.status.busy":"2023-11-15T13:50:48.246552Z","iopub.execute_input":"2023-11-15T13:50:48.246947Z","iopub.status.idle":"2023-11-15T13:50:48.251680Z","shell.execute_reply.started":"2023-11-15T13:50:48.246918Z","shell.execute_reply":"2023-11-15T13:50:48.250785Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import segmentation_models_pytorch as smp\n\nmodel = smp.UnetPlusPlus(\n    encoder_name=\"resnet18\",        \n    encoder_weights=\"imagenet\",     \n    in_channels=3,                  \n    classes=3     \n)","metadata":{"execution":{"iopub.status.busy":"2023-11-15T13:55:08.213674Z","iopub.execute_input":"2023-11-15T13:55:08.214703Z","iopub.status.idle":"2023-11-15T13:55:10.818748Z","shell.execute_reply.started":"2023-11-15T13:55:08.214658Z","shell.execute_reply":"2023-11-15T13:55:10.817928Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class CEDiceLoss(nn.Module):\n    def __init__(self, weights) -> None:\n        super(CEDiceLoss, self).__init__()\n        self.eps: float = 1e-6\n        self.weights: torch.Tensor = weights\n\n    def forward(\n            self,\n            input: torch.Tensor,\n            target: torch.Tensor) -> torch.Tensor:\n        if not torch.is_tensor(input):\n            raise TypeError(\"Input type is not a torch.Tensor. Got {}\"\n                            .format(type(input)))\n        if not len(input.shape) == 4:\n            raise ValueError(\"Invalid input shape, we expect BxNxHxW. Got: {}\"\n                             .format(input.shape))\n        if not input.shape[-2:] == target.shape[-2:]:\n            raise ValueError(\"input and target shapes must be the same. Got: {}\"\n                             .format(input.shape, input.shape))\n        if not input.device == target.device:\n            raise ValueError(\n                \"input and target must be in the same device. Got: {}\" .format(\n                    input.device, target.device))\n        if not self.weights.shape[1] == input.shape[1]:\n            raise ValueError(\"The number of weights must equal the number of classes\")\n        if not torch.sum(self.weights).item() == 1:\n            raise ValueError(\"The sum of all weights must equal 1\")\n            \n        # cross entropy loss\n        celoss = nn.CrossEntropyLoss(self.weights)(input, target)\n        \n        # compute softmax over the classes axis\n        input_soft = F.softmax(input, dim=1)\n\n        # create the labels one hot tensor\n        target_one_hot = one_hot(target, num_classes=input.shape[1],\n                                 device=input.device, dtype=input.dtype)\n\n        # compute the actual dice score\n        dims = (2, 3)\n        intersection = torch.sum(input_soft * target_one_hot, dims)\n        cardinality = torch.sum(input_soft + target_one_hot, dims)\n\n        dice_score = 2. * intersection / (cardinality + self.eps)\n        \n        dice_score = torch.sum(dice_score * self.weights, dim=1)\n        \n        return torch.mean(1. - dice_score) + celoss","metadata":{"execution":{"iopub.status.busy":"2023-11-15T13:55:49.473105Z","iopub.execute_input":"2023-11-15T13:55:49.473469Z","iopub.status.idle":"2023-11-15T13:55:49.485640Z","shell.execute_reply.started":"2023-11-15T13:55:49.473437Z","shell.execute_reply":"2023-11-15T13:55:49.484792Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Train function for each epoch\ndef train(train_dataloader, valid_dataloader,learing_rate_scheduler, epoch, display_step):\n    print(f\"Start epoch #{epoch+1}, learning rate for this epoch: {learing_rate_scheduler.get_last_lr()}\")\n    start_time = time.time()\n    train_loss_epoch = 0\n    test_loss_epoch = 0\n    last_loss = 999999999\n    model.train()\n    for i, (data,targets) in enumerate(train_dataloader):\n        \n        # Load data into GPU\n        data, targets = data.to(device), targets.to(device)\n\n        optimizer.zero_grad()\n        outputs = model(data)\n\n        # Backpropagation, compute gradients\n        loss = loss_function(outputs, targets.long())\n        loss.backward()\n\n        # Apply gradients\n        optimizer.step()\n        \n        # Save loss\n        train_loss_epoch += loss.item()\n        if (i+1) % display_step == 0:\n#             accuracy = float(test(test_loader))\n            print('Train Epoch: {} [{}/{} ({}%)]\\tLoss: {:.4f}'.format(\n                epoch + 1, (i+1) * len(data), len(train_dataloader.dataset), 100 * (i+1) * len(data) / len(train_dataloader.dataset), \n                loss.item()))\n                  \n    print(f\"Done epoch #{epoch+1}, time for this epoch: {time.time()-start_time}s\")\n    train_loss_epoch/= (i + 1)\n    \n    # Evaluate the validation set\n    model.eval()\n    with torch.no_grad():\n        for data, target in valid_dataloader:\n            data, target = data.to(device), target.to(device)\n            test_output = model(data)\n            test_loss = loss_function(test_output, target)\n            test_loss_epoch += test_loss.item()\n            \n    test_loss_epoch/= (i+1)\n    \n    return train_loss_epoch , test_loss_epoch","metadata":{"execution":{"iopub.status.busy":"2023-11-15T13:56:19.775731Z","iopub.execute_input":"2023-11-15T13:56:19.776595Z","iopub.status.idle":"2023-11-15T13:56:19.786873Z","shell.execute_reply.started":"2023-11-15T13:56:19.776562Z","shell.execute_reply":"2023-11-15T13:56:19.785832Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Test function\ndef test(dataloader):\n    test_loss = 0\n    correct = 0\n    with torch.no_grad():\n        for i, (data, targets) in enumerate(dataloader):\n            data, targets = data.to(device), targets.to(device)\n            outputs = model(data)\n            _, pred = torch.max(outputs, 1)\n            test_loss += targets.size(0)\n            correct += torch.sum(pred == targets).item()\n    return 100.0 * correct / test_loss","metadata":{"execution":{"iopub.status.busy":"2023-11-15T15:15:24.474203Z","iopub.execute_input":"2023-11-15T15:15:24.474858Z","iopub.status.idle":"2023-11-15T15:15:24.481684Z","shell.execute_reply.started":"2023-11-15T15:15:24.474823Z","shell.execute_reply":"2023-11-15T15:15:24.480431Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.to(device)","metadata":{"execution":{"iopub.status.busy":"2023-11-15T13:57:49.612535Z","iopub.execute_input":"2023-11-15T13:57:49.612937Z","iopub.status.idle":"2023-11-15T13:57:54.159773Z","shell.execute_reply.started":"2023-11-15T13:57:49.612905Z","shell.execute_reply":"2023-11-15T13:57:54.158877Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"weights = torch.Tensor([[0.4, 0.55, 0.05]]).cuda()\nloss_function = CEDiceLoss(weights)\n\n# Define the optimizer (Adam optimizer)\noptimizer = optim.Adam(params=model.parameters(), lr=learning_rate)\n#optimizer.load_state_dict(checkpoint['optimizer'])\n\n# Learning rate scheduler\nlearing_rate_scheduler = lr_scheduler.StepLR(optimizer, step_size=4, gamma=0.6)","metadata":{"execution":{"iopub.status.busy":"2023-11-15T13:58:29.500995Z","iopub.execute_input":"2023-11-15T13:58:29.501889Z","iopub.status.idle":"2023-11-15T13:58:29.508755Z","shell.execute_reply.started":"2023-11-15T13:58:29.501854Z","shell.execute_reply":"2023-11-15T13:58:29.507742Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def save_model(model, optimizer, path):\n    checkpoint = {\n        \"model\": model.state_dict(),\n        \"optimizer\": optimizer.state_dict(),\n    }\n    torch.save(checkpoint, path)\n\ndef load_model(model, optimizer, path):\n    checkpoint = torch.load(path)\n    model.load_state_dict(checkpoint[\"model\"])\n    optimizer.load_state_dict(checkpoint['optimizer'])\n    return model, optimizer","metadata":{"execution":{"iopub.status.busy":"2023-11-15T14:07:11.252632Z","iopub.execute_input":"2023-11-15T14:07:11.253394Z","iopub.status.idle":"2023-11-15T14:07:11.260524Z","shell.execute_reply.started":"2023-11-15T14:07:11.253358Z","shell.execute_reply":"2023-11-15T14:07:11.259644Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"wandb.login(\n    # set the wandb project where this run will be logged\n#     project= \"PolypSegment\", \n    key = \"79c3d54bdf408d7c5b81da33056d3f33bf9fd715\",\n)\nwandb.init(\n    project = \"PolypSegment\"\n)\n# Training loop\ntrain_loss_array = []\ntest_loss_array = []\nlast_loss = 9999999999999\nfor epoch in range(epochs):\n    train_loss_epoch = 0\n    test_loss_epoch = 0\n    (train_loss_epoch, test_loss_epoch) = train(train_dataloader, \n                                              valid_dataloader, \n                                              learing_rate_scheduler, epoch, display_step)\n    \n    if test_loss_epoch < last_loss:\n        save_model(model, optimizer, checkpoint_path)\n        last_loss = test_loss_epoch\n        \n    learing_rate_scheduler.step()\n    train_loss_array.append(train_loss_epoch)\n    test_loss_array.append(test_loss_epoch)\n    wandb.log({\"Train loss\": train_loss_epoch, \"Valid loss\": test_loss_epoch})\n#     train_accuracy.append(test(train_loader))\n#     valid_accuracy.append(test(test_loader))\n#     print(\"Epoch {}: loss: {:.4f}, train accuracy: {:.4f}, valid accuracy:{:.4f}\".format(epoch + 1, \n#                                         train_loss_array[-1], train_accuracy[-1], valid_accuracy[-1]))","metadata":{"execution":{"iopub.status.busy":"2023-11-15T14:07:19.436553Z","iopub.execute_input":"2023-11-15T14:07:19.436953Z","iopub.status.idle":"2023-11-15T15:12:34.331823Z","shell.execute_reply.started":"2023-11-15T14:07:19.436920Z","shell.execute_reply":"2023-11-15T15:12:34.330729Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.rcParams['figure.dpi'] = 90\nplt.rcParams['figure.figsize'] = (6, 4)\nepochs_array = range(epochs)","metadata":{"execution":{"iopub.status.busy":"2023-11-15T15:13:30.550190Z","iopub.execute_input":"2023-11-15T15:13:30.550932Z","iopub.status.idle":"2023-11-15T15:13:30.555586Z","shell.execute_reply.started":"2023-11-15T15:13:30.550897Z","shell.execute_reply":"2023-11-15T15:13:30.554534Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Plot Training and Test loss\nplt.plot(epochs_array, train_loss_array, 'g', label='Training loss')\nplt.plot(epochs_array, test_loss_array, 'b', label='Test loss')\nplt.title('Training and Test loss')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.legend()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-11-15T15:40:15.368067Z","iopub.execute_input":"2023-11-15T15:40:15.368486Z","iopub.status.idle":"2023-11-15T15:40:15.693504Z","shell.execute_reply.started":"2023-11-15T15:40:15.368454Z","shell.execute_reply":"2023-11-15T15:40:15.692572Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for i, (data, label) in enumerate(train_dataloader):\n    img = data\n    mask = label\n    break","metadata":{"execution":{"iopub.status.busy":"2023-11-15T15:41:30.799075Z","iopub.execute_input":"2023-11-15T15:41:30.799825Z","iopub.status.idle":"2023-11-15T15:41:31.159468Z","shell.execute_reply.started":"2023-11-15T15:41:30.799792Z","shell.execute_reply":"2023-11-15T15:41:31.158603Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig, arr = plt.subplots(4, 3, figsize=(16, 12))\narr[0][0].set_title('Image')\narr[0][1].set_title('Segmentation')\narr[0][2].set_title('Predict')\n\nmodel.eval()\nwith torch.no_grad():\n    predict = model(img.to(device))\n\nfor i in range(4):\n    arr[i][0].imshow(img[i].permute(1, 2, 0));\n    \n    arr[i][1].imshow(F.one_hot(mask[i]).float())\n    \n    arr[i][2].imshow(F.one_hot(torch.argmax(predict[i], 0).cpu()).float())","metadata":{"execution":{"iopub.status.busy":"2023-11-15T15:45:29.037318Z","iopub.execute_input":"2023-11-15T15:45:29.038240Z","iopub.status.idle":"2023-11-15T15:45:31.940583Z","shell.execute_reply.started":"2023-11-15T15:45:29.038202Z","shell.execute_reply":"2023-11-15T15:45:31.939670Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"transform = Compose([Resize((512,512), interpolation=InterpolationMode.BILINEAR),\n                     PILToTensor()])","metadata":{"execution":{"iopub.status.busy":"2023-11-15T15:55:54.746263Z","iopub.execute_input":"2023-11-15T15:55:54.747275Z","iopub.status.idle":"2023-11-15T15:55:54.751948Z","shell.execute_reply.started":"2023-11-15T15:55:54.747236Z","shell.execute_reply":"2023-11-15T15:55:54.750832Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class UNetTestDataClass(Dataset):\n    def __init__(self, images_path, transform):\n        super(UNetTestDataClass, self).__init__()\n        \n        images_list = os.listdir(images_path)\n        images_list = [images_path+i for i in images_list]\n        \n        self.images_list = images_list\n        self.transform = transform\n        \n    def __getitem__(self, index):\n        img_path = self.images_list[index]\n        data = Image.open(img_path)\n        h = data.size[1]\n        w = data.size[0]\n        data = self.transform(data) / 255        \n        return data, img_path, h, w\n    \n    def __len__(self):\n        return len(self.images_list)","metadata":{"execution":{"iopub.status.busy":"2023-11-15T15:55:57.965812Z","iopub.execute_input":"2023-11-15T15:55:57.966186Z","iopub.status.idle":"2023-11-15T15:55:57.973550Z","shell.execute_reply.started":"2023-11-15T15:55:57.966156Z","shell.execute_reply":"2023-11-15T15:55:57.972669Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"path = '/kaggle/input/bkai-igh-neopolyp/test/test/'\nunet_test_dataset = UNetTestDataClass(path, transform)\ntest_dataloader = DataLoader(unet_test_dataset, batch_size=8, shuffle=True)","metadata":{"execution":{"iopub.status.busy":"2023-11-15T15:56:00.391145Z","iopub.execute_input":"2023-11-15T15:56:00.392090Z","iopub.status.idle":"2023-11-15T15:56:00.398684Z","shell.execute_reply.started":"2023-11-15T15:56:00.392055Z","shell.execute_reply":"2023-11-15T15:56:00.397828Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for i, (data, path, h, w) in enumerate(test_dataloader):\n    img = data\n    break","metadata":{"execution":{"iopub.status.busy":"2023-11-15T15:56:01.790993Z","iopub.execute_input":"2023-11-15T15:56:01.791703Z","iopub.status.idle":"2023-11-15T15:56:01.963801Z","shell.execute_reply.started":"2023-11-15T15:56:01.791663Z","shell.execute_reply":"2023-11-15T15:56:01.962820Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig, arr = plt.subplots(5, 2, figsize=(16, 12))\narr[0][0].set_title('Image');\narr[0][1].set_title('Predict');\n\nmodel.eval()\nwith torch.no_grad():\n    predict = model(img.to(device))\n\nfor i in range(5):\n    arr[i][0].imshow(img[i].permute(1, 2, 0));\n    arr[i][1].imshow(F.one_hot(torch.argmax(predict[i], 0).cpu()).float())","metadata":{"execution":{"iopub.status.busy":"2023-11-15T15:56:05.243072Z","iopub.execute_input":"2023-11-15T15:56:05.243534Z","iopub.status.idle":"2023-11-15T15:56:07.457999Z","shell.execute_reply.started":"2023-11-15T15:56:05.243495Z","shell.execute_reply":"2023-11-15T15:56:07.457099Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.eval()\nif not os.path.isdir(\"/kaggle/working/predicted_masks\"):\n    os.mkdir(\"/kaggle/working/predicted_masks\")\nfor _, (img, path, H, W) in enumerate(test_dataloader):\n    a = path\n    b = img\n    h = H\n    w = W\n    \n    with torch.no_grad():\n        predicted_mask = model(b.to(device))\n    for i in range(len(a)):\n        image_id = a[i].split('/')[-1].split('.')[0]\n        filename = image_id + \".png\"\n        mask2img = Resize((h[i].item(), w[i].item()), interpolation=InterpolationMode.NEAREST)(ToPILImage()(F.one_hot(torch.argmax(predicted_mask[i], 0)).permute(2, 0, 1).float()))\n        mask2img.save(os.path.join(\"/kaggle/working/predicted_masks/\", filename))","metadata":{"execution":{"iopub.status.busy":"2023-11-15T15:56:13.376582Z","iopub.execute_input":"2023-11-15T15:56:13.377001Z","iopub.status.idle":"2023-11-15T15:56:34.162683Z","shell.execute_reply.started":"2023-11-15T15:56:13.376967Z","shell.execute_reply":"2023-11-15T15:56:34.161639Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def rle_to_string(runs):\n    return ' '.join(str(x) for x in runs)\n\ndef rle_encode_one_mask(mask):\n    pixels = mask.flatten()\n    pixels[pixels > 0] = 255\n    use_padding = False\n    if pixels[0] or pixels[-1]:\n        use_padding = True\n        pixel_padded = np.zeros([len(pixels) + 2], dtype=pixels.dtype)\n        pixel_padded[1:-1] = pixels\n        pixels = pixel_padded\n    \n    rle = np.where(pixels[1:] != pixels[:-1])[0] + 2\n    if use_padding:\n        rle = rle - 1\n    rle[1::2] = rle[1::2] - rle[:-1:2]\n    return rle_to_string(rle)\n\ndef mask2string(dir):\n    ## mask --> string\n    strings = []\n    ids = []\n    ws, hs = [[] for i in range(2)]\n    for image_id in os.listdir(dir):\n        id = image_id.split('.')[0]\n        path = os.path.join(dir, image_id)\n        print(path)\n        img = cv2.imread(path)[:,:,::-1]\n        h, w = img.shape[0], img.shape[1]\n        for channel in range(2):\n            ws.append(w)\n            hs.append(h)\n            ids.append(f'{id}_{channel}')\n            string = rle_encode_one_mask(img[:,:,channel])\n            strings.append(string)\n    r = {\n        'ids': ids,\n        'strings': strings,\n    }\n    return r\n\n\nMASK_DIR_PATH = '/kaggle/working/predicted_masks' # change this to the path to your output mask folder\ndir = MASK_DIR_PATH\nres = mask2string(dir)\ndf = pd.DataFrame(columns=['Id', 'Expected'])\ndf['Id'] = res['ids']\ndf['Expected'] = res['strings']\ndf.to_csv(r'submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2023-11-15T15:56:37.109151Z","iopub.execute_input":"2023-11-15T15:56:37.109551Z","iopub.status.idle":"2023-11-15T15:56:40.061955Z","shell.execute_reply.started":"2023-11-15T15:56:37.109514Z","shell.execute_reply":"2023-11-15T15:56:40.061004Z"},"trusted":true},"execution_count":null,"outputs":[]}]}