{"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":30588,"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-17T06:58:17.403537Z","iopub.execute_input":"2023-11-17T06:58:17.403801Z","iopub.status.idle":"2023-11-17T06:58:44.132457Z","shell.execute_reply.started":"2023-11-17T06:58:17.403777Z","shell.execute_reply":"2023-11-17T06:58:44.131321Z"},"trusted":true},"outputs":[],"execution_count":null},{"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":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-11-17T06:58:44.134696Z","iopub.execute_input":"2023-11-17T06:58:44.135076Z","iopub.status.idle":"2023-11-17T06:58:51.935231Z","shell.execute_reply.started":"2023-11-17T06:58:44.135036Z","shell.execute_reply":"2023-11-17T06:58:51.934509Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# !pip install ternausnet","metadata":{"execution":{"iopub.status.busy":"2023-11-17T06:58:51.936384Z","iopub.execute_input":"2023-11-17T06:58:51.93671Z","iopub.status.idle":"2023-11-17T06:58:51.940781Z","shell.execute_reply.started":"2023-11-17T06:58:51.936678Z","shell.execute_reply":"2023-11-17T06:58:51.939801Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# import ternausnet","metadata":{"execution":{"iopub.status.busy":"2023-11-17T06:58:51.94388Z","iopub.execute_input":"2023-11-17T06:58:51.944436Z","iopub.status.idle":"2023-11-17T06:58:51.955186Z","shell.execute_reply.started":"2023-11-17T06:58:51.944404Z","shell.execute_reply":"2023-11-17T06:58:51.954294Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# print(dir(ternausnet.models.models))","metadata":{"execution":{"iopub.status.busy":"2023-11-17T06:58:51.956377Z","iopub.execute_input":"2023-11-17T06:58:51.956711Z","iopub.status.idle":"2023-11-17T06:58:51.966549Z","shell.execute_reply.started":"2023-11-17T06:58:51.956678Z","shell.execute_reply":"2023-11-17T06:58:51.965651Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# from ternausnet.models import UNet16","metadata":{"execution":{"iopub.status.busy":"2023-11-17T06:58:51.967671Z","iopub.execute_input":"2023-11-17T06:58:51.967949Z","iopub.status.idle":"2023-11-17T06:58:51.977207Z","shell.execute_reply.started":"2023-11-17T06:58:51.967926Z","shell.execute_reply":"2023-11-17T06:58:51.976507Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!nvidia-smi -L","metadata":{"execution":{"iopub.status.busy":"2023-11-17T06:58:51.978211Z","iopub.execute_input":"2023-11-17T06:58:51.978519Z","iopub.status.idle":"2023-11-17T06:58:52.987969Z","shell.execute_reply.started":"2023-11-17T06:58:51.978495Z","shell.execute_reply":"2023-11-17T06:58:52.986728Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\ndevice","metadata":{"execution":{"iopub.status.busy":"2023-11-17T06:58:52.989897Z","iopub.execute_input":"2023-11-17T06:58:52.990252Z","iopub.status.idle":"2023-11-17T06:58:53.069598Z","shell.execute_reply.started":"2023-11-17T06:58:52.990217Z","shell.execute_reply":"2023-11-17T06:58:53.068646Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install segmentation-models-pytorch","metadata":{"execution":{"iopub.status.busy":"2023-11-17T06:58:53.070852Z","iopub.execute_input":"2023-11-17T06:58:53.071174Z","iopub.status.idle":"2023-11-17T06:59:12.557229Z","shell.execute_reply.started":"2023-11-17T06:58:53.071149Z","shell.execute_reply":"2023-11-17T06:59:12.556308Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import segmentation_models_pytorch as smp\n\nmodel = smp.UnetPlusPlus(\n    encoder_name=\"resnet34\",        \n    encoder_weights=\"imagenet\",     \n    in_channels=3,                  \n    classes=3     \n)","metadata":{"execution":{"iopub.status.busy":"2023-11-17T06:59:12.562633Z","iopub.execute_input":"2023-11-17T06:59:12.562928Z","iopub.status.idle":"2023-11-17T06:59:15.654018Z","shell.execute_reply.started":"2023-11-17T06:59:12.5629Z","shell.execute_reply":"2023-11-17T06:59:15.653136Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Parameters","metadata":{}},{"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 = 50\n\n# Hyperparameters for training \nlearning_rate = 1e-04\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-17T06:59:15.655206Z","iopub.execute_input":"2023-11-17T06:59:15.655509Z","iopub.status.idle":"2023-11-17T06:59:15.662313Z","shell.execute_reply.started":"2023-11-17T06:59:15.655484Z","shell.execute_reply":"2023-11-17T06:59:15.661239Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Dataloader","metadata":{}},{"cell_type":"code","source":"transform = Compose([Resize((256, 256), interpolation=InterpolationMode.BILINEAR),\n                     PILToTensor()])","metadata":{"execution":{"iopub.status.busy":"2023-11-17T06:59:15.663559Z","iopub.execute_input":"2023-11-17T06:59:15.663975Z","iopub.status.idle":"2023-11-17T06:59:15.676653Z","shell.execute_reply.started":"2023-11-17T06:59:15.663942Z","shell.execute_reply":"2023-11-17T06:59:15.675752Z"},"trusted":true},"outputs":[],"execution_count":null},{"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-17T06:59:15.678003Z","iopub.execute_input":"2023-11-17T06:59:15.678679Z","iopub.status.idle":"2023-11-17T06:59:15.687769Z","shell.execute_reply.started":"2023-11-17T06:59:15.678619Z","shell.execute_reply":"2023-11-17T06:59:15.68696Z"},"trusted":true},"outputs":[],"execution_count":null},{"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-17T06:59:15.689015Z","iopub.execute_input":"2023-11-17T06:59:15.689334Z","iopub.status.idle":"2023-11-17T06:59:15.700599Z","shell.execute_reply.started":"2023-11-17T06:59:15.689309Z","shell.execute_reply":"2023-11-17T06:59:15.699888Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"unet_dataset = UNetDataClass(images_path, masks_path, transform)","metadata":{"execution":{"iopub.status.busy":"2023-11-17T06:59:15.701597Z","iopub.execute_input":"2023-11-17T06:59:15.701858Z","iopub.status.idle":"2023-11-17T06:59:15.824753Z","shell.execute_reply.started":"2023-11-17T06:59:15.701828Z","shell.execute_reply":"2023-11-17T06:59:15.824019Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_size = 0.9\nvalid_size = 0.1","metadata":{"execution":{"iopub.status.busy":"2023-11-17T06:59:15.825811Z","iopub.execute_input":"2023-11-17T06:59:15.826085Z","iopub.status.idle":"2023-11-17T06:59:15.830388Z","shell.execute_reply.started":"2023-11-17T06:59:15.826061Z","shell.execute_reply":"2023-11-17T06:59:15.829491Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"torch.manual_seed(42)","metadata":{"execution":{"iopub.status.busy":"2023-11-17T06:59:15.83156Z","iopub.execute_input":"2023-11-17T06:59:15.831846Z","iopub.status.idle":"2023-11-17T06:59:15.850463Z","shell.execute_reply.started":"2023-11-17T06:59:15.83182Z","shell.execute_reply":"2023-11-17T06:59:15.849589Z"},"trusted":true},"outputs":[],"execution_count":null},{"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-17T06:59:15.851743Z","iopub.execute_input":"2023-11-17T06:59:15.852426Z","iopub.status.idle":"2023-11-17T06:59:15.865139Z","shell.execute_reply.started":"2023-11-17T06:59:15.852392Z","shell.execute_reply":"2023-11-17T06:59:15.864325Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_dataloader = DataLoader(train_set, batch_size=batch_size, shuffle=True)\nvalid_dataloader = DataLoader(valid_set, batch_size=batch_size, shuffle=True)","metadata":{"execution":{"iopub.status.busy":"2023-11-17T06:59:15.866479Z","iopub.execute_input":"2023-11-17T06:59:15.866775Z","iopub.status.idle":"2023-11-17T06:59:15.871612Z","shell.execute_reply.started":"2023-11-17T06:59:15.866752Z","shell.execute_reply":"2023-11-17T06:59:15.870674Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Data Augmentation","metadata":{}},{"cell_type":"code","source":"from albumentations import (\n    Compose,\n    RandomRotate90,\n    Flip,\n    Transpose,\n    ElasticTransform,\n    GridDistortion,\n    OpticalDistortion,\n    RandomBrightnessContrast,\n    HorizontalFlip,\n    VerticalFlip,\n    RandomGamma,\n    RGBShift,\n)","metadata":{"execution":{"iopub.status.busy":"2023-11-17T06:59:15.873139Z","iopub.execute_input":"2023-11-17T06:59:15.87357Z","iopub.status.idle":"2023-11-17T06:59:17.815922Z","shell.execute_reply.started":"2023-11-17T06:59:15.873538Z","shell.execute_reply":"2023-11-17T06:59:17.815111Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"augmentation = Compose([\n    HorizontalFlip(p=0.5),\n    VerticalFlip(p=0.5),\n    RandomGamma (gamma_limit=(70, 130), eps=None, always_apply=False, p=0.2),\n    RGBShift(p=0.3, r_shift_limit=10, g_shift_limit=10, b_shift_limit=10),\n])","metadata":{"execution":{"iopub.status.busy":"2023-11-17T06:59:17.817072Z","iopub.execute_input":"2023-11-17T06:59:17.817572Z","iopub.status.idle":"2023-11-17T06:59:17.823397Z","shell.execute_reply.started":"2023-11-17T06:59:17.817532Z","shell.execute_reply":"2023-11-17T06:59:17.822472Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class SegDataClass(Dataset):\n    def __init__(self, images_path, masks_path, transform=None, augmentation=None):\n        super(SegDataClass, self).__init__()\n        \n        images_list = os.listdir(images_path)\n        masks_list = os.listdir(masks_path)\n        \n        images_list = [os.path.join(images_path, image_name) for image_name in images_list]\n        masks_list = [os.path.join(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        self.augmentation = augmentation\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        # Augmentation\n        if self.augmentation:\n            augmented = self.augmentation(image=np.array(data), mask=np.array(label))\n            data = Image.fromarray(augmented['image'])\n            label = Image.fromarray(augmented['mask'])\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        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)\n\n\n# transform = transforms.ToTensor()\naug_dataset = SegDataClass(images_path, masks_path, transform=transform, augmentation=augmentation)","metadata":{"execution":{"iopub.status.busy":"2023-11-17T06:59:17.824707Z","iopub.execute_input":"2023-11-17T06:59:17.825533Z","iopub.status.idle":"2023-11-17T06:59:17.851671Z","shell.execute_reply.started":"2023-11-17T06:59:17.825507Z","shell.execute_reply":"2023-11-17T06:59:17.85077Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"torch.manual_seed(42)","metadata":{"execution":{"iopub.status.busy":"2023-11-17T06:59:17.852975Z","iopub.execute_input":"2023-11-17T06:59:17.853414Z","iopub.status.idle":"2023-11-17T06:59:17.860551Z","shell.execute_reply.started":"2023-11-17T06:59:17.853381Z","shell.execute_reply":"2023-11-17T06:59:17.859663Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_aug_set, valid_aug_set = random_split(aug_dataset, \n                                    [int(train_size * len(aug_dataset)) , \n                                     int(valid_size * len(aug_dataset))])","metadata":{"execution":{"iopub.status.busy":"2023-11-17T06:59:17.861729Z","iopub.execute_input":"2023-11-17T06:59:17.862016Z","iopub.status.idle":"2023-11-17T06:59:17.870503Z","shell.execute_reply.started":"2023-11-17T06:59:17.861993Z","shell.execute_reply":"2023-11-17T06:59:17.869665Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from torch.utils.data import ConcatDataset\n# combined_dataset = ConcatDataset([aug_dataset, train_set])\n# train_dataloader = DataLoader(combined_dataset, batch_size=batch_size, shuffle=True)\ntrain_dataloader = DataLoader(train_aug_set, batch_size=batch_size, shuffle=True)","metadata":{"execution":{"iopub.status.busy":"2023-11-17T06:59:17.871569Z","iopub.execute_input":"2023-11-17T06:59:17.871859Z","iopub.status.idle":"2023-11-17T06:59:17.887216Z","shell.execute_reply.started":"2023-11-17T06:59:17.871835Z","shell.execute_reply":"2023-11-17T06:59:17.886216Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Model","metadata":{}},{"cell_type":"markdown","source":"**Residual Block**","metadata":{}},{"cell_type":"code","source":"class ResidualBlock(nn.Module):\n    def __init__(self, in_channels, out_channels):\n        super(ResidualBlock, self).__init__()\n\n        self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1)\n        self.bn1 = nn.BatchNorm2d(out_channels)\n        self.relu = nn.ReLU(inplace=True)\n\n        self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1)\n        self.bn2 = nn.BatchNorm2d(out_channels)\n        \n        self.bn3 = nn.BatchNorm2d(out_channels)\n        \n        self.dropout = nn.Dropout(p=0.3)\n\n    def forward(self, x):\n        residual = x\n\n        out = self.conv1(x)\n        out = self.bn1(out)\n        out = self.relu(out)\n        \n        out = self.dropout(out)\n\n        out = self.conv2(out)\n        out = self.bn2(out)\n        \n        residual = self.conv1(residual)\n        residual = self.bn3(residual)\n\n        out += residual  \n        out = self.relu(out)\n\n        return out","metadata":{"execution":{"iopub.status.busy":"2023-11-17T06:59:17.88858Z","iopub.execute_input":"2023-11-17T06:59:17.889171Z","iopub.status.idle":"2023-11-17T06:59:17.898969Z","shell.execute_reply.started":"2023-11-17T06:59:17.88914Z","shell.execute_reply":"2023-11-17T06:59:17.898307Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"**Encoder Block**","metadata":{}},{"cell_type":"code","source":"class encoder_block(nn.Module):\n    def __init__(self, in_channels, out_channels):\n        super(encoder_block, self).__init__()\n        \n        self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding='same')\n        self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding='same')\n        \n        self.bn1 = nn.BatchNorm2d(out_channels)\n        self.bn2 = nn.BatchNorm2d(out_channels)\n        \n        self.relu = nn.ReLU()\n        self.dropout = nn.Dropout(p=0.3)\n        self.max_pool = nn.MaxPool2d(kernel_size=2, stride=2)\n        \n    def forward(self, x):\n        x = self.conv1(x)\n        x = self.bn1(x)\n        x = self.relu(x)\n        \n        x = self.dropout(x)\n        \n        x = self.conv2(x)\n        x = self.bn2(x)\n        x = self.relu(x)\n        \n        next_layer = self.max_pool(x)\n        skip_layer = x\n        \n        return next_layer, skip_layer","metadata":{"execution":{"iopub.status.busy":"2023-11-17T06:59:17.900112Z","iopub.execute_input":"2023-11-17T06:59:17.900449Z","iopub.status.idle":"2023-11-17T06:59:17.910294Z","shell.execute_reply.started":"2023-11-17T06:59:17.900416Z","shell.execute_reply":"2023-11-17T06:59:17.909415Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class res_encoder_block(nn.Module):\n    def __init__(self, in_channels, out_channels):\n        super(res_encoder_block, self).__init__()\n        \n        self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding='same')\n        self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding='same')\n        \n        self.bn1 = nn.BatchNorm2d(out_channels)\n        self.bn2 = nn.BatchNorm2d(out_channels)\n        self.bn3 = nn.BatchNorm2d(out_channels)\n        \n        self.relu = nn.ReLU()\n        self.dropout = nn.Dropout(p=0.3)\n        self.max_pool = nn.MaxPool2d(kernel_size=2, stride=2)\n        \n    def forward(self, x):\n        residual = x\n        \n        x = self.conv1(x)\n        x = self.bn1(x)\n        x = self.relu(x)\n        \n        x = self.dropout(x)\n        \n        x = self.conv2(x)\n        x = self.bn2(x)\n        \n        residual = self.conv1(residual)\n        residual = self.bn3(residual)\n        \n        \n        x += residual  \n        x = self.relu(x)\n        \n        next_layer = self.max_pool(x)\n        skip_layer = x\n        \n        return next_layer, skip_layer","metadata":{"execution":{"iopub.status.busy":"2023-11-17T06:59:17.918392Z","iopub.execute_input":"2023-11-17T06:59:17.918668Z","iopub.status.idle":"2023-11-17T06:59:17.928155Z","shell.execute_reply.started":"2023-11-17T06:59:17.918646Z","shell.execute_reply":"2023-11-17T06:59:17.927397Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"**Decoder block**","metadata":{}},{"cell_type":"code","source":"class decoder_block(nn.Module):\n    def __init__(self, in_channels, out_channels):\n        super(decoder_block, self).__init__()\n        \n        self.transpose_conv = nn.ConvTranspose2d(in_channels, out_channels, kernel_size=2, stride=2)\n        \n        self.conv1 = nn.Conv2d(2 * out_channels, out_channels, kernel_size=3, stride=1, padding='same')\n        self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding='same')\n        \n        self.bn1 = nn.BatchNorm2d(out_channels)\n        self.bn2 = nn.BatchNorm2d(out_channels)\n        \n        self.relu = nn.ReLU() \n        self.dropout = nn.Dropout(p=0.3)\n    \n    def forward(self, x, skip_layer):\n        x = self.transpose_conv(x)\n        x = torch.cat([x, skip_layer], axis=1)\n        \n        x = self.conv1(x)\n        x = self.bn1(x)\n        x = self.relu(x)\n        \n        x = self.dropout(x)\n        \n        x = self.conv2(x)\n        x = self.bn2(x)\n        x = self.relu(x)\n        \n        return x","metadata":{"execution":{"iopub.status.busy":"2023-11-17T06:59:17.929206Z","iopub.execute_input":"2023-11-17T06:59:17.929549Z","iopub.status.idle":"2023-11-17T06:59:17.944977Z","shell.execute_reply.started":"2023-11-17T06:59:17.929525Z","shell.execute_reply":"2023-11-17T06:59:17.944174Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class res_decoder_block(nn.Module):\n    def __init__(self, in_channels, out_channels):\n        super(res_decoder_block, self).__init__()\n        \n        self.transpose_conv = nn.ConvTranspose2d(in_channels, out_channels, kernel_size=2, stride=2)\n        \n        self.conv1 = nn.Conv2d(2 * out_channels, out_channels, kernel_size=3, stride=1, padding='same')\n        self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding='same')\n        \n        self.bn1 = nn.BatchNorm2d(out_channels)\n        self.bn2 = nn.BatchNorm2d(out_channels)\n        \n        self.bn3 = nn.BatchNorm2d(out_channels)\n        \n        self.relu = nn.ReLU() \n        self.dropout = nn.Dropout(p=0.3)\n    \n    def forward(self, x, skip_layer):\n        x = self.transpose_conv(x)\n        x = torch.cat([x, skip_layer], axis=1)\n        \n        residual = x\n        \n        x = self.conv1(x)\n        x = self.bn1(x)\n        x = self.relu(x)\n        \n        x = self.dropout(x)\n        \n        x = self.conv2(x)\n        x = self.bn2(x)\n        \n        residual = self.conv1(residual)\n        residual = self.bn3(residual)\n        \n        x += residual\n        x = self.relu(x)\n        \n        return x","metadata":{"execution":{"iopub.status.busy":"2023-11-17T06:59:17.946321Z","iopub.execute_input":"2023-11-17T06:59:17.946569Z","iopub.status.idle":"2023-11-17T06:59:17.962816Z","shell.execute_reply.started":"2023-11-17T06:59:17.946548Z","shell.execute_reply":"2023-11-17T06:59:17.962064Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"**Bottle neck**","metadata":{}},{"cell_type":"code","source":"class bottleneck_block(nn.Module):\n    def __init__(self, in_channels, out_channels):\n        super(bottleneck_block, self).__init__()\n        \n        self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding='same')\n        self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding='same')\n        \n        self.bn1 = nn.BatchNorm2d(out_channels)\n        self.bn2 = nn.BatchNorm2d(out_channels)\n        \n        self.relu = nn.ReLU()\n        self.dropout = nn.Dropout(p=0.3)\n        \n    def forward(self, x):\n        x = self.conv1(x)\n        x = self.bn1(x)\n        x = self.relu(x)\n        \n        x = self.dropout(x)\n        \n        x = self.conv2(x)\n        x = self.bn2(x)\n        x = self.relu(x)\n        \n        return x","metadata":{"execution":{"iopub.status.busy":"2023-11-17T06:59:17.963898Z","iopub.execute_input":"2023-11-17T06:59:17.964149Z","iopub.status.idle":"2023-11-17T06:59:17.981957Z","shell.execute_reply.started":"2023-11-17T06:59:17.964128Z","shell.execute_reply":"2023-11-17T06:59:17.981089Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"**Unet model**","metadata":{}},{"cell_type":"code","source":"# UNet model\nclass UNet(nn.Module):\n    def __init__(self, n_class=3):\n        super(UNet, self).__init__()\n        # Encoder blocks\n        self.enc1 = encoder_block(3, 64)\n        self.enc2 = encoder_block(64, 128)\n        self.enc3 = res_encoder_block(128, 256)\n        self.enc4 = encoder_block(256, 512)\n        \n        # Bottleneck block\n        self.bottleneck = ResidualBlock(512, 1024)\n        \n        # Decoder blocks\n        self.dec1 = decoder_block(1024, 512)\n        self.dec2 = res_decoder_block(512, 256)\n        self.dec3 = decoder_block(256, 128)\n        self.dec4 = decoder_block(128, 64)\n        \n        # 1x1 convolution\n        self.out = nn.Conv2d(64, n_class, kernel_size=1, padding='same')\n        \n    def forward(self, image):\n        n1, s1 = self.enc1(image)\n        n2, s2 = self.enc2(n1)\n        n3, s3 = self.enc3(n2)\n        n4, s4 = self.enc4(n3)\n        \n        n5 = self.bottleneck(n4)\n        \n        n6 = self.dec1(n5, s4)\n        n7 = self.dec2(n6, s3)\n        n8 = self.dec3(n7, s2)\n        n9 = self.dec4(n8, s1)\n        \n        output = self.out(n9)\n        \n        return output","metadata":{"execution":{"iopub.status.busy":"2023-11-17T06:59:17.983238Z","iopub.execute_input":"2023-11-17T06:59:17.983638Z","iopub.status.idle":"2023-11-17T06:59:17.993918Z","shell.execute_reply.started":"2023-11-17T06:59:17.983605Z","shell.execute_reply":"2023-11-17T06:59:17.993137Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Loss function","metadata":{}},{"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\n#         return dice_score","metadata":{"execution":{"iopub.status.busy":"2023-11-17T06:59:17.9949Z","iopub.execute_input":"2023-11-17T06:59:17.995154Z","iopub.status.idle":"2023-11-17T06:59:18.012899Z","shell.execute_reply.started":"2023-11-17T06:59:17.995131Z","shell.execute_reply":"2023-11-17T06:59:18.012141Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Training","metadata":{}},{"cell_type":"markdown","source":"**Initialize weights**","metadata":{}},{"cell_type":"code","source":"def weights_init(model):\n    if isinstance(model, nn.Linear):\n        # Xavier Distribution\n        torch.nn.init.xavier_uniform_(model.weight)","metadata":{"execution":{"iopub.status.busy":"2023-11-17T06:59:18.014018Z","iopub.execute_input":"2023-11-17T06:59:18.014324Z","iopub.status.idle":"2023-11-17T06:59:18.029925Z","shell.execute_reply.started":"2023-11-17T06:59:18.014296Z","shell.execute_reply":"2023-11-17T06:59:18.028946Z"},"trusted":true},"outputs":[],"execution_count":null},{"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-17T06:59:18.030922Z","iopub.execute_input":"2023-11-17T06:59:18.03117Z","iopub.status.idle":"2023-11-17T06:59:18.04311Z","shell.execute_reply.started":"2023-11-17T06:59:18.031148Z","shell.execute_reply":"2023-11-17T06:59:18.042424Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"**Train model**","metadata":{}},{"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-17T06:59:18.044444Z","iopub.execute_input":"2023-11-17T06:59:18.04478Z","iopub.status.idle":"2023-11-17T06:59:18.058077Z","shell.execute_reply.started":"2023-11-17T06:59:18.04475Z","shell.execute_reply":"2023-11-17T06:59:18.057112Z"},"trusted":true},"outputs":[],"execution_count":null},{"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-17T06:59:18.059027Z","iopub.execute_input":"2023-11-17T06:59:18.059289Z","iopub.status.idle":"2023-11-17T06:59:18.074789Z","shell.execute_reply.started":"2023-11-17T06:59:18.059247Z","shell.execute_reply":"2023-11-17T06:59:18.074081Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# model = Unet(in_channels=3, num_classes = 3)\n\ntry:\n    checkpoint = torch.load(pretrained_path)\n\n    new_state_dict = OrderedDict()\n    for k, v in checkpoint['model'].items():\n        name = k[7:] # remove `module.`\n        new_state_dict[name] = v\n    # load params\n    model.load_state_dict(new_state_dict)\n    model = nn.DataParallel(model)\n    model.to(device)\nexcept:\n    model.apply(weights_init)\n    model = nn.DataParallel(model)\n    model.to(device)","metadata":{"execution":{"iopub.status.busy":"2023-11-17T06:59:18.075845Z","iopub.execute_input":"2023-11-17T06:59:18.076102Z","iopub.status.idle":"2023-11-17T06:59:23.010554Z","shell.execute_reply.started":"2023-11-17T06:59:18.07608Z","shell.execute_reply":"2023-11-17T06:59:23.009626Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{},"outputs":[],"execution_count":null},{"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)\ntry: \n    optimizer.load_state_dict(checkpoint['optimizer'])\nexcept:\n    pass\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-17T06:59:23.012209Z","iopub.execute_input":"2023-11-17T06:59:23.012585Z","iopub.status.idle":"2023-11-17T06:59:23.021254Z","shell.execute_reply.started":"2023-11-17T06:59:23.012556Z","shell.execute_reply":"2023-11-17T06:59:23.020485Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"save_model(model, optimizer, checkpoint_path)","metadata":{"execution":{"iopub.status.busy":"2023-11-17T06:59:23.022562Z","iopub.execute_input":"2023-11-17T06:59:23.02287Z","iopub.status.idle":"2023-11-17T06:59:23.238306Z","shell.execute_reply.started":"2023-11-17T06:59:23.022837Z","shell.execute_reply":"2023-11-17T06:59:23.237445Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"wandb.login(\n    # set the wandb project where this run will be logged\n#     project= \"PolypSegment\", \n    key = \"90b1c43eb0f9a3084ba785bb7f308f0f948dfb31\",\n)\nwandb.init(\n    project = \"IWillKillAll\"\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-17T06:59:23.239644Z","iopub.execute_input":"2023-11-17T06:59:23.240292Z","iopub.status.idle":"2023-11-17T07:16:22.158586Z","shell.execute_reply.started":"2023-11-17T06:59:23.240234Z","shell.execute_reply":"2023-11-17T07:16:22.157134Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# torch.cuda.empty_cache()","metadata":{"execution":{"iopub.status.busy":"2023-11-17T07:16:22.160453Z","iopub.execute_input":"2023-11-17T07:16:22.16083Z","iopub.status.idle":"2023-11-17T07:16:22.165938Z","shell.execute_reply.started":"2023-11-17T07:16:22.160794Z","shell.execute_reply":"2023-11-17T07:16:22.165016Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# save_model(model, optimizer, checkpoint_path)","metadata":{"execution":{"iopub.status.busy":"2023-11-17T07:16:22.167349Z","iopub.execute_input":"2023-11-17T07:16:22.167861Z","iopub.status.idle":"2023-11-17T07:16:22.187303Z","shell.execute_reply.started":"2023-11-17T07:16:22.167831Z","shell.execute_reply":"2023-11-17T07:16:22.186244Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# checkpoint = torch.load(pretrained_path)","metadata":{"execution":{"iopub.status.busy":"2023-11-17T07:16:22.188677Z","iopub.execute_input":"2023-11-17T07:16:22.189017Z","iopub.status.idle":"2023-11-17T07:16:22.218747Z","shell.execute_reply.started":"2023-11-17T07:16:22.188985Z","shell.execute_reply":"2023-11-17T07:16:22.217615Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# checkpoint = torch.load(checkpoint_path)","metadata":{"execution":{"iopub.status.busy":"2023-11-17T07:16:22.220069Z","iopub.execute_input":"2023-11-17T07:16:22.220452Z","iopub.status.idle":"2023-11-17T07:16:22.229925Z","shell.execute_reply.started":"2023-11-17T07:16:22.220402Z","shell.execute_reply":"2023-11-17T07:16:22.228906Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# for m in self.children():\n#     m.cuda()\n#     x = m(x)\n#     m.cpu()\n#     torch.cuda.empty_cache()","metadata":{"execution":{"iopub.status.busy":"2023-11-17T07:16:22.231089Z","iopub.execute_input":"2023-11-17T07:16:22.231442Z","iopub.status.idle":"2023-11-17T07:16:22.251284Z","shell.execute_reply.started":"2023-11-17T07:16:22.23141Z","shell.execute_reply":"2023-11-17T07:16:22.250402Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Plot the learning cure","metadata":{}},{"cell_type":"code","source":"# load_model(model, checkpoint)","metadata":{"execution":{"iopub.status.busy":"2023-11-17T07:16:22.252455Z","iopub.execute_input":"2023-11-17T07:16:22.252711Z","iopub.status.idle":"2023-11-17T07:16:22.264604Z","shell.execute_reply.started":"2023-11-17T07:16:22.252678Z","shell.execute_reply":"2023-11-17T07:16:22.263748Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# plt.rcParams['figure.dpi'] = 90\n# plt.rcParams['figure.figsize'] = (6, 4)\n# epochs_array = range(epochs)","metadata":{"execution":{"iopub.status.busy":"2023-11-17T07:16:22.268144Z","iopub.execute_input":"2023-11-17T07:16:22.268671Z","iopub.status.idle":"2023-11-17T07:16:22.276851Z","shell.execute_reply.started":"2023-11-17T07:16:22.268647Z","shell.execute_reply":"2023-11-17T07:16:22.275777Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# # Plot Training and Test loss\n# plt.plot(epochs_array, train_loss_array, 'g', label='Training loss')\n# # plt.plot(epochs_array, test_loss_array, 'b', label='Test loss')\n# plt.title('Training and Test loss')\n# plt.xlabel('Epochs')\n# plt.ylabel('Loss')\n# plt.legend()\n# plt.show()","metadata":{"execution":{"iopub.status.busy":"2023-11-17T07:16:22.278397Z","iopub.execute_input":"2023-11-17T07:16:22.278722Z","iopub.status.idle":"2023-11-17T07:16:22.293961Z","shell.execute_reply.started":"2023-11-17T07:16:22.278692Z","shell.execute_reply":"2023-11-17T07:16:22.293103Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"**Infer**","metadata":{}},{"cell_type":"code","source":"# from torch.jit import load\n# model = UNet()\n# optimizer = optim.Adam(params=model.parameters(), lr=learning_rate)\n\n# checkpoint = torch.load(pretrained_path)","metadata":{"execution":{"iopub.status.busy":"2023-11-17T07:16:22.295195Z","iopub.execute_input":"2023-11-17T07:16:22.295739Z","iopub.status.idle":"2023-11-17T07:16:22.30745Z","shell.execute_reply.started":"2023-11-17T07:16:22.295709Z","shell.execute_reply":"2023-11-17T07:16:22.306496Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# optimizer.load_state_dict(checkpoint['optimizer'])","metadata":{"execution":{"iopub.status.busy":"2023-11-17T07:16:22.308722Z","iopub.execute_input":"2023-11-17T07:16:22.309293Z","iopub.status.idle":"2023-11-17T07:16:22.329576Z","shell.execute_reply.started":"2023-11-17T07:16:22.309241Z","shell.execute_reply":"2023-11-17T07:16:22.328633Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# from collections import OrderedDict\n# new_state_dict = OrderedDict()\n# for k, v in checkpoint['model'].items():\n#     name = k[7:] # remove `module.`\n#     new_state_dict[name] = v\n# # load params\n# model.load_state_dict(new_state_dict)","metadata":{"execution":{"iopub.status.busy":"2023-11-17T07:16:22.330878Z","iopub.execute_input":"2023-11-17T07:16:22.331394Z","iopub.status.idle":"2023-11-17T07:16:22.341354Z","shell.execute_reply.started":"2023-11-17T07:16:22.331201Z","shell.execute_reply":"2023-11-17T07:16:22.340312Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"**Visualize results**","metadata":{}},{"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-17T07:16:22.342472Z","iopub.execute_input":"2023-11-17T07:16:22.342986Z","iopub.status.idle":"2023-11-17T07:16:22.354902Z","shell.execute_reply.started":"2023-11-17T07:16:22.342955Z","shell.execute_reply":"2023-11-17T07:16:22.353766Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# fig, arr = plt.subplots(4, 3, figsize=(16, 12))\n# arr[0][0].set_title('Image')\n# arr[0][1].set_title('Segmentation')\n# arr[0][2].set_title('Predict')\n\n# model.eval()\n# with torch.no_grad():\n#     predict = model(img)\n\n# for 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-17T07:16:22.356291Z","iopub.execute_input":"2023-11-17T07:16:22.356611Z","iopub.status.idle":"2023-11-17T07:16:22.366673Z","shell.execute_reply.started":"2023-11-17T07:16:22.356586Z","shell.execute_reply":"2023-11-17T07:16:22.365881Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"**Create submission**","metadata":{}},{"cell_type":"code","source":"# transform = Compose([Resize((800, 1120), interpolation=InterpolationMode.BILINEAR),\n#                      PILToTensor()])","metadata":{"execution":{"iopub.status.busy":"2023-11-17T07:16:22.367975Z","iopub.execute_input":"2023-11-17T07:16:22.368245Z","iopub.status.idle":"2023-11-17T07:16:22.378016Z","shell.execute_reply.started":"2023-11-17T07:16:22.368222Z","shell.execute_reply":"2023-11-17T07:16:22.377164Z"},"trusted":true},"outputs":[],"execution_count":null},{"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-17T07:16:22.379005Z","iopub.execute_input":"2023-11-17T07:16:22.37944Z","iopub.status.idle":"2023-11-17T07:16:22.391496Z","shell.execute_reply.started":"2023-11-17T07:16:22.379402Z","shell.execute_reply":"2023-11-17T07:16:22.390463Z"},"trusted":true},"outputs":[],"execution_count":null},{"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-17T07:16:22.392668Z","iopub.execute_input":"2023-11-17T07:16:22.392993Z","iopub.status.idle":"2023-11-17T07:16:22.430533Z","shell.execute_reply.started":"2023-11-17T07:16:22.392962Z","shell.execute_reply":"2023-11-17T07:16:22.42958Z"},"trusted":true},"outputs":[],"execution_count":null},{"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-17T07:16:22.431677Z","iopub.execute_input":"2023-11-17T07:16:22.432018Z","iopub.status.idle":"2023-11-17T07:16:22.642651Z","shell.execute_reply.started":"2023-11-17T07:16:22.431988Z","shell.execute_reply":"2023-11-17T07:16:22.641313Z"},"trusted":true},"outputs":[],"execution_count":null},{"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)\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-17T07:16:22.643892Z","iopub.execute_input":"2023-11-17T07:16:22.644213Z","iopub.status.idle":"2023-11-17T07:16:24.407437Z","shell.execute_reply.started":"2023-11-17T07:16:22.644187Z","shell.execute_reply":"2023-11-17T07:16:24.406395Z"},"trusted":true},"outputs":[],"execution_count":null},{"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)\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-17T07:16:24.408653Z","iopub.execute_input":"2023-11-17T07:16:24.408947Z","iopub.status.idle":"2023-11-17T07:16:40.900046Z","shell.execute_reply.started":"2023-11-17T07:16:24.408921Z","shell.execute_reply":"2023-11-17T07:16:40.898779Z"},"trusted":true},"outputs":[],"execution_count":null},{"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'output.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2023-11-17T07:16:40.901648Z","iopub.execute_input":"2023-11-17T07:16:40.902041Z","iopub.status.idle":"2023-11-17T07:16:43.898877Z","shell.execute_reply.started":"2023-11-17T07:16:40.901995Z","shell.execute_reply":"2023-11-17T07:16:43.897848Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{},"outputs":[],"execution_count":null}]}