{"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":"# 🦠 Sartorius - Torch Mask R-CNN\n### A self-contained, Torch Mask R-CNN implementation\n\nAdapted from https://www.kaggle.com/julian3833/sartorius-starter-torch-mask-r-cnn-lb-0-202\n\nMain differences to Julian's notebook: \n - use 3 classes for model training\n - use different thresholds for each class\n - use IOUmAP score to select best model\n\n### Changelog\n\n\n| Version | Comments | Validation | LB |\n| --- | --- | --- | --- |\n|51| use CV2 for image processing, set random state in train_test_split | 0.275 | 0.278 |\n|48| fix combine_masks mistake | 0.267 | 0.291 |\n|46| revert cutoffs to V43 | 0.247 | 0.288 |\n|45| update cutoffs | 0.242 | 0.281 |\n|43| update cutoffs | 0.249 | 0.29 |\n|42| BOX_DETECTIONS_PER_IMG = 540 (from Julians notebook) | 0.245 | 0.281 |\n|40| BOX_DETECTIONS_PER_IMG = 450 | 0.245 | 0.28 |\n|39| use different thresholds for each class | 0.242 | 0.279|\n|37| use cell_type as class labels, use best validation epoch using IOU score | 0.241 | 0.274 |\n|28| use cell_type as class labels, use best validation epoch | | 0.265 |\n|26| same as V 16, select correct best model (best_epoch+1) | | 0.274 |\n|16| with `MIN_SCORE=0.5`, use best validation epoch (19) | | 0.263 |\n|11| 30 epochs, use best validation (17) | | 0.203 |\n|5| 10 epochs, Adam optimizer | | 0.135 | \n|1| 8 epochs. With Scheduler. | | 0.197 | \n\n[Julian's](https://www.kaggle.com/julian3833/sartorius-starter-torch-mask-r-cnn-lb-0-202) log:\n\n|| Version | Comments | LB |\n|---|  --- | --- | --- |\n||30| Version 18 with `MIN_SCORE=0.5`. Remove validation. | `0.273` |\n||28| V27 but pick best epoch using mask-only validation loss. 18 epochs. | `0.205` |\n||27| V18 + 7.5% validation (`PCT_IMAGES_VALIDATION`) w/best epoch for pred. Added `BOX_DETECTIONS_PER_IMG` and `MIN_SCORE` but not used yet. | `0.178` |\n||24| 8 epochs. With Scheduler. | `0.195` |\n||23| 8 epochs. Mask loss only. | `0.036` |\n||22| 8 epochs. Normalize. (7 epochs = `0.189`) | `0.202`|\n||19| 3 epochs size 25%. 3 epochs size 50%. 6 epochs full sized| `0.178` |\n||18| 8 epochs. Full sized. Tidied-up code.|  `0.202` |\n||15| 12 -> 15 epochs. Setup classification head with classes. Bugfix in `analyze_train_sample`|  `0.172` |\n|| *14* | *12 epochs. Full sized* |`0.173` |\n|| 8 | 12 epochs. Resize to (256, 256) |`0.057` |\n\n","metadata":{"id":"AJ_abxrh0zRR","papermill":{"duration":0.024534,"end_time":"2021-10-30T15:50:04.957023","exception":false,"start_time":"2021-10-30T15:50:04.932489","status":"completed"},"tags":[]}},{"cell_type":"markdown","source":"## Imports","metadata":{"id":"1NZ-_x8E0zRW","papermill":{"duration":0.023251,"end_time":"2021-10-30T15:50:05.006187","exception":false,"start_time":"2021-10-30T15:50:04.982936","status":"completed"},"tags":[]}},{"cell_type":"code","source":"# The notebooks is self-contained\n# It has very few imports\n# No external dependencies (only the model weights)\n# No train - inference notebooks\n# We only rely on Pytorch\nimport os\nimport random\nimport time\nimport collections\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport cv2\nfrom sklearn.model_selection import train_test_split\nfrom tqdm.notebook import tqdm\n\nimport torch\nimport torchvision\nfrom torchvision.transforms import ToPILImage\nfrom torchvision.transforms import functional as F\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision.models.detection.faster_rcnn import FastRCNNPredictor\nfrom torchvision.models.detection.mask_rcnn import MaskRCNNPredictor","metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","id":"oQYSI0Y00zRX","papermill":{"duration":2.167855,"end_time":"2021-10-30T15:50:07.197808","exception":false,"start_time":"2021-10-30T15:50:05.029953","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-12-01T14:40:26.372661Z","iopub.execute_input":"2022-12-01T14:40:26.373383Z","iopub.status.idle":"2022-12-01T14:40:29.180669Z","shell.execute_reply.started":"2022-12-01T14:40:26.373291Z","shell.execute_reply":"2022-12-01T14:40:29.179903Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Fix randomness\n\ndef fix_all_seeds(seed):\n    np.random.seed(seed)\n    random.seed(seed)\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed(seed)\n    if torch.cuda.is_available():\n        torch.cuda.manual_seed_all(seed)\n        torch.backends.cudnn.deterministic = True\n    \nfix_all_seeds(2021)","metadata":{"id":"Y7fwE02H0zRY","papermill":{"duration":0.032827,"end_time":"2021-10-30T15:50:07.253793","exception":false,"start_time":"2021-10-30T15:50:07.220966","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-12-01T14:40:29.184319Z","iopub.execute_input":"2022-12-01T14:40:29.184544Z","iopub.status.idle":"2022-12-01T14:40:29.260539Z","shell.execute_reply.started":"2022-12-01T14:40:29.184518Z","shell.execute_reply":"2022-12-01T14:40:29.259837Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Configuration","metadata":{"id":"NqZ4eNVK0zRZ","papermill":{"duration":0.022674,"end_time":"2021-10-30T15:50:07.29946","exception":false,"start_time":"2021-10-30T15:50:07.276786","status":"completed"},"tags":[]}},{"cell_type":"code","source":"# Reduced the train dataset to 5000 rows\nTEST = False\n\nif os.path.exists(\"../input/sartorius-cell-instance-segmentation\"):\n    # running on kaggle\n    data_directory = '../input/sartorius-cell-instance-segmentation'\n    DEVICE = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')\n    BATCH_SIZE = 2\n    NUM_EPOCHS = 30\n\nelif 'google.colab' in str(get_ipython()):\n    # running on CoLab\n    from google.colab import drive\n    drive.mount('/content/drive')\n    data_directory = '/content/drive/MyDrive/input'\n    DEVICE = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')\n    BATCH_SIZE = 1\n    NUM_EPOCHS = 5\n    \nelse:\n    data_directory = 'input'\n    DEVICE = torch.device('cpu')\n    BATCH_SIZE = 2\n    NUM_EPOCHS = 1\n    TEST = True\n\nTRAIN_CSV = f\"{data_directory}/train.csv\"\nTRAIN_PATH = f\"{data_directory}/train\"\nTEST_PATH = f\"{data_directory}/test\"\n\nWIDTH = 704\nHEIGHT = 520\n\nresize_factor = False # 0.5\n\n# Normalize to resnet mean and std if True.\nNORMALIZE = False\nRESNET_MEAN = (0.485, 0.456, 0.406)\nRESNET_STD = (0.229, 0.224, 0.225)\n\n# No changes tried with the optimizer yet.\nMOMENTUM = 0.9\nLEARNING_RATE = 0.001\nWEIGHT_DECAY = 0.0005\n\n# Changes the confidence required for a pixel to be kept for a mask. \n# Only used 0.5 till now.\n# MASK_THRESHOLD = 0.5\n# MIN_SCORE = 0.5\n# cell type specific thresholds\ncell_type_dict = {\"astro\": 1, \"cort\": 2, \"shsy5y\": 3}\nmask_threshold_dict = {1: 0.55, 2: 0.75, 3:  0.6}\nmin_score_dict = {1: 0.55, 2: 0.75, 3: 0.5}\n\n# Use a StepLR scheduler if True. \nUSE_SCHEDULER = False\n\nPCT_IMAGES_VALIDATION = 0.075\n\nBOX_DETECTIONS_PER_IMG = 540","metadata":{"id":"VSPe6quz0zRZ","lines_to_next_cell":1,"outputId":"e2cca0e2-0ada-471b-e688-33ee16049407","papermill":{"duration":0.071974,"end_time":"2021-10-30T15:50:07.394165","exception":false,"start_time":"2021-10-30T15:50:07.322191","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-12-01T14:40:29.261757Z","iopub.execute_input":"2022-12-01T14:40:29.262009Z","iopub.status.idle":"2022-12-01T14:40:29.274226Z","shell.execute_reply.started":"2022-12-01T14:40:29.261966Z","shell.execute_reply":"2022-12-01T14:40:29.273453Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Utilities","metadata":{"id":"iIpvad7y0zRb","papermill":{"duration":0.022537,"end_time":"2021-10-30T15:50:07.439624","exception":false,"start_time":"2021-10-30T15:50:07.417087","status":"completed"},"tags":[]}},{"cell_type":"code","source":"# ref: https://www.kaggle.com/inversion/run-length-decoding-quick-start\ndef rle_decode(mask_rle, shape, color=1):\n    '''\n    mask_rle: run-length as string formated (start length)\n    shape: (height, width, channels) of array to return\n    color: color for the mask\n    Returns numpy array (mask)\n\n    '''\n    s = mask_rle.split()\n\n    starts = list(map(lambda x: int(x) - 1, s[0::2]))\n    lengths = list(map(int, s[1::2]))\n    ends = [x + y for x, y in zip(starts, lengths)]\n    if len(shape)==3:\n        img = np.zeros((shape[0] * shape[1], shape[2]), dtype=np.float32)\n    else:\n        img = np.zeros(shape[0] * shape[1], dtype=np.float32)\n    for start, end in zip(starts, ends):\n        img[start : end] = color\n\n    return img.reshape(shape)\n\n\ndef rle_encoding(x):\n    dots = np.where(x.flatten() == 1)[0]\n    run_lengths = []\n    prev = -2\n    for b in dots:\n        if (b>prev+1): run_lengths.extend((b + 1, 0))\n        run_lengths[-1] += 1\n        prev = b\n    return ' '.join(map(str, run_lengths))\n\n\ndef remove_overlapping_pixels(mask, other_masks):\n    for other_mask in other_masks:\n        if np.sum(np.logical_and(mask, other_mask)) > 0:\n            mask[np.logical_and(mask, other_mask)] = 0\n    return mask\n\ndef combine_masks(masks, mask_threshold):\n    \"\"\"\n    combine masks into one image\n    \"\"\"\n    maskimg = np.zeros((HEIGHT, WIDTH))\n    # print(len(masks.shape), masks.shape)\n    for m, mask in enumerate(masks,1):\n        maskimg[mask>mask_threshold] = m\n    return maskimg\n\n\ndef get_filtered_masks(pred):\n    \"\"\"\n    filter masks using MIN_SCORE for mask and MAX_THRESHOLD for pixels\n    \"\"\"\n    use_masks = []   \n    for i, mask in enumerate(pred[\"masks\"]):\n\n        # Filter-out low-scoring results. Not tried yet.\n        scr = pred[\"scores\"][i].cpu().item()\n        label = pred[\"labels\"][i].cpu().item()\n        if scr > min_score_dict[label]:\n            mask = mask.cpu().numpy().squeeze()\n            # Keep only highly likely pixels\n            binary_mask = mask > mask_threshold_dict[label]\n            binary_mask = remove_overlapping_pixels(binary_mask, use_masks)\n            use_masks.append(binary_mask)\n\n    return use_masks","metadata":{"papermill":{"duration":0.034074,"end_time":"2021-10-27T04:04:40.693264","exception":false,"start_time":"2021-10-27T04:04:40.65919","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-12-01T14:40:29.276635Z","iopub.execute_input":"2022-12-01T14:40:29.277105Z","iopub.status.idle":"2022-12-01T14:40:29.292316Z","shell.execute_reply.started":"2022-12-01T14:40:29.277070Z","shell.execute_reply":"2022-12-01T14:40:29.291525Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Metric: mean of the precision values at each IoU threshold\n\nRef: https://www.kaggle.com/theoviel/competition-metric-map-iou","metadata":{"papermill":{"duration":0.022763,"end_time":"2021-10-30T15:50:07.545798","exception":false,"start_time":"2021-10-30T15:50:07.523035","status":"completed"},"tags":[]}},{"cell_type":"code","source":"def compute_iou(labels, y_pred, verbose=0):\n    \"\"\"\n    Computes the IoU for instance labels and predictions.\n\n    Args:\n        labels (np array): Labels.\n        y_pred (np array): predictions\n\n    Returns:\n        np array: IoU matrix, of size true_objects x pred_objects.\n    \"\"\"\n\n    true_objects = len(np.unique(labels))\n    pred_objects = len(np.unique(y_pred))\n\n    if verbose:\n        print(\"Number of true objects: {}\".format(true_objects))\n        print(\"Number of predicted objects: {}\".format(pred_objects))\n\n    # Compute intersection between all objects\n    intersection = np.histogram2d(\n        labels.flatten(), y_pred.flatten(), bins=(true_objects, pred_objects)\n    )[0]\n\n    # Compute areas (needed for finding the union between all objects)\n    area_true = np.histogram(labels, bins=true_objects)[0]\n    area_pred = np.histogram(y_pred, bins=pred_objects)[0]\n    area_true = np.expand_dims(area_true, -1)\n    area_pred = np.expand_dims(area_pred, 0)\n\n    # Compute union\n    union = area_true + area_pred - intersection\n    intersection = intersection[1:, 1:] # exclude background\n    union = union[1:, 1:]\n    union[union == 0] = 1e-9\n    iou = intersection / union\n    \n    return iou  \n\ndef precision_at(threshold, iou):\n    \"\"\"\n    Computes the precision at a given threshold.\n\n    Args:\n        threshold (float): Threshold.\n        iou (np array): IoU matrix.\n\n    Returns:\n        int: Number of true positives,\n        int: Number of false positives,\n        int: Number of false negatives.\n    \"\"\"\n    matches = iou > threshold\n    true_positives = np.sum(matches, axis=1) == 1  # Correct objects\n    false_positives = np.sum(matches, axis=0) == 0  # Missed objects\n    false_negatives = np.sum(matches, axis=1) == 0  # Extra objects\n    tp, fp, fn = (\n        np.sum(true_positives),\n        np.sum(false_positives),\n        np.sum(false_negatives),\n    )\n    return tp, fp, fn\n\ndef iou_map(truths, preds, verbose=0):\n    \"\"\"\n    Computes the metric for the competition.\n    Masks contain the segmented pixels where each object has one value associated,\n    and 0 is the background.\n\n    Args:\n        truths (list of masks): Ground truths.\n        preds (list of masks): Predictions.\n        verbose (int, optional): Whether to print infos. Defaults to 0.\n\n    Returns:\n        float: mAP.\n    \"\"\"\n    ious = [compute_iou(truth, pred, verbose) for truth, pred in zip(truths, preds)]\n\n    if verbose:\n        print(\"Thresh\\tTP\\tFP\\tFN\\tPrec.\")\n\n    prec = []\n    for t in np.arange(0.5, 1.0, 0.05):\n        tps, fps, fns = 0, 0, 0\n        for iou in ious:\n            tp, fp, fn = precision_at(t, iou)\n            tps += tp\n            fps += fp\n            fns += fn\n\n        p = tps / (tps + fps + fns)\n        prec.append(p)\n\n        if verbose:\n            print(\"{:1.3f}\\t{}\\t{}\\t{}\\t{:1.3f}\".format(t, tps, fps, fns, p))\n\n    if verbose:\n        print(\"AP\\t-\\t-\\t-\\t{:1.3f}\".format(np.mean(prec)))\n\n    return np.mean(prec)\n\n\ndef get_score(ds, mdl):\n    \"\"\"\n    Get average IOU mAP score for a dataset\n    \"\"\"\n    mdl.eval()\n    iouscore = 0\n    for i in tqdm(range(len(ds))):\n        img, targets = ds[i]\n        with torch.no_grad():\n            result = mdl([img.to(DEVICE)])[0]\n            \n        masks = combine_masks(targets['masks'], 0.5)\n        labels = pd.Series(result['labels'].cpu().numpy()).value_counts()\n\n        mask_threshold = mask_threshold_dict[labels.sort_values().index[-1]]\n        pred_masks = combine_masks(get_filtered_masks(result), mask_threshold)\n        iouscore += iou_map([masks],[pred_masks])\n    return iouscore / len(ds)\n","metadata":{"papermill":{"duration":0.042481,"end_time":"2021-10-30T15:50:07.612219","exception":false,"start_time":"2021-10-30T15:50:07.569738","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-12-01T14:40:29.293858Z","iopub.execute_input":"2022-12-01T14:40:29.294145Z","iopub.status.idle":"2022-12-01T14:40:29.313159Z","shell.execute_reply.started":"2022-12-01T14:40:29.294092Z","shell.execute_reply":"2022-12-01T14:40:29.312447Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Transformations\nJust Horizontal and Vertical Flip for now.\n\nNormalization to Resnet's mean and std can be performed using the parameter `NORMALIZE` in the top cell.\n\nThe first 3 transformations come from [this](https://www.kaggle.com/abhishek/maskrcnn-utils) utils package by Abishek, `VerticalFlip` is my adaption of HorizontalFlip, and `Normalize` is of my own.","metadata":{"papermill":{"duration":0.023883,"end_time":"2021-10-30T15:50:07.659293","exception":false,"start_time":"2021-10-30T15:50:07.63541","status":"completed"},"tags":[]}},{"cell_type":"code","source":"# These are slight redefinitions of torch.transformation classes\n# The difference is that they handle the target and the mask\n# Copied from Abishek, added new ones\nclass Compose:\n    def __init__(self, transforms):\n        self.transforms = transforms\n\n    def __call__(self, image, target):\n        for t in self.transforms:\n            image, target = t(image, target)\n        return image, target\n\nclass VerticalFlip:\n    def __init__(self, prob):\n        self.prob = prob\n\n    def __call__(self, image, target):\n        if random.random() < self.prob:\n            height, width = image.shape[-2:]\n            image = image.flip(-2)\n            bbox = target[\"boxes\"]\n            bbox[:, [1, 3]] = height - bbox[:, [3, 1]]\n            target[\"boxes\"] = bbox\n            target[\"masks\"] = target[\"masks\"].flip(-2)\n        return image, target\n\nclass HorizontalFlip:\n    def __init__(self, prob):\n        self.prob = prob\n\n    def __call__(self, image, target):\n        if random.random() < self.prob:\n            height, width = image.shape[-2:]\n            image = image.flip(-1)\n            bbox = target[\"boxes\"]\n            bbox[:, [0, 2]] = width - bbox[:, [2, 0]]\n            target[\"boxes\"] = bbox\n            target[\"masks\"] = target[\"masks\"].flip(-1)\n        return image, target\n\nclass Normalize:\n    def __call__(self, image, target):\n        image = F.normalize(image, RESNET_MEAN, RESNET_STD)\n        return image, target\n\nclass ToTensor:\n    def __call__(self, image, target):\n        image = F.to_tensor(image)\n        return image, target\n    \n\ndef get_transform(train):\n    transforms = [ToTensor()]\n    if NORMALIZE:\n        transforms.append(Normalize())\n    \n    # Data augmentation for train\n    if train: \n        transforms.append(HorizontalFlip(0.5))\n        transforms.append(VerticalFlip(0.5))\n\n    return Compose(transforms)","metadata":{"papermill":{"duration":0.038125,"end_time":"2021-10-30T15:50:07.72041","exception":false,"start_time":"2021-10-30T15:50:07.682285","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-12-01T14:40:29.315191Z","iopub.execute_input":"2022-12-01T14:40:29.315674Z","iopub.status.idle":"2022-12-01T14:40:29.328701Z","shell.execute_reply.started":"2022-12-01T14:40:29.315639Z","shell.execute_reply":"2022-12-01T14:40:29.327824Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Training Dataset and DataLoader","metadata":{"id":"hHT_aovU0zRd","papermill":{"duration":0.022607,"end_time":"2021-10-30T15:50:07.76565","exception":false,"start_time":"2021-10-30T15:50:07.743043","status":"completed"},"tags":[]}},{"cell_type":"code","source":"cell_type_dict = {\"astro\": 1, \"cort\": 2, \"shsy5y\": 3}\n\nclass CellDataset(Dataset):\n    def __init__(self, image_dir, df, transforms=None, resize=False):\n        self.transforms = transforms\n        self.image_dir = image_dir\n        self.df = df\n        \n        self.should_resize = resize is not False\n        if self.should_resize:\n            self.height = int(HEIGHT * resize)\n            self.width = int(WIDTH * resize)\n            print(\"image size used:\", self.height, self.width)\n        else:\n            self.height = HEIGHT\n            self.width = WIDTH\n        \n        self.image_info = collections.defaultdict(dict)\n        temp_df = self.df.groupby([\"id\", \"cell_type\"])['annotation'].agg(lambda x: list(x)).reset_index()\n        for index, row in temp_df.iterrows():\n            self.image_info[index] = {\n                    'image_id': row['id'],\n                    'image_path': os.path.join(self.image_dir, row['id'] + '.png'),\n                    'annotations': list(row[\"annotation\"]),\n                    'cell_type': cell_type_dict[row[\"cell_type\"]]\n                    }\n            \n    def get_box(self, a_mask):\n        ''' Get the bounding box of a given mask '''\n        pos = np.where(a_mask)\n        xmin = np.min(pos[1])\n        xmax = np.max(pos[1])\n        ymin = np.min(pos[0])\n        ymax = np.max(pos[0])\n        return [xmin, ymin, xmax, ymax]\n\n    def __getitem__(self, idx):\n        ''' Get the image and the target'''\n        \n        img_path = self.image_info[idx][\"image_path\"]\n        img = cv2.imread(img_path, cv2.IMREAD_COLOR)\n        \n        if self.should_resize:\n            img = cv2.resize(img, (self.width, self.height))\n\n        info = self.image_info[idx]\n\n        n_objects = len(info['annotations'])\n        masks = np.zeros((len(info['annotations']), self.height, self.width), dtype=np.uint8)\n        boxes = []\n        labels = []\n        for i, annotation in enumerate(info['annotations']):\n            a_mask = rle_decode(annotation, (HEIGHT, WIDTH))\n            \n            if self.should_resize:\n                a_mask = cv2.resize(a_mask, (self.width, self.height))\n            \n            a_mask = np.array(a_mask) > 0\n            masks[i, :, :] = a_mask\n            \n            boxes.append(self.get_box(a_mask))\n\n        # labels\n        labels = [int(info[\"cell_type\"]) for _ in range(n_objects)]\n        #labels = [1 for _ in range(n_objects)]\n        \n        \n        boxes = torch.as_tensor(boxes, dtype=torch.float32)\n        labels = torch.as_tensor(labels, dtype=torch.int64)\n        masks = torch.as_tensor(masks, dtype=torch.uint8)\n\n        image_id = torch.tensor([idx])\n        area = (boxes[:, 3] - boxes[:, 1]) * (boxes[:, 2] - boxes[:, 0])\n        iscrowd = torch.zeros((n_objects,), dtype=torch.int64)\n\n        # This is the required target for the Mask R-CNN\n        target = {\n            'boxes': boxes,\n            'labels': labels,\n            'masks': masks,\n            'image_id': image_id,\n            'area': area,\n            'iscrowd': iscrowd\n        }\n\n        if self.transforms is not None:\n            img, target = self.transforms(img, target)\n\n        return img, target\n\n    def __len__(self):\n        return len(self.image_info)","metadata":{"id":"C9Y03YgA0zRd","papermill":{"duration":0.044667,"end_time":"2021-10-30T15:50:07.833528","exception":false,"start_time":"2021-10-30T15:50:07.788861","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-12-01T14:40:29.331121Z","iopub.execute_input":"2022-12-01T14:40:29.331610Z","iopub.status.idle":"2022-12-01T14:40:29.349974Z","shell.execute_reply.started":"2022-12-01T14:40:29.331567Z","shell.execute_reply":"2022-12-01T14:40:29.349245Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_base = pd.read_csv(TRAIN_CSV, nrows=5000 if TEST else None)","metadata":{"id":"tmCw3DTL0zRe","papermill":{"duration":0.594812,"end_time":"2021-10-30T15:50:08.451409","exception":false,"start_time":"2021-10-30T15:50:07.856597","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-12-01T14:40:29.351341Z","iopub.execute_input":"2022-12-01T14:40:29.351583Z","iopub.status.idle":"2022-12-01T14:40:30.051327Z","shell.execute_reply.started":"2022-12-01T14:40:29.351553Z","shell.execute_reply":"2022-12-01T14:40:30.050548Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_images = df_base.groupby([\"id\", \"cell_type\"]).agg({'annotation': 'count'}).sort_values(\"annotation\", ascending=False).reset_index()\n\nfor ct in cell_type_dict:\n    ctdf = df_images[df_images[\"cell_type\"]==ct].copy()\n    if len(ctdf)>0:\n        ctdf['quantiles'] = pd.qcut(ctdf['annotation'], 5)\n        display(ctdf.head())","metadata":{"id":"pQXGwdnL0zRe","outputId":"08e892c7-aa0c-4b96-de86-7eb8a4234f16","papermill":{"duration":0.151173,"end_time":"2021-10-30T15:50:08.629709","exception":false,"start_time":"2021-10-30T15:50:08.478536","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-12-01T14:40:30.053398Z","iopub.execute_input":"2022-12-01T14:40:30.053854Z","iopub.status.idle":"2022-12-01T14:40:30.130671Z","shell.execute_reply.started":"2022-12-01T14:40:30.053812Z","shell.execute_reply":"2022-12-01T14:40:30.129861Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# We used this as a reference to fill BOX_DETECTIONS_PER_IMG=140\ndf_images[['annotation']].describe().astype(int)","metadata":{"id":"oCRxcK2f0zRf","outputId":"ea5a6673-5758-4964-cdde-03235c5c8215","papermill":{"duration":0.041853,"end_time":"2021-10-30T15:50:08.783532","exception":false,"start_time":"2021-10-30T15:50:08.741679","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-12-01T14:40:30.133448Z","iopub.execute_input":"2022-12-01T14:40:30.133931Z","iopub.status.idle":"2022-12-01T14:40:30.149355Z","shell.execute_reply.started":"2022-12-01T14:40:30.133893Z","shell.execute_reply":"2022-12-01T14:40:30.148405Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Use the quantiles of amoount of annotations to stratify\ndf_images_train, df_images_val = train_test_split(df_images, stratify=df_images['cell_type'], \n                                                  test_size=PCT_IMAGES_VALIDATION,\n                                                  random_state=1234)\ndf_train = df_base[df_base['id'].isin(df_images_train['id'])]\ndf_val = df_base[df_base['id'].isin(df_images_val['id'])]\nprint(f\"Images in train set:           {len(df_images_train)}\")\nprint(f\"Annotations in train set:      {len(df_train)}\")\nprint(f\"Images in validation set:      {len(df_images_val)}\")\nprint(f\"Annotations in validation set: {len(df_val)}\")","metadata":{"id":"2v7VvtTp0zRf","outputId":"82690b02-dd4b-4c1d-ed5d-78e30bf084a2","papermill":{"duration":0.057122,"end_time":"2021-10-30T15:50:08.872848","exception":false,"start_time":"2021-10-30T15:50:08.815726","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-12-01T14:40:30.150708Z","iopub.execute_input":"2022-12-01T14:40:30.151037Z","iopub.status.idle":"2022-12-01T14:40:30.175130Z","shell.execute_reply.started":"2022-12-01T14:40:30.151003Z","shell.execute_reply":"2022-12-01T14:40:30.174323Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ds_train = CellDataset(TRAIN_PATH, df_train, resize=resize_factor, transforms=get_transform(train=True))\ndl_train = DataLoader(ds_train, batch_size=BATCH_SIZE, shuffle=True, pin_memory=True,\n                      num_workers=2, collate_fn=lambda x: tuple(zip(*x)))\n\nds_val = CellDataset(TRAIN_PATH, df_val, resize=resize_factor, transforms=get_transform(train=False))\ndl_val = DataLoader(ds_val, batch_size=BATCH_SIZE, shuffle=True, pin_memory=True,\n                    num_workers=2, collate_fn=lambda x: tuple(zip(*x)))","metadata":{"id":"kUcpAbdO0zRg","papermill":{"duration":0.113642,"end_time":"2021-10-30T15:50:09.011921","exception":false,"start_time":"2021-10-30T15:50:08.898279","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-12-01T14:40:30.176459Z","iopub.execute_input":"2022-12-01T14:40:30.176735Z","iopub.status.idle":"2022-12-01T14:40:30.254940Z","shell.execute_reply.started":"2022-12-01T14:40:30.176702Z","shell.execute_reply":"2022-12-01T14:40:30.254242Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Train model","metadata":{"id":"y8JNMn770zRg","papermill":{"duration":0.026132,"end_time":"2021-10-30T15:50:09.063742","exception":false,"start_time":"2021-10-30T15:50:09.03761","status":"completed"},"tags":[]}},{"cell_type":"markdown","source":"## setup model","metadata":{"papermill":{"duration":0.026483,"end_time":"2021-10-30T15:50:09.116837","exception":false,"start_time":"2021-10-30T15:50:09.090354","status":"completed"},"tags":[]}},{"cell_type":"code","source":"# Override pythorch checkpoint with an \"offline\" version of the file\n!mkdir -p /root/.cache/torch/hub/checkpoints/\n!cp ../input/cocopre/maskrcnn_resnet50_fpn_coco-bf2d0c1e.pth /root/.cache/torch/hub/checkpoints/maskrcnn_resnet50_fpn_coco-bf2d0c1e.pth","metadata":{"id":"VMaqdcNa0zRg","outputId":"c5ca31a5-6d8d-4639-e547-f44e5772c725","papermill":{"duration":4.941361,"end_time":"2021-10-30T15:50:14.083567","exception":false,"start_time":"2021-10-30T15:50:09.142206","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-12-01T14:40:30.256240Z","iopub.execute_input":"2022-12-01T14:40:30.256514Z","iopub.status.idle":"2022-12-01T14:40:36.313429Z","shell.execute_reply.started":"2022-12-01T14:40:30.256465Z","shell.execute_reply":"2022-12-01T14:40:36.312412Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_model(num_classes, model_chkpt=None):\n    # This is just a dummy value for the classification head\n    \n    if NORMALIZE:\n        model = torchvision.models.detection.maskrcnn_resnet50_fpn(pretrained=True,\n                                                                   box_detections_per_img=BOX_DETECTIONS_PER_IMG,\n                                                                   image_mean=RESNET_MEAN,\n                                                                   image_std=RESNET_STD)\n    else:\n        model = torchvision.models.detection.maskrcnn_resnet50_fpn(pretrained=True,\n                                                                   box_detections_per_img=BOX_DETECTIONS_PER_IMG)\n\n    # get the number of input features for the classifier\n    in_features = model.roi_heads.box_predictor.cls_score.in_features\n    # replace the pre-trained head with a new one\n    model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes+1)\n\n    # now get the number of input features for the mask classifier\n    in_features_mask = model.roi_heads.mask_predictor.conv5_mask.in_channels\n    hidden_layer = 256\n    # and replace the mask predictor with a new one\n    model.roi_heads.mask_predictor = MaskRCNNPredictor(in_features_mask, hidden_layer, num_classes+1)\n    \n    if model_chkpt:\n        model.load_state_dict(torch.load(model_chkpt, map_location=DEVICE))\n    return model\n\n# Get the Mask R-CNN model\n# The model does classification, bounding boxes and MASKs for individuals, all at the same time\n# We only care about MASKS\nmodel = get_model(len(cell_type_dict))\nmodel.to(DEVICE)\n\n# TODO: try removing this for\nfor param in model.parameters():\n    param.requires_grad = True\n    \nmodel.train();","metadata":{"id":"3Ds5dHex0zRh","papermill":{"duration":3.679063,"end_time":"2021-10-30T15:50:17.789168","exception":false,"start_time":"2021-10-30T15:50:14.110105","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-12-01T14:40:36.315981Z","iopub.execute_input":"2022-12-01T14:40:36.316209Z","iopub.status.idle":"2022-12-01T14:40:40.200414Z","shell.execute_reply.started":"2022-12-01T14:40:36.316181Z","shell.execute_reply":"2022-12-01T14:40:40.199666Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Training loop!","metadata":{"id":"RvawgUM30zRh","papermill":{"duration":0.028196,"end_time":"2021-10-30T15:50:17.847237","exception":false,"start_time":"2021-10-30T15:50:17.819041","status":"completed"},"tags":[]}},{"cell_type":"code","source":"params = [p for p in model.parameters() if p.requires_grad]\noptimizer = torch.optim.SGD(params, lr=LEARNING_RATE, momentum=MOMENTUM, weight_decay=WEIGHT_DECAY)\n#optimizer = torch.optim.Adam(params, lr=LEARNING_RATE, weight_decay=WEIGHT_DECAY)\n\nlr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=5, gamma=0.1)\n\nn_batches, n_batches_val = len(dl_train), len(dl_val)\n\nvalidation_mask_losses = []\n\nfor epoch in range(1, NUM_EPOCHS + 1):\n    print(f\"Starting epoch {epoch} of {NUM_EPOCHS}\")\n\n    time_start = time.time()\n    loss_accum = 0.0\n    loss_mask_accum = 0.0\n    loss_classifier_accum = 0.0\n    for batch_idx, (images, targets) in enumerate(dl_train, 1):\n    \n        # Predict\n        images = list(image.to(DEVICE) for image in images)\n        targets = [{k: v.to(DEVICE) for k, v in t.items()} for t in targets]\n\n        loss_dict = model(images, targets)\n        loss = sum(loss for loss in loss_dict.values())\n        \n        # Backprop\n        optimizer.zero_grad()\n        loss.backward()\n        optimizer.step()\n        \n        # Logging\n        loss_mask = loss_dict['loss_mask'].item()\n        loss_accum += loss.item()\n        loss_mask_accum += loss_mask\n        loss_classifier_accum += loss_dict['loss_classifier'].item()\n        \n        if batch_idx % 500 == 0:\n            print(f\"    [Batch {batch_idx:3d} / {n_batches:3d}] Batch train loss: {loss.item():7.3f}. Mask-only loss: {loss_mask:7.3f}.\")\n                        \n    if USE_SCHEDULER:\n        lr_scheduler.step()\n\n    # Train losses\n    train_loss = loss_accum / n_batches\n    train_loss_mask = loss_mask_accum / n_batches\n    train_loss_classifier = loss_classifier_accum / n_batches\n\n    # Validation\n    val_loss_accum = 0\n    val_loss_mask_accum = 0\n    val_loss_classifier_accum = 0\n    \n    with torch.no_grad():\n        for batch_idx, (images, targets) in enumerate(dl_val, 1):\n            images = list(image.to(DEVICE) for image in images)\n            targets = [{k: v.to(DEVICE) for k, v in t.items()} for t in targets]\n\n            val_loss_dict = model(images, targets)\n            val_batch_loss = sum(loss for loss in val_loss_dict.values())\n            val_loss_accum += val_batch_loss.item()\n            val_loss_mask_accum += val_loss_dict['loss_mask'].item()\n            val_loss_classifier_accum += val_loss_dict['loss_classifier'].item()\n\n    # Validation losses\n    val_loss = val_loss_accum / n_batches_val\n    val_loss_mask = val_loss_mask_accum / n_batches_val\n    val_loss_classifier = val_loss_classifier_accum / n_batches_val\n    elapsed = time.time() - time_start\n\n    validation_mask_losses.append(val_loss_mask)\n\n    torch.save(model.state_dict(), f\"pytorch_model-e{epoch}.bin\")\n    prefix = f\"[Epoch {epoch:2d} / {NUM_EPOCHS:2d}]\"\n    print(prefix)\n    print(f\"{prefix} Train mask-only loss: {train_loss_mask:7.3f}, classifier loss {train_loss_classifier:7.3f}\")\n    print(f\"{prefix} Val mask-only loss  : {val_loss_mask:7.3f}, classifier loss {val_loss_classifier:7.3f}\")\n    print(prefix)\n    print(f\"{prefix} Train loss: {train_loss:7.3f}. Val loss: {val_loss:7.3f} [{elapsed:.0f} secs]\")\n    print(prefix)","metadata":{"id":"52B16JCW0zRh","outputId":"9b9c5ad9-58c1-4d50-dd7c-79b18b1e57b7","papermill":{"duration":7670.472684,"end_time":"2021-10-30T17:58:08.347309","exception":false,"start_time":"2021-10-30T15:50:17.874625","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-12-01T14:40:40.201610Z","iopub.execute_input":"2022-12-01T14:40:40.201861Z","iopub.status.idle":"2022-12-01T16:56:27.015107Z","shell.execute_reply.started":"2022-12-01T14:40:40.201827Z","shell.execute_reply":"2022-12-01T16:56:27.014204Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Analyze prediction results for train set","metadata":{"id":"MspyyJlP0zRh","papermill":{"duration":0.054203,"end_time":"2021-10-30T17:58:08.456349","exception":false,"start_time":"2021-10-30T17:58:08.402146","status":"completed"},"tags":[]}},{"cell_type":"code","source":"# Plots: the image, The image + the ground truth mask, The image + the predicted mask\n\ndef analyze_train_sample(model, ds_train, sample_index):\n    \n    img, targets = ds_train[sample_index]\n    #print(img.shape)\n    l = np.unique(targets[\"labels\"])\n    ig, ax = plt.subplots(nrows=1, ncols=3, figsize=(20,60), facecolor=\"#fefefe\")\n    ax[0].imshow(img.numpy().transpose((1,2,0)))\n    ax[0].set_title(f\"cell type {l}\")\n    ax[0].axis(\"off\")\n    \n    masks = combine_masks(targets['masks'], 0.5)\n    #plt.imshow(img.numpy().transpose((1,2,0)))\n    ax[1].imshow(masks)\n    ax[1].set_title(f\"Ground truth, {len(targets['masks'])} cells\")\n    ax[1].axis(\"off\")\n    \n    model.eval()\n    with torch.no_grad():\n        preds = model([img.to(DEVICE)])[0]\n    \n    l = pd.Series(preds['labels'].cpu().numpy()).value_counts()\n    lstr = \"\"\n    for i in l.index:\n        lstr += f\"{l[i]}x{i} \"\n    #print(l, l.sort_values().index[-1])\n    #plt.imshow(img.cpu().numpy().transpose((1,2,0)))\n    mask_threshold = mask_threshold_dict[l.sort_values().index[-1]]\n    #print(mask_threshold)\n    pred_masks = combine_masks(get_filtered_masks(preds), mask_threshold)\n    ax[2].imshow(pred_masks)\n    ax[2].set_title(f\"Predictions, labels: {lstr}\")\n    ax[2].axis(\"off\")\n    plt.show() \n    \n    #print(masks.shape, pred_masks.shape)\n    score = iou_map([masks],[pred_masks])\n    print(\"Score:\", score)    \n    \n    \n# NOTE: It puts the model in eval mode!! Revert for re-training\nanalyze_train_sample(model, ds_train, 20)","metadata":{"id":"dJOE3B0u0zRi","papermill":{"duration":2.317703,"end_time":"2021-10-30T17:58:10.828377","exception":false,"start_time":"2021-10-30T17:58:08.510674","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-12-01T16:56:27.017096Z","iopub.execute_input":"2022-12-01T16:56:27.017754Z","iopub.status.idle":"2022-12-01T16:56:28.712251Z","shell.execute_reply.started":"2022-12-01T16:56:27.017709Z","shell.execute_reply":"2022-12-01T16:56:28.711456Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"analyze_train_sample(model, ds_train, 102)","metadata":{"id":"ZRx9K5n60zRi","outputId":"3ff2b8d0-8e4d-46a0-b3cb-7f2fad862808","papermill":{"duration":1.189143,"end_time":"2021-10-30T17:58:12.06041","exception":false,"start_time":"2021-10-30T17:58:10.871267","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-12-01T16:56:28.713789Z","iopub.execute_input":"2022-12-01T16:56:28.714073Z","iopub.status.idle":"2022-12-01T16:56:29.327910Z","shell.execute_reply.started":"2022-12-01T16:56:28.714034Z","shell.execute_reply":"2022-12-01T16:56:29.327087Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"analyze_train_sample(model, ds_train, 7)","metadata":{"id":"Rn6YeGVZ0zRi","outputId":"3b0b0c2b-1f0b-40b0-9529-275d24c3afa3","papermill":{"duration":5.359614,"end_time":"2021-10-30T17:58:17.470546","exception":false,"start_time":"2021-10-30T17:58:12.110932","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-12-01T16:56:29.329523Z","iopub.execute_input":"2022-12-01T16:56:29.329966Z","iopub.status.idle":"2022-12-01T16:56:34.208938Z","shell.execute_reply.started":"2022-12-01T16:56:29.329925Z","shell.execute_reply":"2022-12-01T16:56:34.208131Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Get the model from the best epoch","metadata":{"id":"Jon4MSmk0zRj","papermill":{"duration":0.059699,"end_time":"2021-10-30T17:58:17.590822","exception":false,"start_time":"2021-10-30T17:58:17.531123","status":"completed"},"tags":[]}},{"cell_type":"code","source":"# Epochs with their losses and IOU scores\n\nval_scores = pd.DataFrame()\nfor e, val_loss in enumerate(validation_mask_losses):\n    model_chk = f\"pytorch_model-e{e+1}.bin\"\n    print(\"Loading:\", model_chk)\n    model = get_model(len(cell_type_dict), model_chk)\n    model.load_state_dict(torch.load(model_chk))\n    model = model.to(DEVICE)\n    val_scores.loc[e,\"mask_loss\"] = val_loss\n    val_scores.loc[e,\"score\"] = get_score(ds_val, model)\n    \n    \ndisplay(val_scores.sort_values(\"score\", ascending=False))\n\nbest_epoch = np.argmax(val_scores[\"score\"])\nprint(best_epoch+1)","metadata":{"id":"O0ejRcer0zRj","outputId":"0806ad69-abcf-440a-c9ad-d5a2a454abe4","papermill":{"duration":2288.212204,"end_time":"2021-10-30T18:36:25.86261","exception":false,"start_time":"2021-10-30T17:58:17.650406","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-12-01T16:56:34.210172Z","iopub.execute_input":"2022-12-01T16:56:34.210872Z","iopub.status.idle":"2022-12-01T17:53:01.192935Z","shell.execute_reply.started":"2022-12-01T16:56:34.210835Z","shell.execute_reply":"2022-12-01T17:53:01.192153Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Prediction","metadata":{"id":"bTNGfMuQ0zRi","papermill":{"duration":0.080258,"end_time":"2021-10-30T18:36:26.026589","exception":false,"start_time":"2021-10-30T18:36:25.946331","status":"completed"},"tags":[]}},{"cell_type":"markdown","source":"## Test Dataset and DataLoader","metadata":{"id":"tRSo-FPt0zRi","papermill":{"duration":0.081736,"end_time":"2021-10-30T18:36:26.192122","exception":false,"start_time":"2021-10-30T18:36:26.110386","status":"completed"},"tags":[]}},{"cell_type":"code","source":"class CellTestDataset(Dataset):\n    def __init__(self, image_dir, transforms=None, resize=False):\n        self.transforms = transforms\n        self.image_dir = image_dir\n        self.image_ids = [f[:-4]for f in os.listdir(self.image_dir)]\n        self.should_resize = resize is not False\n        if self.should_resize:\n            self.height = int(HEIGHT * resize)\n            self.width = int(WIDTH * resize)\n            print(\"image size used:\", self.height, self.width)\n            \n    def __getitem__(self, idx):\n        image_id = self.image_ids[idx]\n        image_path = os.path.join(self.image_dir, image_id + '.png')\n        image = cv2.imread(image_path, cv2.IMREAD_COLOR)\n        if self.should_resize:\n            image = cv2.resize(image, (self.width, self.height))\n\n        if self.transforms is not None:\n            image, _ = self.transforms(image=image, target=None)\n        return {'image': image, 'image_id': image_id}\n\n    def __len__(self):\n        return len(self.image_ids)","metadata":{"id":"ijZzdcHB0zRj","papermill":{"duration":0.092733,"end_time":"2021-10-30T18:36:26.365881","exception":false,"start_time":"2021-10-30T18:36:26.273148","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-12-01T17:53:01.194177Z","iopub.execute_input":"2022-12-01T17:53:01.194940Z","iopub.status.idle":"2022-12-01T17:53:01.203967Z","shell.execute_reply.started":"2022-12-01T17:53:01.194901Z","shell.execute_reply":"2022-12-01T17:53:01.203293Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ds_test = CellTestDataset(TEST_PATH, transforms=get_transform(train=False))","metadata":{"id":"WbciaVrJ0zRj","outputId":"3ec69aa1-4136-41a1-b853-67d38654ef9a","papermill":{"duration":0.090469,"end_time":"2021-10-30T18:36:26.536396","exception":false,"start_time":"2021-10-30T18:36:26.445927","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-12-01T17:53:01.205073Z","iopub.execute_input":"2022-12-01T17:53:01.205394Z","iopub.status.idle":"2022-12-01T17:53:01.226696Z","shell.execute_reply.started":"2022-12-01T17:53:01.205358Z","shell.execute_reply":"2022-12-01T17:53:01.225997Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_chk = f\"pytorch_model-e{best_epoch+1}.bin\"\nprint(\"Loading:\", model_chk)\nmodel = get_model(len(cell_type_dict))\nmodel.load_state_dict(torch.load(model_chk))\nmodel = model.to(DEVICE)\n\nfor param in model.parameters():\n    param.requires_grad = False\n\nmodel.eval();\n\nsubmission = []\nfor sample in ds_test:\n    img = sample['image']\n    image_id = sample['image_id']\n    with torch.no_grad():\n        result = model([img.to(DEVICE)])[0]\n    \n    previous_masks = []\n    for i, mask in enumerate(result[\"masks\"]):\n\n        # Filter-out low-scoring results.\n        score = result[\"scores\"][i].cpu().item()\n        label = result[\"labels\"][i].cpu().item()\n        if score > min_score_dict[label]:\n            mask = mask.cpu().numpy()\n            # Keep only highly likely pixels\n            binary_mask = mask > mask_threshold_dict[label]\n            binary_mask = remove_overlapping_pixels(binary_mask, previous_masks)\n            previous_masks.append(binary_mask)\n            rle = rle_encoding(binary_mask)\n            submission.append((image_id, rle))\n\n    # Add empty prediction if no RLE was generated for this image\n    all_images_ids = [image_id for image_id, rle in submission]\n    if image_id not in all_images_ids:\n        submission.append((image_id, \"\"))\n\ndf_sub = pd.DataFrame(submission, columns=['id', 'predicted'])\ndf_sub.to_csv(\"submission.csv\", index=False)\ndf_sub.head()","metadata":{"id":"dUrfObRF0zRk","outputId":"5f0432a3-8b87-4540-f49d-9d033b61bdbc","papermill":{"duration":5.323233,"end_time":"2021-10-30T18:36:31.939163","exception":false,"start_time":"2021-10-30T18:36:26.61593","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-12-01T17:53:01.228088Z","iopub.execute_input":"2022-12-01T17:53:01.228421Z","iopub.status.idle":"2022-12-01T17:53:08.239540Z","shell.execute_reply.started":"2022-12-01T17:53:01.228383Z","shell.execute_reply":"2022-12-01T17:53:08.238871Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}}]}