{"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":"markdown","source":"## summary\n\n* 2.5d segmentation\n    *  segmentation_models_pytorch \n    *  Unet\n* use only 6 slices\n* slide inference\n* add rotate TTA","metadata":{}},{"cell_type":"code","source":"from torch.utils.data import DataLoader\nfrom torch.cuda.amp import autocast, GradScaler\nimport sys\nimport time\nimport torch as tc\nimport random\nfrom torch.utils.data import DataLoader, Dataset\nimport torch\nimport albumentations as A\nfrom albumentations.pytorch import ToTensorV2\nimport numpy as np\n\nfrom tqdm.auto import tqdm\n\nimport torch\nimport torch.nn as nn\nfrom torch.optim import AdamW\n\nfrom torch.utils.data import DataLoader, Dataset\nimport matplotlib.pyplot as plt\nimport cv2,gc\nimport os,warnings\nimport pandas as pd","metadata":{"execution":{"iopub.status.busy":"2023-05-09T12:35:02.136098Z","iopub.execute_input":"2023-05-09T12:35:02.136427Z","iopub.status.idle":"2023-05-09T12:35:09.784209Z","shell.execute_reply.started":"2023-05-09T12:35:02.136394Z","shell.execute_reply":"2023-05-09T12:35:09.783037Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sys.path.append('/kaggle/input/pretrainedmodels/pretrainedmodels-0.7.4')\nsys.path.append('/kaggle/input/efficientnet-pytorch/EfficientNet-PyTorch-master')\nsys.path.append('/kaggle/input/timm-pytorch-image-models/pytorch-image-models-master')\nsys.path.append('/kaggle/input/segmentation-models-pytorch/segmentation_models.pytorch-master')\n\nimport segmentation_models_pytorch as smp","metadata":{"execution":{"iopub.status.busy":"2023-05-09T12:35:09.786440Z","iopub.execute_input":"2023-05-09T12:35:09.787692Z","iopub.status.idle":"2023-05-09T12:35:13.714179Z","shell.execute_reply.started":"2023-05-09T12:35:09.787648Z","shell.execute_reply":"2023-05-09T12:35:13.712853Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## config","metadata":{}},{"cell_type":"code","source":"import os\nimport albumentations as A\nfrom albumentations.pytorch import ToTensorV2\n\nclass CFG:\n    # ============== comp exp name =============\n    comp_name = 'vesuvius'\n\n    # comp_dir_path = './'\n    comp_dir_path = '/kaggle/input/'\n    comp_folder_name = 'vesuvius-challenge-ink-detection'\n    # comp_dataset_path = f'{comp_dir_path}datasets/{comp_folder_name}/'\n    comp_dataset_path = f'{comp_dir_path}{comp_folder_name}/'\n    \n    exp_name = 'vesuvius_2d_slide_exp002'\n\n    # ============== pred target =============\n    target_size = 1\n    TTA=True\n    \n    # ============== model cfg =============\n    model_name = 'Unet'\n    # backbone = 'efficientnet-b0'\n    backbone = 'se_resnext50_32x4d'\n\n    in_chans = 6 # 65\n    # ============== training cfg =============\n    size = 224\n    tile_size = 224\n    stride = tile_size // 8\n\n    batch_size = 64 # 32\n    use_amp = True\n\n    scheduler = 'GradualWarmupSchedulerV2'\n    # scheduler = 'CosineAnnealingLR'\n    epochs = 15\n\n    warmup_factor = 10\n    lr = 1e-4 / warmup_factor\n\n    # ============== fold =============\n    valid_id = 2\n\n    objective_cv = 'binary'  # 'binary', 'multiclass', 'regression'\n    metric_direction = 'maximize'  # maximize, 'minimize'\n    # metrics = 'dice_coef'\n\n    # ============== fixed =============\n    pretrained = True\n    inf_weight = 'best'  # 'best'\n\n    min_lr = 1e-6\n    weight_decay = 1e-6\n    max_grad_norm = 1000\n\n    print_freq = 50\n    num_workers = 4\n\n    seed = 42\n\n    # ============== augmentation =============\n    train_aug_list = [\n        # A.RandomResizedCrop(\n        #     size, size, scale=(0.85, 1.0)),\n        A.Resize(size, size),\n        A.HorizontalFlip(p=0.5),\n        A.VerticalFlip(p=0.5),\n        A.RandomBrightnessContrast(p=0.75),\n        A.ShiftScaleRotate(p=0.75),\n        A.OneOf([\n                A.GaussNoise(var_limit=[10, 50]),\n                A.GaussianBlur(),\n                A.MotionBlur(),\n                ], p=0.4),\n        A.GridDistortion(num_steps=5, distort_limit=0.3, p=0.5),\n        A.CoarseDropout(max_holes=1, max_width=int(size * 0.3), max_height=int(size * 0.3), \n                        mask_fill_value=0, p=0.5),\n        # A.Cutout(max_h_size=int(size * 0.6),\n        #          max_w_size=int(size * 0.6), num_holes=1, p=1.0),\n        A.Normalize(\n            mean= [0] * in_chans,\n            std= [1] * in_chans\n        ),\n        ToTensorV2(transpose_mask=True),\n    ]\n\n    valid_aug_list = [\n        A.Resize(size, size),\n        A.Normalize(\n            mean= [0] * in_chans,\n            std= [1] * in_chans\n        ),\n        ToTensorV2(transpose_mask=True),\n    ]\n","metadata":{"execution":{"iopub.status.busy":"2023-05-09T12:35:13.716501Z","iopub.execute_input":"2023-05-09T12:35:13.717364Z","iopub.status.idle":"2023-05-09T12:35:13.731346Z","shell.execute_reply.started":"2023-05-09T12:35:13.717323Z","shell.execute_reply":"2023-05-09T12:35:13.730020Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IS_DEBUG = False\nmode = 'train' if IS_DEBUG else 'test'\nTH = 0.2","metadata":{"execution":{"iopub.status.busy":"2023-05-09T12:35:13.735463Z","iopub.execute_input":"2023-05-09T12:35:13.735840Z","iopub.status.idle":"2023-05-09T12:35:13.747521Z","shell.execute_reply.started":"2023-05-09T12:35:13.735797Z","shell.execute_reply":"2023-05-09T12:35:13.746522Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')","metadata":{"execution":{"iopub.status.busy":"2023-05-09T12:35:13.749053Z","iopub.execute_input":"2023-05-09T12:35:13.749965Z","iopub.status.idle":"2023-05-09T12:35:13.847618Z","shell.execute_reply.started":"2023-05-09T12:35:13.749867Z","shell.execute_reply":"2023-05-09T12:35:13.846519Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## helper","metadata":{}},{"cell_type":"code","source":"# ref.: https://www.kaggle.com/stainsby/fast-tested-rle\ndef rle(img):\n    '''\n    img: numpy array, 1 - mask, 0 - background\n    Returns run length as string formated\n    '''\n    pixels = img.flatten()\n    # pixels = (pixels >= thr).astype(int)\n    \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)","metadata":{"execution":{"iopub.status.busy":"2023-05-09T12:35:13.851494Z","iopub.execute_input":"2023-05-09T12:35:13.851933Z","iopub.status.idle":"2023-05-09T12:35:13.860836Z","shell.execute_reply.started":"2023-05-09T12:35:13.851898Z","shell.execute_reply":"2023-05-09T12:35:13.859766Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## dataset","metadata":{}},{"cell_type":"code","source":"def read_image(fragment_id):\n    images = []\n\n    # idxs = range(65)\n    mid = 65 // 2\n    start = mid - CFG.in_chans // 2\n    end = mid + CFG.in_chans // 2\n    idxs = range(start, end)\n\n    for i in tqdm(idxs):\n        \n        image = cv2.imread(CFG.comp_dataset_path + f\"{mode}/{fragment_id}/surface_volume/{i:02}.tif\", 0)\n\n        pad0 = (CFG.tile_size - image.shape[0] % CFG.tile_size)\n        pad1 = (CFG.tile_size - image.shape[1] % CFG.tile_size)\n\n        image = np.pad(image, [(0, pad0), (0, pad1)], constant_values=0)\n\n        images.append(image)\n    images = np.stack(images, axis=2)\n    \n    return images","metadata":{"execution":{"iopub.status.busy":"2023-05-09T12:35:13.862839Z","iopub.execute_input":"2023-05-09T12:35:13.863452Z","iopub.status.idle":"2023-05-09T12:35:13.878060Z","shell.execute_reply.started":"2023-05-09T12:35:13.863409Z","shell.execute_reply":"2023-05-09T12:35:13.877034Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_transforms(data, cfg):\n    if data == 'train':\n        aug = A.Compose(cfg.train_aug_list)\n    elif data == 'valid':\n        aug = A.Compose(cfg.valid_aug_list)\n\n    # print(aug)\n    return aug\n\nclass CustomDataset(Dataset):\n    def __init__(self, images, cfg, labels=None, transform=None):\n        self.images = images\n        self.cfg = cfg\n        self.labels = labels\n        self.transform = transform\n\n    def __len__(self):\n        # return len(self.xyxys)\n        return len(self.images)\n\n    def __getitem__(self, idx):\n        # x1, y1, x2, y2 = self.xyxys[idx]\n        image = self.images[idx]\n        data = self.transform(image=image)\n        image = data['image']\n        return image\n","metadata":{"execution":{"iopub.status.busy":"2023-05-09T12:35:13.879480Z","iopub.execute_input":"2023-05-09T12:35:13.881861Z","iopub.status.idle":"2023-05-09T12:35:13.891631Z","shell.execute_reply.started":"2023-05-09T12:35:13.881810Z","shell.execute_reply":"2023-05-09T12:35:13.890659Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def make_test_dataset(fragment_id):\n    test_images = read_image(fragment_id)\n    \n    x1_list = list(range(0, test_images.shape[1]-CFG.tile_size+1, CFG.stride))\n    y1_list = list(range(0, test_images.shape[0]-CFG.tile_size+1, CFG.stride))\n    \n    test_images_list = []\n    xyxys = []\n    for y1 in y1_list:\n        for x1 in x1_list:\n            y2 = y1 + CFG.tile_size\n            x2 = x1 + CFG.tile_size\n            \n            test_images_list.append(test_images[y1:y2, x1:x2])\n            xyxys.append((x1, y1, x2, y2))\n    xyxys = np.stack(xyxys)\n            \n    test_dataset = CustomDataset(test_images_list, CFG, transform=get_transforms(data='valid', cfg=CFG))\n    \n    test_loader = DataLoader(test_dataset,\n                          batch_size=CFG.batch_size,\n                          shuffle=False,\n                          num_workers=CFG.num_workers, pin_memory=True, drop_last=False)\n    \n    return test_loader, xyxys","metadata":{"execution":{"iopub.status.busy":"2023-05-09T12:35:13.894178Z","iopub.execute_input":"2023-05-09T12:35:13.894905Z","iopub.status.idle":"2023-05-09T12:35:13.904683Z","shell.execute_reply.started":"2023-05-09T12:35:13.894849Z","shell.execute_reply":"2023-05-09T12:35:13.903350Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## model","metadata":{}},{"cell_type":"code","source":"class CustomModel(nn.Module):\n    def __init__(self, cfg, weight=None):\n        super().__init__()\n        self.cfg = cfg\n\n        self.encoder = smp.Unet(\n            encoder_name=cfg.backbone, \n            encoder_weights=weight,\n            in_channels=cfg.in_chans,\n            classes=cfg.target_size,\n            activation=None,\n        )\n\n    def forward(self, image):\n        output = self.encoder(image)\n        output = output.squeeze(-1)\n        return output\n\ndef build_model(cfg, weight=\"imagenet\"):\n    print('model_name', cfg.model_name)\n    print('backbone', cfg.backbone)\n\n    model = CustomModel(cfg, weight)\n    return model\n","metadata":{"execution":{"iopub.status.busy":"2023-05-09T12:35:13.909996Z","iopub.execute_input":"2023-05-09T12:35:13.910401Z","iopub.status.idle":"2023-05-09T12:35:13.921196Z","shell.execute_reply.started":"2023-05-09T12:35:13.910356Z","shell.execute_reply":"2023-05-09T12:35:13.920080Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class EnsembleModel(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.model = nn.ModuleList()\n        for fold in [1, 2, 3]:\n            _model = build_model(CFG, weight=None)\n            #_model.to(device)\n\n            model_path = f'/kaggle/input/vesuvius-models-public/{CFG.exp_name}/vesuvius-models/Unet_fold{fold}_best.pth'\n            state = torch.load(model_path)['model']\n            _model.load_state_dict(state)\n            _model.eval()\n\n            self.model.append(_model)\n    \n    def forward(self,x):\n        output=[]\n        for m in self.model:\n            output.append(m(x))\n        output=torch.stack(output,dim=0).mean(0)\n        return output\n        \n    ","metadata":{"execution":{"iopub.status.busy":"2023-05-09T12:35:13.922890Z","iopub.execute_input":"2023-05-09T12:35:13.923906Z","iopub.status.idle":"2023-05-09T12:35:13.934595Z","shell.execute_reply.started":"2023-05-09T12:35:13.923865Z","shell.execute_reply":"2023-05-09T12:35:13.933867Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def TTA(x:tc.Tensor,model:nn.Module):\n    #x.shape=(batch,c,h,w)\n    if CFG.TTA:\n        shape=x.shape\n        x=[x,*[tc.rot90(x,k=i,dims=(-2,-1)) for i in range(1,4)]]\n        x=tc.cat(x,dim=0)\n        x=model(x)\n        x=torch.sigmoid(x)\n        x=x.reshape(4,shape[0],*shape[2:])\n        x=[tc.rot90(x[i],k=-i,dims=(-2,-1)) for i in range(4)]\n        x=tc.stack(x,dim=0)\n        return x.mean(0)\n    else :\n        x=model(x)\n        x=torch.sigmoid(x)\n        return x","metadata":{"execution":{"iopub.status.busy":"2023-05-09T12:35:13.936174Z","iopub.execute_input":"2023-05-09T12:35:13.937172Z","iopub.status.idle":"2023-05-09T12:35:13.949601Z","shell.execute_reply.started":"2023-05-09T12:35:13.937131Z","shell.execute_reply":"2023-05-09T12:35:13.948670Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"if mode == 'test':\n    fragment_ids = sorted(os.listdir(CFG.comp_dataset_path + mode))\nelse:\n    fragment_ids = [3]\nmodel = EnsembleModel()\nmodel = nn.DataParallel(model, device_ids=[0, 1])\nmodel = model.cuda()","metadata":{"execution":{"iopub.status.busy":"2023-05-09T12:35:13.951119Z","iopub.execute_input":"2023-05-09T12:35:13.952066Z","iopub.status.idle":"2023-05-09T12:35:57.018680Z","shell.execute_reply.started":"2023-05-09T12:35:13.952024Z","shell.execute_reply":"2023-05-09T12:35:57.017540Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## main","metadata":{}},{"cell_type":"code","source":"results = []\nfor fragment_id in fragment_ids:\n    \n    test_loader, xyxys = make_test_dataset(fragment_id)\n    \n    binary_mask = cv2.imread(CFG.comp_dataset_path + f\"{mode}/{fragment_id}/mask.png\", 0)\n    binary_mask = (binary_mask / 255).astype(int)\n    \n    ori_h = binary_mask.shape[0]\n    ori_w = binary_mask.shape[1]\n    # mask = mask / 255\n\n    pad0 = (CFG.tile_size - binary_mask.shape[0] % CFG.tile_size)\n    pad1 = (CFG.tile_size - binary_mask.shape[1] % CFG.tile_size)\n\n    binary_mask = np.pad(binary_mask, [(0, pad0), (0, pad1)], constant_values=0)\n    \n    mask_pred = np.zeros(binary_mask.shape)\n    mask_count = np.zeros(binary_mask.shape)\n\n    for step, (images) in tqdm(enumerate(test_loader), total=len(test_loader)):\n        images = images.cuda()\n        batch_size = images.size(0)\n\n        with torch.no_grad():\n            y_preds = TTA(images,model).cpu().numpy()\n\n        start_idx = step*CFG.batch_size\n        end_idx = start_idx + batch_size\n        for i, (x1, y1, x2, y2) in enumerate(xyxys[start_idx:end_idx]):\n            mask_pred[y1:y2, x1:x2] += y_preds[i].reshape(mask_pred[y1:y2, x1:x2].shape)\n            mask_count[y1:y2, x1:x2] += np.ones((CFG.tile_size, CFG.tile_size))\n    \n    \n    print(f'mask_count_min: {mask_count.min()}')\n    mask_pred /= mask_count\n    \n    fig, axes = plt.subplots(1, 3, figsize=(15, 8))\n    axes[0].imshow(mask_count)\n    axes[1].imshow(mask_pred.copy())\n    \n    \n    \n    mask_pred = mask_pred[:ori_h, :ori_w]\n    binary_mask = binary_mask[:ori_h, :ori_w]\n    \n    mask_pred = (mask_pred >= TH).astype(int)\n    mask_pred *= binary_mask\n    axes[2].imshow(mask_pred)\n    plt.show()\n    \n    inklabels_rle = rle(mask_pred)\n    \n    results.append((fragment_id, inklabels_rle))\n    \n\n    del mask_pred, mask_count\n    del test_loader\n    \n    gc.collect()\n    torch.cuda.empty_cache()","metadata":{"execution":{"iopub.status.busy":"2023-05-09T12:37:26.902293Z","iopub.execute_input":"2023-05-09T12:37:26.903472Z","iopub.status.idle":"2023-05-09T13:21:49.817567Z","shell.execute_reply.started":"2023-05-09T12:37:26.903420Z","shell.execute_reply":"2023-05-09T13:21:49.816251Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## submission","metadata":{}},{"cell_type":"code","source":"sub = pd.DataFrame(results, columns=['Id', 'Predicted'])","metadata":{"execution":{"iopub.status.busy":"2023-05-09T12:36:13.936923Z","iopub.status.idle":"2023-05-09T12:36:13.939211Z","shell.execute_reply.started":"2023-05-09T12:36:13.938883Z","shell.execute_reply":"2023-05-09T12:36:13.938917Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub","metadata":{"execution":{"iopub.status.busy":"2023-05-09T12:36:13.940979Z","iopub.status.idle":"2023-05-09T12:36:13.941916Z","shell.execute_reply.started":"2023-05-09T12:36:13.941596Z","shell.execute_reply":"2023-05-09T12:36:13.941636Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample_sub = pd.read_csv(CFG.comp_dataset_path + 'sample_submission.csv')\nsample_sub = pd.merge(sample_sub[['Id']], sub, on='Id', how='left')","metadata":{"execution":{"iopub.status.busy":"2023-05-09T12:36:13.943448Z","iopub.status.idle":"2023-05-09T12:36:13.944316Z","shell.execute_reply.started":"2023-05-09T12:36:13.944031Z","shell.execute_reply":"2023-05-09T12:36:13.944057Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample_sub","metadata":{"execution":{"iopub.status.busy":"2023-05-09T12:36:13.945896Z","iopub.status.idle":"2023-05-09T12:36:13.946812Z","shell.execute_reply.started":"2023-05-09T12:36:13.946490Z","shell.execute_reply":"2023-05-09T12:36:13.946517Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample_sub.to_csv(\"submission.csv\", index=False)","metadata":{"execution":{"iopub.status.busy":"2023-05-09T12:36:13.948480Z","iopub.status.idle":"2023-05-09T12:36:13.949391Z","shell.execute_reply.started":"2023-05-09T12:36:13.949119Z","shell.execute_reply":"2023-05-09T12:36:13.949147Z"},"trusted":true},"execution_count":null,"outputs":[]}]}