{"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-23T14:17:13.120711Z","iopub.execute_input":"2022-07-23T14:17:13.121545Z","iopub.status.idle":"2022-07-23T14:17:58.773112Z","shell.execute_reply.started":"2022-07-23T14:17:13.121443Z","shell.execute_reply":"2022-07-23T14:17:58.771984Z"},"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-23T14:17:58.775460Z","iopub.execute_input":"2022-07-23T14:17:58.776061Z","iopub.status.idle":"2022-07-23T14:17:58.785675Z","shell.execute_reply.started":"2022-07-23T14:17:58.776019Z","shell.execute_reply":"2022-07-23T14:17:58.784732Z"},"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\n\nimport 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-23T14:17:58.788561Z","iopub.execute_input":"2022-07-23T14:17:58.789156Z","iopub.status.idle":"2022-07-23T14:18:04.474414Z","shell.execute_reply.started":"2022-07-23T14:17:58.789108Z","shell.execute_reply":"2022-07-23T14:18:04.473348Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class config:\n    IMAGE_SIZE = 1024\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-b0-finetuned-cityscapes-1024x1024\"\n    FOLDS = 5\n    LR = 1e-3\n    ","metadata":{"execution":{"iopub.status.busy":"2022-07-23T14:18:04.475869Z","iopub.execute_input":"2022-07-23T14:18:04.477176Z","iopub.status.idle":"2022-07-23T14:18:04.482723Z","shell.execute_reply.started":"2022-07-23T14:18:04.477146Z","shell.execute_reply":"2022-07-23T14:18:04.481798Z"},"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-23T14:18:04.486371Z","iopub.execute_input":"2022-07-23T14:18:04.486993Z","iopub.status.idle":"2022-07-23T14:18:04.496915Z","shell.execute_reply.started":"2022-07-23T14:18:04.486955Z","shell.execute_reply":"2022-07-23T14:18:04.495996Z"},"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-23T14:18:04.498430Z","iopub.execute_input":"2022-07-23T14:18:04.498814Z","iopub.status.idle":"2022-07-23T14:18:04.513011Z","shell.execute_reply.started":"2022-07-23T14:18:04.498777Z","shell.execute_reply":"2022-07-23T14:18:04.511983Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\nimport torch.nn as nn\nimport segmentation_models_pytorch as smp\n\nfrom transformers import SegformerForSemanticSegmentation\n\nclass HubmapModel(nn.Module):\n    def __init__(self):\n        super(HubmapModel, self).__init__()\n#         configuration = SegformerConfig.from_pretrained(\"nvidia/segformer-b0-finetuned-ade-512-512\")\n#         configuration.num_labels = 1 ## set output as 1 \n#         self.model = SegformerForSemanticSegmentation(config=configuration)\n\n        self.model = SegformerForSemanticSegmentation.from_pretrained(config.MODEL_PATH,\n                                                         num_labels=1,ignore_mismatched_sizes=True)\n    \n    def forward(self, image):\n        img_segs = self.model(image)\n    \n        upsampled_logits = nn.functional.interpolate(img_segs.logits,\n#                 size=(image.shape[0],1,image.shape[2],image.shape[3]), # (height, width)\n                scale_factor=4,\n                mode='nearest',\n                )\n#         print(upsampled_logits.shape)\n        return upsampled_logits\n\n\n# def HubmapModel():\n\n#     model = smp.Unet(encoder_name=\"efficientnet-b7\", \n#         encoder_weights=None, \n#         in_channels=3, \n#         classes=1).to(\"cuda\")\n    \n#     return model","metadata":{"execution":{"iopub.status.busy":"2022-07-23T14:18:04.514627Z","iopub.execute_input":"2022-07-23T14:18:04.515074Z","iopub.status.idle":"2022-07-23T14:18:05.065725Z","shell.execute_reply.started":"2022-07-23T14:18:04.514931Z","shell.execute_reply":"2022-07-23T14:18:05.064725Z"},"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-23T14:18:05.066967Z","iopub.execute_input":"2022-07-23T14:18:05.067625Z","iopub.status.idle":"2022-07-23T14:18:05.082402Z","shell.execute_reply.started":"2022-07-23T14:18:05.067588Z","shell.execute_reply":"2022-07-23T14:18:05.081573Z"},"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    model.load_state_dict(torch.load(f\"../input/train-hubmap-resized-images/model-3.pth\"))\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 = transform.resize(mask, (df_valid.img_height, df_valid.img_width))\n    \n    threshold_otsu = filters.threshold_otsu(mask)\n    mask = mask > threshold_otsu\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-23T14:18:05.083619Z","iopub.execute_input":"2022-07-23T14:18:05.084044Z","iopub.status.idle":"2022-07-23T14:18:16.594225Z","shell.execute_reply.started":"2022-07-23T14:18:05.083997Z","shell.execute_reply":"2022-07-23T14:18:16.593228Z"},"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-23T14:18:16.595520Z","iopub.execute_input":"2022-07-23T14:18:16.596074Z","iopub.status.idle":"2022-07-23T14:18:16.606294Z","shell.execute_reply.started":"2022-07-23T14:18:16.596027Z","shell.execute_reply":"2022-07-23T14:18:16.605428Z"},"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-23T14:18:16.608096Z","iopub.execute_input":"2022-07-23T14:18:16.608847Z","iopub.status.idle":"2022-07-23T14:18:16.617981Z","shell.execute_reply.started":"2022-07-23T14:18:16.608810Z","shell.execute_reply":"2022-07-23T14:18:16.617119Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission.head()","metadata":{"execution":{"iopub.status.busy":"2022-07-23T14:18:16.620485Z","iopub.execute_input":"2022-07-23T14:18:16.621244Z","iopub.status.idle":"2022-07-23T14:18:16.635307Z","shell.execute_reply.started":"2022-07-23T14:18:16.621209Z","shell.execute_reply":"2022-07-23T14:18:16.634466Z"},"trusted":true},"execution_count":null,"outputs":[]}]}