{"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":"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","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2021-05-25T08:05:29.647493Z","iopub.execute_input":"2021-05-25T08:05:29.647814Z","iopub.status.idle":"2021-05-25T08:05:31.829259Z","shell.execute_reply.started":"2021-05-25T08:05:29.647783Z","shell.execute_reply":"2021-05-25T08:05:31.828444Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import rasterio\nfrom rasterio.windows import Window","metadata":{"execution":{"iopub.status.busy":"2021-05-25T08:05:31.830891Z","iopub.execute_input":"2021-05-25T08:05:31.831261Z","iopub.status.idle":"2021-05-25T08:05:32.162030Z","shell.execute_reply.started":"2021-05-25T08:05:31.831224Z","shell.execute_reply":"2021-05-25T08:05:32.161296Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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","metadata":{"execution":{"iopub.status.busy":"2021-05-25T08:05:32.163360Z","iopub.execute_input":"2021-05-25T08:05:32.163697Z","iopub.status.idle":"2021-05-25T08:05:33.470299Z","shell.execute_reply.started":"2021-05-25T08:05:32.163662Z","shell.execute_reply":"2021-05-25T08:05:33.469528Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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();","metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","execution":{"iopub.status.busy":"2021-05-25T08:05:33.471665Z","iopub.execute_input":"2021-05-25T08:05:33.472126Z","iopub.status.idle":"2021-05-25T08:05:33.482531Z","shell.execute_reply.started":"2021-05-25T08:05:33.472086Z","shell.execute_reply":"2021-05-25T08:05:33.481695Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"DATA_PATH = '../input/hubmap-kidney-segmentation'\nEPOCHES = 9\nBATCH_SIZE = 32\nDEVICE = 'cuda' if torch.cuda.is_available() else 'cpu' ","metadata":{"execution":{"iopub.status.busy":"2021-05-25T08:05:33.486695Z","iopub.execute_input":"2021-05-25T08:05:33.487263Z","iopub.status.idle":"2021-05-25T08:05:33.567427Z","shell.execute_reply.started":"2021-05-25T08:05:33.487205Z","shell.execute_reply":"2021-05-25T08:05:33.566405Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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\ndef rle_encode_less_memory(img):\n    pixels = img.T.flatten()\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    return ' '.join(str(x) for x in runs)\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)","metadata":{"execution":{"iopub.status.busy":"2021-05-25T08:05:33.569868Z","iopub.execute_input":"2021-05-25T08:05:33.570467Z","iopub.status.idle":"2021-05-25T08:05:33.595772Z","shell.execute_reply.started":"2021-05-25T08:05:33.570421Z","shell.execute_reply":"2021-05-25T08:05:33.594981Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"identity = rasterio.Affine(1, 0, 0, 0, 1, 0)\n\nclass HubDataset(D.Dataset):\n\n    def __init__(self, root_dir, transform,\n                 window=256, overlap=64, threshold = 500):\n        self.path = pathlib.Path(root_dir)\n        self.overlap = overlap\n        self.window = window\n        self.transform = transform\n        self.csv = pd.read_csv((self.path / 'train.csv').as_posix(),\n                               index_col=[0])\n        self.threshold = threshold\n        self.build_slices()\n        self.len = len(self.slices)\n        self.as_tensor = T.Compose([\n            T.ToTensor(),\n            T.Normalize([0.625, 0.448, 0.688],\n                        [0.131, 0.177, 0.101]),\n        ])\n    def build_slices(self):\n        self.masks = []\n        self.files = []\n        self.slices = []\n        for i, filename in enumerate(self.csv.index.values):\n            filepath = (self.path /'train'/(filename+'.tiff')).as_posix()\n            self.files.append(filepath)\n            with rasterio.open(filepath, transform = identity) as dataset:\n                self.masks.append(rle_decode(\n                    self.csv.loc[filename, 'encoding'], dataset.shape))\n                slices = make_grid(dataset.shape, window=self.window,\n                                   min_overlap=self.overlap)\n                for slc in slices:\n                    x1,x2,y1,y2 = slc\n                    if dataset.read(1, window=Window.from_slices((x1,x2),(y1,y2))).sum() == 0:\n                        continue\n                    if self.masks[-1][x1:x2,y1:y2].sum() > self.threshold or random.random() < 0.2:\n                        self.slices.append([i,x1,x2,y1,y2])\n                        \n    # get data operation\n    def __getitem__(self, index):\n        \n        idx = self.slices[index][0]\n        filename = self.files[idx]\n        x1,x2,y1,y2 = self.slices[index][1:] \n        with rasterio.open(filename, transform = identity) as dataset:\n            channels = [1,2,3] if dataset.count == 3 else [1,1,1]\n            image = dataset.read(channels,window=Window.from_slices((x1,x2),(y1,y2)))    \n            image = np.moveaxis(image, 0, -1)\n            \n        mask = self.masks[idx][x1:x2,y1:y2]\n        \n        augments = self.transform(image=image, mask=mask)\n        return self.as_tensor(augments['image']), augments['mask'][None]\n    \n    def __len__(self):\n        \"\"\"\n        Total number of samples in the dataset\n        \"\"\"\n        return self.len","metadata":{"execution":{"iopub.status.busy":"2021-05-25T08:05:33.596921Z","iopub.execute_input":"2021-05-25T08:05:33.597459Z","iopub.status.idle":"2021-05-25T08:05:33.623018Z","shell.execute_reply.started":"2021-05-25T08:05:33.597417Z","shell.execute_reply":"2021-05-25T08:05:33.621954Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"WINDOW=1024\nMIN_OVERLAP=32\nNEW_SIZE=256\n\ntrfm = A.Compose([\n    A.Resize(NEW_SIZE,NEW_SIZE),\n    A.HorizontalFlip(p=0.5),\n    A.ColorJitter (brightness=0.07, contrast=0.07,\n                   saturation=0.1, hue=0.1, always_apply=False, p=0.3)\n])\n\nds = HubDataset(DATA_PATH, window=WINDOW, overlap=MIN_OVERLAP, transform=trfm)","metadata":{"execution":{"iopub.status.busy":"2021-05-25T08:05:33.624775Z","iopub.execute_input":"2021-05-25T08:05:33.625254Z","iopub.status.idle":"2021-05-25T08:11:55.040628Z","shell.execute_reply.started":"2021-05-25T08:05:33.625198Z","shell.execute_reply":"2021-05-25T08:11:55.039830Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image, mask = ds[12]\nplt.figure(figsize=(16,8))\nplt.subplot(121)\nplt.imshow(mask[0], cmap='gray')\nplt.subplot(122)\nplt.imshow(image[0]);","metadata":{"execution":{"iopub.status.busy":"2021-05-25T08:14:03.546312Z","iopub.execute_input":"2021-05-25T08:14:03.546647Z","iopub.status.idle":"2021-05-25T08:14:04.153095Z","shell.execute_reply.started":"2021-05-25T08:14:03.546614Z","shell.execute_reply":"2021-05-25T08:14:04.152324Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"valid_idx, train_idx = [], []\nfor i in range(len(ds)):\n    if ds.slices[i][0] == 7:\n        valid_idx.append(i)\n    else:\n        train_idx.append(i)","metadata":{"execution":{"iopub.status.busy":"2021-05-25T08:11:56.110707Z","iopub.execute_input":"2021-05-25T08:11:56.111032Z","iopub.status.idle":"2021-05-25T08:11:56.118601Z","shell.execute_reply.started":"2021-05-25T08:11:56.111000Z","shell.execute_reply":"2021-05-25T08:11:56.117770Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_ds = D.Subset(ds, train_idx)\nvalid_ds = D.Subset(ds, valid_idx)\n\n# define training and validation data loaders\nloader = D.DataLoader(\n    train_ds, batch_size=BATCH_SIZE, shuffle=True, num_workers=0)\n\nvloader = D.DataLoader(\n    valid_ds, batch_size=BATCH_SIZE, shuffle=False, num_workers=0)","metadata":{"execution":{"iopub.status.busy":"2021-05-25T08:11:56.120070Z","iopub.execute_input":"2021-05-25T08:11:56.120676Z","iopub.status.idle":"2021-05-25T08:11:56.130911Z","shell.execute_reply.started":"2021-05-25T08:11:56.120637Z","shell.execute_reply":"2021-05-25T08:11:56.130187Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_model():\n    model = torchvision.models.segmentation.fcn_resnet50(True)\n    model.classifier[4] = nn.Conv2d(512, 1, kernel_size=(1, 1), stride=(1, 1))\n    model.aux_classifier[4] = nn.Conv2d(256, 1, kernel_size=(1, 1), stride=(1, 1))\n    return model","metadata":{"execution":{"iopub.status.busy":"2021-05-25T08:11:56.134039Z","iopub.execute_input":"2021-05-25T08:11:56.134329Z","iopub.status.idle":"2021-05-25T08:11:56.142211Z","shell.execute_reply.started":"2021-05-25T08:11:56.134305Z","shell.execute_reply":"2021-05-25T08:11:56.141349Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"@torch.no_grad()\ndef validation(model, loader, loss_fn):\n    losses = []\n    model.eval()\n    for image, target in loader:\n        image, target = image.to(DEVICE), target.float().to(DEVICE)\n        output = model(image)['out']\n        loss = loss_fn(output, target)\n        losses.append(loss.item())\n        \n    return np.array(losses).mean()","metadata":{"execution":{"iopub.status.busy":"2021-05-25T08:11:56.143439Z","iopub.execute_input":"2021-05-25T08:11:56.143795Z","iopub.status.idle":"2021-05-25T08:11:56.153032Z","shell.execute_reply.started":"2021-05-25T08:11:56.143762Z","shell.execute_reply":"2021-05-25T08:11:56.152172Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# deeplabv3_resnet101_coco-586e9e4e.pth  fcn_resnet50_coco-1167a1af.pth\n# deeplabv3_resnet50_coco-cd0a2569.pth   resnet101-5d3b4d8f.pth\n# fcn_resnet101_coco-7ecb50ca.pth        resnet50-19c8e357.pth\n# Copy pretrain weight for model to cache dir\n!mkdir -p /root/.cache/torch/hub/checkpoints/\n!cp ../input/pytorch-pretrained-models/resnet50-19c8e357.pth /root/.cache/torch/hub/checkpoints/\n!cp ../input/pretrain-coco-weights-pytorch/fcn_resnet50_coco-1167a1af.pth /root/.cache/torch/hub/checkpoints/","metadata":{"execution":{"iopub.status.busy":"2021-05-25T08:11:56.154337Z","iopub.execute_input":"2021-05-25T08:11:56.154778Z","iopub.status.idle":"2021-05-25T08:12:00.396555Z","shell.execute_reply.started":"2021-05-25T08:11:56.154745Z","shell.execute_reply":"2021-05-25T08:12:00.395632Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = get_model()\n\nmodel.to(DEVICE);\n\noptimizer = torch.optim.AdamW(model.parameters(),\n                  lr=1e-4, weight_decay=1e-3)","metadata":{"execution":{"iopub.status.busy":"2021-05-25T08:12:00.400283Z","iopub.execute_input":"2021-05-25T08:12:00.400568Z","iopub.status.idle":"2021-05-25T08:12:05.038886Z","shell.execute_reply.started":"2021-05-25T08:12:00.400538Z","shell.execute_reply":"2021-05-25T08:12:05.037921Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"### Table for results\nheader = r'''\n        Train | Valid\nEpoch |  Loss |  Loss | Time, m\n'''\n#          Epoch         metrics            time\nraw_line = '{:6d}' + '\\u2502{:7.3f}'*2 + '\\u2502{:6.2f}'","metadata":{"execution":{"iopub.status.busy":"2021-05-25T08:12:05.040287Z","iopub.execute_input":"2021-05-25T08:12:05.040635Z","iopub.status.idle":"2021-05-25T08:12:05.046497Z","shell.execute_reply.started":"2021-05-25T08:12:05.040598Z","shell.execute_reply":"2021-05-25T08:12:05.044403Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class SoftDiceLoss(nn.Module):\n    def __init__(self, smooth=1., dims=(-2,-1)):\n\n        super(SoftDiceLoss, self).__init__()\n        self.smooth = smooth\n        self.dims = dims\n    \n    def forward(self, x, y):\n\n        tp = (x * y).sum(self.dims)\n        fp = (x * (1 - y)).sum(self.dims)\n        fn = ((1 - x) * y).sum(self.dims)\n        \n        dc = (2 * tp + self.smooth) / (2 * tp + fp + fn + self.smooth)\n        dc = dc.mean()\n\n        return 1 - dc","metadata":{"execution":{"iopub.status.busy":"2021-05-25T08:12:05.048626Z","iopub.execute_input":"2021-05-25T08:12:05.049060Z","iopub.status.idle":"2021-05-25T08:12:05.061387Z","shell.execute_reply.started":"2021-05-25T08:12:05.049008Z","shell.execute_reply":"2021-05-25T08:12:05.060540Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"bce_fn = nn.BCEWithLogitsLoss()\ndice_fn = SoftDiceLoss()\n\ndef loss_fn(y_pred, y_true):\n    bce = bce_fn(y_pred, y_true)\n    dice = dice_fn(y_pred.sigmoid(), y_true)\n    return 0.8*bce+ 0.2*dice\n\nprint(header)\n\nfor epoch in range(1, EPOCHES+1):\n    losses = []\n    start_time = time.time()\n    model.train()\n    for image, target in loader:\n        \n        image, target = image.to(DEVICE), target.float().to(DEVICE)\n        optimizer.zero_grad()\n        output = model(image)['out']\n        loss = loss_fn(output, target)\n        loss.backward()\n        optimizer.step()\n        losses.append(loss.item())\n    vloss = validation(model, vloader, loss_fn)\n    print(raw_line.format(epoch, np.array(losses).mean(), vloss,\n                              (time.time()-start_time)/60**1))\n    losses = []","metadata":{"execution":{"iopub.status.busy":"2021-05-25T08:12:05.062941Z","iopub.execute_input":"2021-05-25T08:12:05.063401Z","iopub.status.idle":"2021-05-25T08:12:36.344789Z","shell.execute_reply.started":"2021-05-25T08:12:05.063362Z","shell.execute_reply":"2021-05-25T08:12:36.343316Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# del train set\ndel loader, vloader, train_ds, valid_ds, ds\ngc.collect();","metadata":{"execution":{"iopub.status.busy":"2021-05-25T08:12:36.345925Z","iopub.status.idle":"2021-05-25T08:12:36.346678Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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\nmodel.eval()\n\np = pathlib.Path(DATA_PATH)\n\nsubm = {}\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        channels = [1,2,3] if dataset.count == 3 else [1,1,1]\n        image = dataset.read(channels,\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])['out'][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_encode_less_memory(preds)}\n    del preds\n    gc.collect();","metadata":{"execution":{"iopub.status.busy":"2021-05-25T08:12:36.347882Z","iopub.status.idle":"2021-05-25T08:12:36.348674Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission = pd.DataFrame.from_dict(subm, orient='index')\nsubmission.to_csv('submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2021-05-25T08:12:36.349687Z","iopub.status.idle":"2021-05-25T08:12:36.350375Z"},"trusted":true},"execution_count":null,"outputs":[]}]}