{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# !cp -r ../input/pytorch-segmentation-models-lib/ ./\n# !pip config set global.disable-pip-version-check true\n# !pip install -q ./pytorch-segmentation-models-lib/pretrainedmodels-0.7.4/pretrainedmodels-0.7.4\n# !pip install -q ./pytorch-segmentation-models-lib/efficientnet_pytorch-0.6.3/efficientnet_pytorch-0.6.3\n# !pip install -q ./pytorch-segmentation-models-lib/timm-0.4.12-py3-none-any.whl\n# !pip install -q ./pytorch-segmentation-models-lib/segmentation_models_pytorch-0.2.0-py3-none-any.whl","metadata":{"execution":{"iopub.status.busy":"2022-07-30T06:21:21.475837Z","iopub.execute_input":"2022-07-30T06:21:21.476427Z","iopub.status.idle":"2022-07-30T06:21:21.500514Z","shell.execute_reply.started":"2022-07-30T06:21:21.476237Z","shell.execute_reply":"2022-07-30T06:21:21.499405Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def rle_encode_less_memory(img):\n    #the image should be transposed\n    pixels = img.T.flatten()\n    \n    # This simplified method requires first and last pixel to be zero\n    pixels[0] = 0\n    pixels[-1] = 0\n    runs = np.where(pixels[1:] != pixels[:-1])[0] + 2\n    runs[1::2] -= runs[::2]\n    \n    return ' '.join(str(x) for x in runs)","metadata":{"execution":{"iopub.status.busy":"2022-07-30T06:21:21.502551Z","iopub.execute_input":"2022-07-30T06:21:21.503150Z","iopub.status.idle":"2022-07-30T06:21:21.518339Z","shell.execute_reply.started":"2022-07-30T06:21:21.503091Z","shell.execute_reply":"2022-07-30T06:21:21.517050Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# ! pip install segmentation-models-pytorch\n\nfrom skimage import io, filters, transform \nimport tifffile as tiff\nimport albumentations as A\n \nimport os\nimport numpy as np\nimport pandas as pd\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n# import segmentation_models_pytorch as smp","metadata":{"papermill":{"duration":13.182907,"end_time":"2022-07-12T04:01:53.673664","exception":false,"start_time":"2022-07-12T04:01:40.490757","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-07-30T06:22:24.736755Z","iopub.execute_input":"2022-07-30T06:22:24.737131Z","iopub.status.idle":"2022-07-30T06:22:24.742520Z","shell.execute_reply.started":"2022-07-30T06:22:24.737099Z","shell.execute_reply":"2022-07-30T06:22:24.741604Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class config:\n    IMAGE_SIZE = 768\n    TRAIN_BATCH_SIZE = 2\n    VALID_BATCH_SIZE = 2*TRAIN_BATCH_SIZE\n    EPOCHS = 15\n    DEVICE = \"cuda\"\n    OUTPUT = \"/hubmap/\"\n    MODEL_PATH = \"../input/segformer-nvidia-mit-b1\"\n    FOLDS = 5\n    LR = 1e-3\n    ","metadata":{"execution":{"iopub.status.busy":"2022-07-30T06:21:25.801414Z","iopub.execute_input":"2022-07-30T06:21:25.802039Z","iopub.status.idle":"2022-07-30T06:21:25.810232Z","shell.execute_reply.started":"2022-07-30T06:21:25.802001Z","shell.execute_reply":"2022-07-30T06:21:25.809220Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class HubDataset(torch.utils.data.Dataset):\n    def __init__(self,image_path, augmentations=None):\n        self.image_path = image_path\n        self.augmentations = augmentations\n        \n    def __len__(self):\n        return len(self.image_path)\n    \n    def __getitem__(self,item):\n        \n        image = tiff.imread(self.image_path[item])\n#         mask = io.imread(self.mask_path[item])\n#         mask = mask.reshape(mask.shape[0],mask.shape[1],1)\n        \n        \n        ## resize\n        image = transform.resize(image, (config.IMAGE_SIZE, config.IMAGE_SIZE, 3))\n#         mask = transform.resize(mask, (config.IMAGE_SIZE, config.IMAGE_SIZE, 1))\n        \n        image = image - np.min(image)\n        image = image / np.max(image)\n        \n#         if self.augmentations is not None:\n#             augmented = self.augmentations(image=image, mask=mask)\n#             image = augmented[\"image\"]\n#             mask = augmented[\"mask\"]    \n        image = np.transpose(image, (2, 0, 1)).astype(np.float32)\n#         mask = np.transpose(mask, (2, 0, 1)).astype(np.float32)\n        \n        return {\n            \"image\": torch.tensor(image, dtype=torch.float),\n#             \"mask\" : torch.tensor(mask, dtype=torch.float),\n        }","metadata":{"papermill":{"duration":0.017041,"end_time":"2022-07-12T04:01:53.717711","exception":false,"start_time":"2022-07-12T04:01:53.70067","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-07-30T06:21:25.811936Z","iopub.execute_input":"2022-07-30T06:21:25.812518Z","iopub.status.idle":"2022-07-30T06:21:25.824754Z","shell.execute_reply.started":"2022-07-30T06:21:25.812472Z","shell.execute_reply":"2022-07-30T06:21:25.823344Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\nimport torch.nn as nn\n\n@torch.no_grad()    \ndef infer(model,valid_loader,device):\n    model.eval()\n    \n    masks = []\n    for data in valid_loader:\n        inputs = data['image']\n        \n        inputs = inputs.to(device, dtype=torch.float)\n\n        output = model(inputs,)\n        output = torch.sigmoid(output)\n        \n        output = output.detach().cpu().numpy()\n        masks.append(output)\n    return masks","metadata":{"execution":{"iopub.status.busy":"2022-07-30T06:21:25.828589Z","iopub.execute_input":"2022-07-30T06:21:25.828981Z","iopub.status.idle":"2022-07-30T06:21:25.836781Z","shell.execute_reply.started":"2022-07-30T06:21:25.828926Z","shell.execute_reply":"2022-07-30T06:21:25.835590Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\nimport torch.nn as nn\n\nfrom transformers import SegformerForSemanticSegmentation\n\n\nclass MixUpSample(nn.Module):\n    def __init__(self, scale_factor=4):\n        super().__init__()\n        self.mixing = nn.Parameter(torch.tensor(0.5))\n        self.scale_factor = scale_factor\n\n    def forward(self, x):\n        x = self.mixing * F.interpolate(\n            x, scale_factor=self.scale_factor, mode=\"bilinear\", align_corners=False\n        ) + (1 - self.mixing) * F.interpolate(\n            x, scale_factor=self.scale_factor, mode=\"nearest\"\n        )\n        return x\n\n\nclass HubmapModel(nn.Module):\n    def __init__(self):\n        super(HubmapModel, self).__init__()\n\n        self.model = SegformerForSemanticSegmentation.from_pretrained(\n            config.MODEL_PATH, num_labels=1, ignore_mismatched_sizes=True\n        )\n        self.mixup = MixUpSample()\n\n    def forward(self, image):\n        img_segs = self.model(image)\n\n        upsampled_logits = self.mixup(img_segs.logits)\n        return upsampled_logits","metadata":{"execution":{"iopub.status.busy":"2022-07-30T06:21:25.838740Z","iopub.execute_input":"2022-07-30T06:21:25.839304Z","iopub.status.idle":"2022-07-30T06:21:26.342179Z","shell.execute_reply.started":"2022-07-30T06:21:25.839242Z","shell.execute_reply":"2022-07-30T06:21:26.341260Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## MAIN","metadata":{}},{"cell_type":"code","source":"df = pd.read_csv(\"../input/hubmap-organ-segmentation/test.csv\")","metadata":{"execution":{"iopub.status.busy":"2022-07-30T06:21:26.343592Z","iopub.execute_input":"2022-07-30T06:21:26.343969Z","iopub.status.idle":"2022-07-30T06:21:26.358410Z","shell.execute_reply.started":"2022-07-30T06:21:26.343930Z","shell.execute_reply":"2022-07-30T06:21:26.357544Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_paths = [\n              \"../input/train-hubmap-resized-images-part-2/model-3.pth\",\n#               \"../input/hubmap-segormer-b0-768/model-1.pth\", \n              ]","metadata":{"execution":{"iopub.status.busy":"2022-07-30T06:21:54.618377Z","iopub.execute_input":"2022-07-30T06:21:54.618728Z","iopub.status.idle":"2022-07-30T06:21:54.624599Z","shell.execute_reply.started":"2022-07-30T06:21:54.618700Z","shell.execute_reply":"2022-07-30T06:21:54.622426Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"rle_list = []\nfor idx,row in df.iterrows():\n\n    ###\n    model = HubmapModel()\n    model.to(\"cuda\")\n    \n    \n\n    \n    df_valid  = row\n    valid_ids = df_valid.id\n\n    valid_images = [os.path.join(\"../input/hubmap-organ-segmentation/test_images\",str(valid_ids) + \".tiff\")]\n\n    valid_dataset = HubDataset(image_path=valid_images)\n    valid_loader = torch.utils.data.DataLoader(valid_dataset,batch_size=config.VALID_BATCH_SIZE,shuffle=False,pin_memory=True) \n    \n    mask = np.zeros((config.IMAGE_SIZE, config.IMAGE_SIZE))\n    \n    for path in model_paths:\n        \n        model.load_state_dict(torch.load(path))\n        masks_output = infer(model=model,valid_loader=valid_loader,device=config.DEVICE)\n\n        mask += masks_output[0][0].reshape(masks_output[0][0].shape[1],masks_output[0][0].shape[2])\n        \n    mask = mask/len(model_paths)\n\n    mask = transform.resize(mask, (df_valid.img_height, df_valid.img_width))\n\n    threshold = filters.threshold_li(mask) ##  isodata, otsu, li. mean\n    mask = mask > threshold\n    mask = mask.astype(np.int8)\n    \n    print(mask.shape)\n    io.imshow(mask)\n    ###\n    rle_list.append(rle_encode_less_memory(mask))","metadata":{"execution":{"iopub.status.busy":"2022-07-30T06:22:36.287534Z","iopub.execute_input":"2022-07-30T06:22:36.287893Z","iopub.status.idle":"2022-07-30T06:22:38.295204Z","shell.execute_reply.started":"2022-07-30T06:22:36.287865Z","shell.execute_reply":"2022-07-30T06:22:38.294268Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(threshold)","metadata":{"execution":{"iopub.status.busy":"2022-07-30T06:22:43.624855Z","iopub.execute_input":"2022-07-30T06:22:43.625541Z","iopub.status.idle":"2022-07-30T06:22:43.631351Z","shell.execute_reply.started":"2022-07-30T06:22:43.625501Z","shell.execute_reply":"2022-07-30T06:22:43.629951Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission = pd.read_csv(\"../input/hubmap-organ-segmentation/sample_submission.csv\")","metadata":{"execution":{"iopub.status.busy":"2022-07-30T06:22:46.816214Z","iopub.execute_input":"2022-07-30T06:22:46.817463Z","iopub.status.idle":"2022-07-30T06:22:46.829216Z","shell.execute_reply.started":"2022-07-30T06:22:46.817409Z","shell.execute_reply":"2022-07-30T06:22:46.828212Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission[\"rle\"] = rle_list\nsubmission.to_csv(\"submission.csv\", index=False)","metadata":{"execution":{"iopub.status.busy":"2022-07-30T06:22:51.835155Z","iopub.execute_input":"2022-07-30T06:22:51.835736Z","iopub.status.idle":"2022-07-30T06:22:51.854163Z","shell.execute_reply.started":"2022-07-30T06:22:51.835690Z","shell.execute_reply":"2022-07-30T06:22:51.853320Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission.head()","metadata":{"execution":{"iopub.status.busy":"2022-07-30T06:22:53.965506Z","iopub.execute_input":"2022-07-30T06:22:53.965962Z","iopub.status.idle":"2022-07-30T06:22:53.982497Z","shell.execute_reply.started":"2022-07-30T06:22:53.965922Z","shell.execute_reply":"2022-07-30T06:22:53.981383Z"},"trusted":true},"execution_count":null,"outputs":[]}]}