{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport pathlib, sys, os, random, time\nimport numba, cv2, gc\n\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\nfrom tqdm.notebook import tqdm\n\nimport albumentations as A\n\nimport rasterio\nfrom rasterio.windows import Window","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install ../input/pretrainedmodels/pretrainedmodels-0.7.4/pretrainedmodels-0.7.4/","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.utils.data as D\n\nimport torchvision\nfrom torchvision import transforms as T","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"def set_seeds(seed=42):\n    random.seed(seed)\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed(seed)\n    torch.cuda.manual_seed_all(seed)\n    torch.backends.cudnn.deterministic = True\n\nset_seeds();","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"DATA_PATH = '../input/hubmap-kidney-segmentation'\nEPOCHES = 20\nBATCH_SIZE = 32\nDEVICE = 'cuda' if torch.cuda.is_available() else 'cpu' ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# used for converting the decoded image to rle mask\ndef rle_encode(im):\n    '''\n    im: numpy array, 1 - mask, 0 - background\n    Returns run length as string formated\n    '''\n    pixels = im.flatten(order = 'F')\n    pixels = np.concatenate([[0], pixels, [0]])\n    runs = np.where(pixels[1:] != pixels[:-1])[0] + 1\n    runs[1::2] -= runs[::2]\n    return ' '.join(str(x) for x in runs)\n\ndef rle_decode(mask_rle, shape=(256, 256)):\n    '''\n    mask_rle: run-length as string formated (start length)\n    shape: (height,width) of array to return \n    Returns numpy array, 1 - mask, 0 - background\n\n    '''\n    s = mask_rle.split()\n    starts, lengths = [np.asarray(x, dtype=int) for x in (s[0:][::2], s[1:][::2])]\n    starts -= 1\n    ends = starts + lengths\n    img = np.zeros(shape[0]*shape[1], dtype=np.uint8)\n    for lo, hi in zip(starts, ends):\n        img[lo:hi] = 1\n    return img.reshape(shape, order='F')\n\n@numba.njit()\ndef rle_numba(pixels):\n    size = len(pixels)\n    points = []\n    if pixels[0] == 1: points.append(0)\n    flag = True\n    for i in range(1, size):\n        if pixels[i] != pixels[i-1]:\n            if flag:\n                points.append(i+1)\n                flag = False\n            else:\n                points.append(i+1 - points[-1])\n                flag = True\n    if pixels[-1] == 1: points.append(size-points[-1]+1)    \n    return points\n\ndef rle_numba_encode(image):\n    pixels = image.flatten(order = 'F')\n    points = rle_numba(pixels)\n    return ' '.join(str(x) for x in points)\n\ndef make_grid(shape, window=256, min_overlap=32):\n    \"\"\"\n        Return Array of size (N,4), where N - number of tiles,\n        2nd axis represente slices: x1,x2,y1,y2 \n    \"\"\"\n    x, y = shape\n    nx = x // (window - min_overlap) + 1\n    x1 = np.linspace(0, x, num=nx, endpoint=False, dtype=np.int64)\n    x1[-1] = x - window\n    x2 = (x1 + window).clip(0, x)\n    ny = y // (window - min_overlap) + 1\n    y1 = np.linspace(0, y, num=ny, endpoint=False, dtype=np.int64)\n    y1[-1] = y - window\n    y2 = (y1 + window).clip(0, y)\n    slices = np.zeros((nx,ny, 4), dtype=np.int64)\n    \n    for i in range(nx):\n        for j in range(ny):\n            slices[i,j] = x1[i], x2[i], y1[j], y2[j]    \n    return slices.reshape(nx*ny,4)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"identity = rasterio.Affine(1, 0, 0, 0, 1, 0)\n\nWINDOW=1024\nMIN_OVERLAP=40\nNEW_SIZE=256","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_model():\n    model = torchvision.models.segmentation.fcn_resnet50(False)\n    \n    pth = torch.load('../fcn_resnet50_coco-1167a1af.pth')\n    for key in [\"aux_classifier.0.weight\", \"aux_classifier.1.weight\", \"aux_classifier.1.bias\", \"aux_classifier.1.running_mean\", \"aux_classifier.1.running_var\", \"aux_classifier.1.num_batches_tracked\", \"aux_classifier.4.weight\", \"aux_classifier.4.bias\"]:\n        del pth[key]\n    \n    model.load_state_dict(pth)\n    model.classifier[4] = nn.Conv2d(512, 1, kernel_size=(1, 1), stride=(1, 1))\n    return model\n\n\nimport functools\nimport torch.utils.model_zoo as model_zoo\nfrom torchvision.models.resnet import ResNet\nfrom torchvision.models.resnet import BasicBlock\nfrom torchvision.models.resnet import Bottleneck\nfrom pretrainedmodels.models.torchvision_models import pretrained_settings\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\n\n\ndef preprocess_input(x, mean=None, std=None, input_space='RGB', input_range=None, **kwargs):\n\n    if input_space == 'BGR':\n        x = x[..., ::-1].copy()\n\n    if input_range is not None:\n        if x.max() > 1 and input_range[1] == 1:\n            x = x / 255.\n\n    if mean is not None:\n        mean = np.array(mean)\n        x = x - mean\n\n    if std is not None:\n        std = np.array(std)\n        x = x / std\n\n    return x\n\n\nclass Model(nn.Module):\n\n    def __init__(self):\n        super().__init__()\n\n    def initialize(self):\n        for m in self.modules():\n            if isinstance(m, nn.Conv2d):\n                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\n            elif isinstance(m, nn.BatchNorm2d):\n                nn.init.constant_(m.weight, 1)\n                nn.init.constant_(m.bias, 0)\n\n\nclass Conv2dReLU(nn.Module):\n    def __init__(self, in_channels, out_channels, kernel_size, padding=0,\n                 stride=1, use_batchnorm=True, **batchnorm_params):\n\n        super().__init__()\n\n        layers = [\n            nn.Conv2d(in_channels, out_channels, kernel_size,\n                              stride=stride, padding=padding, bias=not (use_batchnorm)),\n            nn.ReLU(inplace=True),\n        ]\n\n        if use_batchnorm:\n            layers.insert(1, nn.BatchNorm2d(out_channels, **batchnorm_params))\n\n        self.block = nn.Sequential(*layers)\n\n    def forward(self, x):\n        return self.block(x)\n\n\nclass EncoderDecoder(Model):\n\n    def __init__(self, encoder, decoder, activation):\n        super().__init__()\n        self.encoder = encoder\n        self.decoder = decoder\n\n        if callable(activation) or activation is None:\n            self.activation = activation\n        elif activation == 'softmax':\n            self.activation = nn.Softmax(dim=1)\n        elif activation == 'sigmoid':\n            self.activation = nn.Sigmoid()\n        else:\n            raise ValueError('Activation should be \"sigmoid\"/\"softmax\"/callable/None')\n\n    def forward(self, x):\n        \"\"\"Sequentially pass `x` trough model`s `encoder` and `decoder` (return logits!)\"\"\"\n        x = self.encoder(x)\n        x = self.decoder(x)\n        return x\n\n    def predict(self, x):\n        \"\"\"Inference method. Switch model to `eval` mode, call `.forward(x)`\n        and apply activation function (if activation is not `None`) with `torch.no_grad()`\n\n        Args:\n            x: 4D torch tensor with shape (batch_size, channels, height, width)\n\n        Return:\n            prediction: 4D torch tensor with shape (batch_size, classes, height, width)\n\n        \"\"\"\n        if self.training:\n            self.eval()\n\n        with torch.no_grad():\n            x = self.forward(x)\n            if self.activation:\n                x = self.activation(x)\n\n        return x\n\n\nclass DecoderBlock(nn.Module):\n    def __init__(self, in_channels, out_channels, use_batchnorm=True):\n        super().__init__()\n        self.block = nn.Sequential(\n            Conv2dReLU(in_channels, out_channels, kernel_size=3, padding=1, use_batchnorm=use_batchnorm),\n            Conv2dReLU(out_channels, out_channels, kernel_size=3, padding=1, use_batchnorm=use_batchnorm),\n        )\n\n    def forward(self, x):\n        x, skip = x\n        x = F.interpolate(x, scale_factor=2, mode='nearest')\n        if skip is not None:\n            x = torch.cat([x, skip], dim=1)\n        x = self.block(x)\n        return x\n\n\nclass CenterBlock(DecoderBlock):\n\n    def forward(self, x):\n        return self.block(x)\n\n\nclass UnetDecoder(Model):\n\n    def __init__(\n            self,\n            encoder_channels,\n            decoder_channels=(256, 128, 64, 32, 16),\n            final_channels=1,\n            use_batchnorm=True,\n            center=False,\n    ):\n        super().__init__()\n\n        if center:\n            channels = encoder_channels[0]\n            self.center = CenterBlock(channels, channels, use_batchnorm=use_batchnorm)\n        else:\n            self.center = None\n\n        in_channels = self.compute_channels(encoder_channels, decoder_channels)\n        out_channels = decoder_channels\n\n        self.layer1 = DecoderBlock(in_channels[0], out_channels[0], use_batchnorm=use_batchnorm)\n        self.layer2 = DecoderBlock(in_channels[1], out_channels[1], use_batchnorm=use_batchnorm)\n        self.layer3 = DecoderBlock(in_channels[2], out_channels[2], use_batchnorm=use_batchnorm)\n        self.layer4 = DecoderBlock(in_channels[3], out_channels[3], use_batchnorm=use_batchnorm)\n        self.layer5 = DecoderBlock(in_channels[4], out_channels[4], use_batchnorm=use_batchnorm)\n        self.final_conv = nn.Conv2d(out_channels[4], final_channels, kernel_size=(1, 1))\n\n        self.initialize()\n\n    def compute_channels(self, encoder_channels, decoder_channels):\n        channels = [\n            encoder_channels[0] + encoder_channels[1],\n            encoder_channels[2] + decoder_channels[0],\n            encoder_channels[3] + decoder_channels[1],\n            encoder_channels[4] + decoder_channels[2],\n            0 + decoder_channels[3],\n        ]\n        return channels\n\n    def forward(self, x):\n        encoder_head = x[0]\n        skips = x[1:]\n\n        if self.center:\n            encoder_head = self.center(encoder_head)\n\n        x = self.layer1([encoder_head, skips[0]])\n        x = self.layer2([x, skips[1]])\n        x = self.layer3([x, skips[2]])\n        x = self.layer4([x, skips[3]])\n        x = self.layer5([x, None])\n        x = self.final_conv(x)\n\n        return x\n\n\nclass ResNetEncoder(ResNet):\n\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        self.pretrained = False\n        del self.fc\n\n    def forward(self, x):\n        x0 = self.conv1(x)\n        x0 = self.bn1(x0)\n        x0 = self.relu(x0)\n\n        x1 = self.maxpool(x0)\n        x1 = self.layer1(x1)\n\n        x2 = self.layer2(x1)\n        x3 = self.layer3(x2)\n        x4 = self.layer4(x3)\n\n        return [x4, x3, x2, x1, x0]\n\n    def load_state_dict(self, state_dict, **kwargs):\n        state_dict.pop('fc.bias')\n        state_dict.pop('fc.weight')\n        super().load_state_dict(state_dict, **kwargs)\n\n\nresnet_encoders = {\n    'resnet18': {\n        'encoder': ResNetEncoder,\n        'pretrained_settings': pretrained_settings['resnet18'],\n        'out_shapes': (512, 256, 128, 64, 64),\n        'params': {\n            'block': BasicBlock,\n            'layers': [2, 2, 2, 2],\n        },\n    },\n\n    'resnet34': {\n        'encoder': ResNetEncoder,\n        'pretrained_settings': pretrained_settings['resnet34'],\n        'out_shapes': (512, 256, 128, 64, 64),\n        'params': {\n            'block': BasicBlock,\n            'layers': [3, 4, 6, 3],\n        },\n    },\n\n    'resnet50': {\n        'encoder': ResNetEncoder,\n        'pretrained_settings': pretrained_settings['resnet50'],\n        'out_shapes': (2048, 1024, 512, 256, 64),\n        'params': {\n            'block': Bottleneck,\n            'layers': [3, 4, 6, 3],\n        },\n    },\n\n    'resnet101': {\n        'encoder': ResNetEncoder,\n        'pretrained_settings': pretrained_settings['resnet101'],\n        'out_shapes': (2048, 1024, 512, 256, 64),\n        'params': {\n            'block': Bottleneck,\n            'layers': [3, 4, 23, 3],\n        },\n    },\n\n    'resnet152': {\n        'encoder': ResNetEncoder,\n        'pretrained_settings': pretrained_settings['resnet152'],\n        'out_shapes': (2048, 1024, 512, 256, 64),\n        'params': {\n            'block': Bottleneck,\n            'layers': [3, 8, 36, 3],\n        },\n    },\n}\n\nencoders = {}\nencoders.update(resnet_encoders)\n\ndef get_encoder(name, encoder_weights=None):\n    Encoder = encoders[name]['encoder']\n    encoder = Encoder(**encoders[name]['params'])\n    encoder.out_shapes = encoders[name]['out_shapes']\n\n    if encoder_weights is not None:\n        settings = encoders[name]['pretrained_settings'][encoder_weights]\n        encoder.load_state_dict(model_zoo.load_url(settings['url']))\n\n    return encoder\n\n\ndef get_encoder_names():\n    return list(encoders.keys())\n\n\ndef get_preprocessing_fn(encoder_name, pretrained='imagenet'):\n    settings = encoders[encoder_name]['pretrained_settings']\n\n    if pretrained not in settings.keys():\n        raise ValueError('Avaliable pretrained options {}'.format(settings.keys()))\n\n    input_space = settings[pretrained].get('input_space')\n    input_range = settings[pretrained].get('input_range')\n    mean = settings[pretrained].get('mean')\n    std = settings[pretrained].get('std')\n    \n    return functools.partial(preprocess_input, mean=mean, std=std, input_space=input_space, input_range=input_range)\n\n\nclass Unet(EncoderDecoder):\n    \"\"\"Unet_ is a fully convolution neural network for image semantic segmentation\n\n    Args:\n        encoder_name: name of classification model (without last dense layers) used as feature\n            extractor to build segmentation model.\n        encoder_weights: one of ``None`` (random initialization), ``imagenet`` (pre-training on ImageNet).\n        decoder_channels: list of numbers of ``Conv2D`` layer filters in decoder blocks\n        decoder_use_batchnorm: if ``True``, ``BatchNormalisation`` layer between ``Conv2D`` and ``Activation`` layers\n            is used.\n        classes: a number of classes for output (output shape - ``(batch, classes, h, w)``).\n        activation: activation function used in ``.predict(x)`` method for inference.\n            One of [``sigmoid``, ``softmax``, callable, None]\n        center: if ``True`` add ``Conv2dReLU`` block on encoder head (useful for VGG models)\n\n    Returns:\n        ``torch.nn.Module``: **Unet**\n\n    .. _Unet:\n        https://arxiv.org/pdf/1505.04597\n\n    \"\"\"\n\n    def __init__(\n            self,\n            encoder_name='resnet34',\n            encoder_weights='imagenet',\n            decoder_use_batchnorm=True,\n            decoder_channels=(256, 128, 64, 32, 16),\n            classes=1,\n            activation='sigmoid',\n            center=False,  # usefull for VGG models\n    ):\n        encoder = get_encoder(\n            encoder_name,\n            encoder_weights=encoder_weights\n        )\n\n        decoder = UnetDecoder(\n            encoder_channels=encoder.out_shapes,\n            decoder_channels=decoder_channels,\n            final_channels=classes,\n            use_batchnorm=decoder_use_batchnorm,\n            center=center,\n        )\n\n        super().__init__(encoder, decoder, activation)\n\n        self.name = 'u-{}'.format(encoder_name)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!mkdir /root/.cache/torch/hub/checkpoints/ -p\n!cp ../input/pytorch-pretrained-models/resnet34-333f7ec4.pth /root/.cache/torch/hub/checkpoints/\n!cp ../input/pytorch-pretrained-models/resnet18-5c106cde.pth /root/.cache/torch/hub/checkpoints/\n!cp ../input/pytorch-pretrained-models/resnet50-19c8e357.pth /root/.cache/torch/hub/checkpoints/","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"trfm = T.Compose([\n    T.ToPILImage(),\n    T.Resize(NEW_SIZE),\n    T.ToTensor(),\n    T.Normalize([0.625, 0.448, 0.688],\n                [0.131, 0.177, 0.101]),\n])\n\n\nmodel = Unet(encoder_name=\"resnet34\",classes=1,activation=None)    \nmodel.to(DEVICE);\n\np = pathlib.Path(DATA_PATH)\n\nsubm = {}\n\nmodel.load_state_dict(torch.load(\"../input/hubmapkidneysegmentation/fold_0.pth\"))\nmodel.eval()\n\nfor i, filename in enumerate(p.glob('test/*.tiff')):\n    dataset = rasterio.open(filename.as_posix(), transform = identity)\n    slices = make_grid(dataset.shape, window=WINDOW, min_overlap=MIN_OVERLAP)\n    preds = np.zeros(dataset.shape, dtype=np.uint8)\n    for (x1,x2,y1,y2) in slices:\n        image = dataset.read([1,2,3],\n                    window=Window.from_slices((x1,x2),(y1,y2)))\n        image = np.moveaxis(image, 0, -1)\n        image = trfm(image)\n        with torch.no_grad():\n            score = model(image.to(DEVICE)[None])[0][0]\n            score = score.cpu().numpy()\n            score = cv2.resize(score, (WINDOW, WINDOW))\n            preds[x1:x2,y1:y2] = (score > 0).astype(np.uint8)\n            \n    subm[i] = {'id':filename.stem, 'predicted': rle_numba_encode(preds)}\n    del preds\n    gc.collect();","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = pd.DataFrame.from_dict(subm, orient='index')\nsubmission.to_csv('submission.csv', index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!ls -lh","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"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":4,"nbformat_minor":4}