{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":30201,"databundleVersionId":2750748,"sourceType":"competition"},{"sourceId":1791001,"sourceType":"datasetVersion","datasetId":1064455}],"dockerImageVersionId":30635,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Welcome to my Object segmentation project!\n## This project was my attempt at the *Sartorius - Cell Instance Segmentation* Kaggle problem!\n## Much of what I did was based on other notebooks publicly available in <a href=\"https://www.kaggle.com/competitions/sartorius-cell-instance-segmentation/code\">the \"code\" part of the competition</a>, more information on what especific noteboooks I used can be found in References","metadata":{}},{"cell_type":"markdown","source":"## These are the basic libraries used, I tried to keep it to a minimum in order to extract torch to its highest potential\n## The decision to use the Mask R-cnn architecture was based in <a href=\"https://www.kaggle.com/c/sartorius-cell-instance-segmentation/discussion/279790\">this discussion</a>","metadata":{}},{"cell_type":"code","source":"import os\nimport time\nimport random\nimport collections\n\nimport numpy as np\nimport pandas as pd\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\n\nimport torch\nimport torchvision\nfrom torchvision import transforms\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\nfrom torchvision.models.detection import MaskRCNN_ResNet50_FPN_V2_Weights, maskrcnn_resnet50_fpn_v2, roi_heads\n\n","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-01-29T02:07:59.936361Z","iopub.execute_input":"2024-01-29T02:07:59.936774Z","iopub.status.idle":"2024-01-29T02:08:02.660360Z","shell.execute_reply.started":"2024-01-29T02:07:59.936741Z","shell.execute_reply":"2024-01-29T02:08:02.659375Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Setting seeds for all future random instaces, in order to prevent random outcomes from random numbers generators.\n### Example:\n#### np.random.seed(0) makes the random numbers predictable:\n\n```\n>>> numpy.random.seed(0) ; numpy.random.rand(4)\narray([ 0.55,  0.72,  0.6 ,  0.54])\n>>> numpy.random.seed(0) ; numpy.random.rand(4)\narray([ 0.55,  0.72,  0.6 ,  0.54])\n```","metadata":{}},{"cell_type":"code","source":"def __set__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    torch.cuda.manual_seed_all(seed)\n    \n__set__seeds(2024)","metadata":{"execution":{"iopub.status.busy":"2024-01-29T02:08:02.662143Z","iopub.execute_input":"2024-01-29T02:08:02.662547Z","iopub.status.idle":"2024-01-29T02:08:02.671981Z","shell.execute_reply.started":"2024-01-29T02:08:02.662522Z","shell.execute_reply":"2024-01-29T02:08:02.671166Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Useful constants and mask r-cnn hyperparameters","metadata":{}},{"cell_type":"code","source":"BASE_PATH = \"/kaggle/input/sartorius-cell-instance-segmentation\"\nTRAIN_PATH = BASE_PATH + \"/train\"\nTEST_PATH = BASE_PATH + \"/test\"\nTRAIN_CSV = BASE_PATH + \"/train.csv\"\n\nIMG_WIDTH = 704\nIMG_HEIGHT = 520\n\nTEST = False\n\nDEVICE = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')\n\n# Will be used to normalize pictures\nRESNET_MEAN = (0.485, 0.456, 0.406)\nRESNET_STD = (0.229, 0.224, 0.225)\n\nBATCH_SIZE = 2\n\nMOMENTUM = 0.9\nLEARNING_RATE = 0.001\nWEIGHT_DECAY = 0.0005\n\n# Confidence required for a pixel to be kept for a mask\nMASK_THRESHOLD = 0.5\n\n# Dictionaries to classify each type of cell\nCELL_TYPE_DICT = {\"astro\": 1, \"cort\": 2, \"shsy5y\": 3}\nDICT_TO_CELL = {1: \"astro\", 2: \"cort\", 3: \"shsy5y\"}\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# Normalize to resnet mean and std if True.\nNORMALIZE = True \n\n\n# Using a learning rate scheduler\nUSE_SCHEDULER = True\n\n# Number of epochs in training\nNUM_EPOCHS = 8\n\nBOX_DETECTIONS_PER_IMG = 539","metadata":{"execution":{"iopub.status.busy":"2024-01-29T02:08:02.674619Z","iopub.execute_input":"2024-01-29T02:08:02.675258Z","iopub.status.idle":"2024-01-29T02:08:02.714611Z","shell.execute_reply.started":"2024-01-29T02:08:02.675233Z","shell.execute_reply":"2024-01-29T02:08:02.713609Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Transformations used in training dataset\n### Only used vertical flip, normalization and horizontal flip.","metadata":{}},{"cell_type":"code","source":"# These are slight redefinitions of torch.transformation classes, they are needed because of the masks created\n# The difference is that they handle the target and the mask\n# From Abishek and DATAISTA0\n\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 training dataset\n    if train: \n        if NORMALIZE: \n            transforms.append(Normalize())\n        transforms.append(HorizontalFlip(0.5))\n        transforms.append(VerticalFlip(0.5))\n        \n    return Compose(transforms)","metadata":{"execution":{"iopub.status.busy":"2024-01-29T02:08:02.718445Z","iopub.execute_input":"2024-01-29T02:08:02.718771Z","iopub.status.idle":"2024-01-29T02:08:02.732847Z","shell.execute_reply.started":"2024-01-29T02:08:02.718744Z","shell.execute_reply":"2024-01-29T02:08:02.732068Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Auxiliary functions\n### These functions vary a lot in what aspect they've helped in the project. From rle encoding/decoding to computing IoU scores.\n### IoU score funtions where taken from <a href=\"https://www.kaggle.com/theoviel/competition-metric-map-iou\">this notebook</a>.\n","metadata":{}},{"cell_type":"code","source":"def rle_decode(mask_rle, shape, color=1):\n    \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    ends = starts + lengths\n    img = np.zeros(shape[0] * shape[1], dtype=np.float32)\n    for lo, hi in zip(starts, ends):\n        img[lo : hi] = color\n    return img.reshape(shape)\n\n\ndef rle_encoding(x):\n    '''\n    x : image to be encoded \n    Returns string of encoded image\n    '''\n    \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\n\ndef draw_box(box):\n    '''\n    box: list of four elements organized like : [xmin, ymin, xmax, ymax]\n    \n    Returns image with 1's where box should be in a image with dimensions IMG_WIDTH x IMG_HEIGHT \n    '''\n    \n    result = np.zeros((IMG_HEIGHT, IMG_WIDTH))\n    xmin = int(box[0])\n    ymin = int(box[1])\n    xmax = int(box[2])\n    ymax = int(box[3]) \n    \n    for x in range(xmin, xmax):\n        if (xmin != 0) and (xmax != IMG_WIDTH):\n            result[ymin-1][x] = 1\n            result[ymax-1][x] = 1\n            \n    for y in range(ymin, ymax):\n        if (ymin != 0) and (ymax != IMG_HEIGHT):\n            result[y][xmax-1] = 1\n            result[y][xmin-1] = 1\n            \n    return result\n\n\ndef get_box(a_mask):\n    ''' \n    Get the bounding box of a given mask.\n    '''\n\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\n    return [xmin, ymin, xmax, ymax]\n\n\ndef combine_masks(masks, mask_threshold):\n    \"\"\"\n    Combine masks into one image.\n    \"\"\"\n    maskimg = np.zeros((IMG_HEIGHT, IMG_WIDTH))\n    for m, mask in enumerate(masks,1):\n        maskimg[mask>mask_threshold] = m\n    return maskimg\n\n\ndef combine_masks_boxes(masks, boxes):\n    '''\n    masks: image with several masks, marked as non-zero values and background as 0`s.\n    boxes: image with several boxes, marked as 1's and background as 0`s.\n    Returns image with both the boxes and masks, taking in consideration their values.\n    Boxes will have the max value possible.\n    '''\n    result = np.zeros((IMG_HEIGHT, IMG_WIDTH))\n    cur_max = 0\n    for i in range(IMG_WIDTH):\n        for j in range(IMG_HEIGHT):\n            \n            result[j][i] = 0\n            \n            if masks[j][i] != 0:\n                result[j][i] = masks[j][i]\n                if masks[j][i] > cur_max:\n                    cur_max = masks[j][i]\n                    \n                    \n    for i in range(IMG_WIDTH):\n        for j in range(IMG_HEIGHT):\n            if boxes[j][i] != 0:\n                result[j][i] = cur_max                \n    return result\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\n\n\ndef 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\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\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)","metadata":{"execution":{"iopub.status.busy":"2024-01-29T02:08:02.734405Z","iopub.execute_input":"2024-01-29T02:08:02.734805Z","iopub.status.idle":"2024-01-29T02:08:02.771805Z","shell.execute_reply.started":"2024-01-29T02:08:02.734773Z","shell.execute_reply":"2024-01-29T02:08:02.770886Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Dataset constructor\n### Created training dataset first, test dataset will be constructed afterwards!\n### Cell types were differenciated, heavily inspired by <a href=\"https://www.kaggle.com/code/rluethy/sartorius-torch-mask-r-cnn\"> rluethy's notebook</a>","metadata":{}},{"cell_type":"code","source":"class CellDataset(Dataset):\n    def __init__(self, image_dir, df, transforms=None):\n        self.transforms = transforms\n        self.image_dir = image_dir\n        self.df = df\n        self.height = IMG_HEIGHT\n        self.width = IMG_WIDTH\n        self.image_info = collections.defaultdict(dict)\n        \n        temp_df = self.df.groupby(['id', 'cell_type'])['annotation'].agg(lambda x: list(x)).reset_index()\n        \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': row[\"annotation\"],\n                    'cell_type': CELL_TYPE_DICT[row[\"cell_type\"]]\n                    }\n    \n\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 = Image.open(img_path).convert(\"RGB\")\n        info = self.image_info[idx]\n        n_objects = len(info['annotations'])\n        masks = np.zeros((len(info['annotations']), self.height, self.width), dtype=np.uint8)\n        boxes = []\n        \n        for i, annotation in enumerate(info['annotations']):\n            \n            a_mask = rle_decode(annotation, (IMG_HEIGHT, IMG_WIDTH))\n            a_mask = Image.fromarray(a_mask)\n            a_mask = np.array(a_mask) > 0\n            masks[i, :, :] = a_mask\n            boxes.append(get_box(a_mask))\n            \n        # dummy labels\n        labels = [info[\"cell_type\"] for _ in range(n_objects)]\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        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 in torch usage\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        return img, target\n    \n    def __len__(self):\n        return len(self.image_info)","metadata":{"execution":{"iopub.status.busy":"2024-01-29T02:08:02.773287Z","iopub.execute_input":"2024-01-29T02:08:02.773566Z","iopub.status.idle":"2024-01-29T02:08:02.788338Z","shell.execute_reply.started":"2024-01-29T02:08:02.773542Z","shell.execute_reply":"2024-01-29T02:08:02.787477Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Create instances of the classes previously created as well as explore some of the data","metadata":{}},{"cell_type":"code","source":"df_train = pd.read_csv(TRAIN_CSV, nrows=5000 if TEST else None)\nds_train = CellDataset(TRAIN_PATH, df_train, transforms=get_transform(train=True))\ndl_train = DataLoader(ds_train, batch_size=BATCH_SIZE, shuffle=True, \n                      num_workers=2, collate_fn=lambda x: tuple(zip(*x)))\n","metadata":{"execution":{"iopub.status.busy":"2024-01-29T02:08:02.789330Z","iopub.execute_input":"2024-01-29T02:08:02.789633Z","iopub.status.idle":"2024-01-29T02:08:03.502502Z","shell.execute_reply.started":"2024-01-29T02:08:02.789609Z","shell.execute_reply":"2024-01-29T02:08:03.501720Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def sample_images(ncols):\n    '''\n    ncols : number of images to sample\n    Returns plot with 2x(ncols) images from training dataset \n    '''\n    ns = random.sample(range(100), ncols)\n    fig, axs = plt.subplots(2, ncols, figsize=(20, 6)) \n    \n    for i in range(ncols):\n        img, targets = ds_train[ns[i]]\n        masks = np.zeros((IMG_HEIGHT, IMG_WIDTH))\n        boxes = np.zeros((IMG_HEIGHT, IMG_WIDTH))\n        axs[0][i].set_title(f\"Image {ns[i]}\")\n        axs[0][i].imshow(img.numpy().transpose((1,2,0)))\n        axs[0][i].axis(\"off\")\n        \n\n        for mask in targets['masks']:\n            box = get_box(mask)\n            boxes = np.logical_or(boxes, draw_box(box))\n            \n        masks = combine_masks(targets['masks'], 0.5)\n            \n        axs[1][i].set_title(f\"{ns[i]} {DICT_TO_CELL[((targets['labels'])[0]).item()]} mask\")\n        detections = combine_masks_boxes(masks, boxes)\n        axs[1][i].imshow(detections)\n        axs[1][i].axis(\"off\")\n    plt.show()\nsample_images(4)","metadata":{"execution":{"iopub.status.busy":"2024-01-29T02:08:03.503575Z","iopub.execute_input":"2024-01-29T02:08:03.503865Z","iopub.status.idle":"2024-01-29T02:08:13.030915Z","shell.execute_reply.started":"2024-01-29T02:08:03.503840Z","shell.execute_reply":"2024-01-29T02:08:13.029977Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Create main mask r-cnn model\n### I opted to use the new experimental model in the torch vision repository ","metadata":{}},{"cell_type":"code","source":"def get_model():\n    # This is just a dummy value for the classification head\n    NUM_CLASSES = len(CELL_TYPE_DICT)\n    model = torchvision.models.detection.maskrcnn_resnet50_fpn_v2(weights=MaskRCNN_ResNet50_FPN_V2_Weights.DEFAULT, box_detections_per_img=BOX_DETECTIONS_PER_IMG)\n    \n    \n    # get the number of input features for the classifier\n    in_features = model.roi_heads.box_predictor.cls_score.in_features\n    \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 = 128\n    \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    return model\n\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()\nmodel.to(DEVICE)\n\nfor param in model.parameters():\n    param.requires_grad = True\n    \nmodel.train();","metadata":{"execution":{"iopub.status.busy":"2024-01-29T02:08:13.032164Z","iopub.execute_input":"2024-01-29T02:08:13.032512Z","iopub.status.idle":"2024-01-29T02:08:15.408535Z","shell.execute_reply.started":"2024-01-29T02:08:13.032481Z","shell.execute_reply":"2024-01-29T02:08:15.407722Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Train the model","metadata":{}},{"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\nlr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=3, gamma=0.1)\n\nn_batches = len(dl_train)\n\nfor epoch in range(1, NUM_EPOCHS + 1):\n    print(f\"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    \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        \n        targets = [{k: v.to(DEVICE) for k, v in t.items()} for t in targets]\n        \n        loss_dict = model(images, targets)\n        \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        # 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        \n        if batch_idx % 50 == 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 and epoch >= 5:\n        lr_scheduler.step()\n   \n    \n    # Total network loss\n    network_loss = train_loss + train_loss_mask + train_loss_classifier\n    \n    \n    \n    elapsed = time.time() - time_start\n    \n    \n    torch.save(model.state_dict(), f\"pytorch_model-e{epoch}.bin\")\n    prefix = f\"[Epoch {epoch:2d} / {NUM_EPOCHS:2d}]\"\n    print(f\"{prefix} Train mask-only loss: {train_loss_mask:7.3f}\")\n    print(f\"{prefix} Train loss: {train_loss:7.3f}. [{elapsed:.0f} secs]\")\n    print(f\"{prefix} Train Classifier loss: {train_loss_classifier:7.3f}\")\n    print(f\"{prefix} Total network loss: {network_loss:7.3f}\")","metadata":{"execution":{"iopub.status.busy":"2024-01-29T02:08:15.411307Z","iopub.execute_input":"2024-01-29T02:08:15.411599Z","iopub.status.idle":"2024-01-29T02:14:45.648924Z","shell.execute_reply.started":"2024-01-29T02:08:15.411574Z","shell.execute_reply":"2024-01-29T02:14:45.647542Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Plots: the image, The image + the ground truth mask + detection boxes, The image + the predicted mask + predicted boxes\ndef analyze_sample(model, ds_train, sample_index):\n    '''\n    model : model used to create the masks/boxes of the object detection\n    ds_train : data set to take samples from\n    sample_index: index of the image that will be used\n    Returns grid 1x3 with : the image | the image + the ground truth mask + detection boxes | the image + the predicted mask + predicted boxes\n    '''\n    img, targets = ds_train[sample_index]\n    fig, axs = plt.subplots(1, 3, figsize=(20, 40), facecolor=\"#fefefe\") \n    \n    masks = np.zeros((IMG_HEIGHT, IMG_WIDTH))\n    boxes = np.zeros((IMG_HEIGHT, IMG_WIDTH))\n    \n    axs[0].imshow(img.numpy().transpose((1,2,0)))\n    axs[0].set_title(\"Image\")\n    axs[0].axis(\"off\")\n    \n    for mask in targets['masks']:\n        box = get_box(mask)\n        boxes = np.logical_or(boxes, draw_box(box)) \n        \n    masks = combine_masks(targets['masks'], 0.5)\n    detections = combine_masks_boxes(masks, boxes)\n    axs[1].imshow(detections)\n    axs[1].set_title(\"Ground truth\")\n    axs[1].axis(\"off\")\n    \n    model.eval()\n    with torch.no_grad():\n        preds = model([img.to(DEVICE)])[0]\n\n    axs[2].imshow(img.cpu().numpy().transpose((1,2,0)))\n    \n    for mask in preds['masks'].cpu().detach():\n        box = get_box(mask[[0]])\n        boxes = np.logical_or(boxes, draw_box(box))\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    mask_threshold = MASK_THRESHOLD_DICT[l.sort_values().index[-1]]\n    pred_masks = combine_masks(get_filtered_masks(preds), 0.5)\n        \n       \n    detections = combine_masks_boxes(pred_masks, boxes)\n    score = iou_map([masks],[pred_masks])\n    axs[2].imshow(detections)\n    axs[2].set_title(f\"Predictions | IoU score: {score:.2f}\")\n    axs[2].axis(\"off\")\n    plt.show()\nanalyze_sample(model, ds_train, random.randint(1, 500))\n","metadata":{"execution":{"iopub.status.busy":"2024-01-29T02:14:45.650326Z","iopub.status.idle":"2024-01-29T02:14:45.650725Z","shell.execute_reply.started":"2024-01-29T02:14:45.650532Z","shell.execute_reply":"2024-01-29T02:14:45.650551Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"analyze_sample(model, ds_train, random.randint(1, 500))","metadata":{"execution":{"iopub.status.busy":"2024-01-29T02:14:45.651746Z","iopub.status.idle":"2024-01-29T02:14:45.652114Z","shell.execute_reply.started":"2024-01-29T02:14:45.651915Z","shell.execute_reply":"2024-01-29T02:14:45.651932Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"analyze_sample(model, ds_train, random.randint(1, 500))","metadata":{"execution":{"iopub.status.busy":"2024-01-29T02:14:45.653101Z","iopub.status.idle":"2024-01-29T02:14:45.653415Z","shell.execute_reply.started":"2024-01-29T02:14:45.653259Z","shell.execute_reply":"2024-01-29T02:14:45.653273Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class CellTestDataset(Dataset):\n    def __init__(self, image_dir, transforms=None):\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    \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 = Image.open(image_path).convert(\"RGB\")\n\n        if self.transforms is not None:\n            image, _ = self.transforms(image=image, target=None)\n        return {'image': image, 'image_id': image_id}","metadata":{"execution":{"iopub.status.busy":"2024-01-29T02:14:45.654919Z","iopub.status.idle":"2024-01-29T02:14:45.655408Z","shell.execute_reply.started":"2024-01-29T02:14:45.655102Z","shell.execute_reply":"2024-01-29T02:14:45.655118Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ds_test = CellTestDataset(TEST_PATH, transforms=get_transform(train=False))\n","metadata":{"execution":{"iopub.status.busy":"2024-01-29T02:14:45.657158Z","iopub.status.idle":"2024-01-29T02:14:45.657597Z","shell.execute_reply.started":"2024-01-29T02:14:45.657369Z","shell.execute_reply":"2024-01-29T02:14:45.657391Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Encode masks results, append results to submissions list!","metadata":{}},{"cell_type":"code","source":"model.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        score = result[\"scores\"][i].cpu().item()\n        mask = mask.cpu().numpy()\n        # Keep only highly likely pixels\n        binary_mask = mask > MASK_THRESHOLD\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":{"execution":{"iopub.status.busy":"2024-01-29T02:14:45.659416Z","iopub.status.idle":"2024-01-29T02:14:45.659863Z","shell.execute_reply.started":"2024-01-29T02:14:45.659625Z","shell.execute_reply":"2024-01-29T02:14:45.659647Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## References\n### This notebook was extremely inspired by other notebooks that competed in the past, such as: <a href=\"https://www.kaggle.com/theoviel/competition-metric-map-iou\">this notebook (IoU)</a>, <a href=\"https://www.kaggle.com/code/rluethy/sartorius-torch-mask-r-cnn\"> rluethy's notebook</a>, <a href=\"https://www.kaggle.com/code/julian3833/sartorius-starter-torch-mask-r-cnn-lb-0-273\">DATAISTA0's notebook</a>\n### Thanks for checking out my project!","metadata":{}}]}