{"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":"#无外部依赖关系（仅模型权重）\n#我们只依赖Pytorch\n#导入内部和外部所依赖的库，import后对应的方法会在代码中进行使用\nimport os\nimport random\nimport time\nimport collections\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\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-04-25T04:47:59.278679Z","iopub.execute_input":"2022-04-25T04:47:59.27949Z","iopub.status.idle":"2022-04-25T04:47:59.286391Z","shell.execute_reply.started":"2022-04-25T04:47:59.279439Z","shell.execute_reply":"2022-04-25T04:47:59.285674Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Fix randomness\n #torch中随机化的过程\ndef fix_all_seeds(seed):\n    np.random.seed(seed)\n    random.seed(seed)            # 框架运行时会生成随机粒子\n    os.environ['PYTHONHASHSEED'] = str(seed)       #定义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-04-25T04:47:59.399986Z","iopub.execute_input":"2022-04-25T04:47:59.400323Z","iopub.status.idle":"2022-04-25T04:47:59.406918Z","shell.execute_reply.started":"2022-04-25T04:47:59.400289Z","shell.execute_reply":"2022-04-25T04:47:59.40612Z"},"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\"):     # 通过os方法中的路径判断函数判断文件路径是否存在\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')  #定义了代码是使用cuda版本还是cpu进行推理\n    BATCH_SIZE = 2   #通过训练两张图片，对两张图片的损失求均值，反向传播，可以让训练的损失更加平缓，训练的模型效果更好\n    NUM_EPOCHS = 1   #设置训练轮次=1\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#if elif和else是一个三选择判断，三个条件满足之一，运行之一，三者都是通过找data_directory的路径，定义框架推理模式，设置BATCH_SIZE和训练轮次\n\nTRAIN_CSV = f\"{data_directory}/train.csv\"   #找到data_directory文件夹后，在该路径下会有train.csv文件，通过后边的路径可以找到训练文件所在路径\nTRAIN_PATH = f\"{data_directory}/train\"    #原理同上，找到训练文件所在路径\nTEST_PATH = f\"{data_directory}/test\"      #原理同上，找到测试文件所在路径\n\n#设置图片的宽度和高度，对不同大小的图片在进入网络之前进行统一处理\nWIDTH = 704\nHEIGHT = 520\n\n#对数据集进行图像增强的处理\nresize_factor = False # 0.5  如果是ture的话，后边标的0.5相当于对现有的数据集进行长宽缩小一半的操作，混合到原有数据集共同参加训练，丰富数据样本的过程\n\n# Normalize to resnet mean and std if True.\nNORMALIZE = False    #标准化的一个过程，是一个参数设置为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   #使用std随机初始化的优化器方式再加一个动量进去，动量是0.9\n#随机初始化加动量的原因是：在下降过程中，训练的过程中会陷入到局部最优，并不能得到全局最优，加入动量是采用物理学的方法，在下降的过程带有一定的惯性，尽量实现全局最优\nLEARNING_RATE = 0.001  #学习率，训练一次，进行梯度下降的过程，使用回归的损失函数*学习率*WEIGHT_DECAY参数，调整学习率的大小，通过斜率观察梯度的方向\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-04-25T04:47:59.670137Z","iopub.execute_input":"2022-04-25T04:47:59.670448Z","iopub.status.idle":"2022-04-25T04:47:59.683504Z","shell.execute_reply.started":"2022-04-25T04:47:59.670418Z","shell.execute_reply":"2022-04-25T04:47:59.68264Z"},"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)   #对mask_rle, shape, color进行处理，返回img.reshape，对图片进行格式调整\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\n","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-04-25T04:47:59.799179Z","iopub.execute_input":"2022-04-25T04:47:59.799472Z","iopub.status.idle":"2022-04-25T04:47:59.813324Z","shell.execute_reply.started":"2022-04-25T04:47:59.799444Z","shell.execute_reply":"2022-04-25T04:47:59.81268Z"},"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-04-25T04:47:59.993968Z","iopub.execute_input":"2022-04-25T04:47:59.994162Z","iopub.status.idle":"2022-04-25T04:48:00.011869Z","shell.execute_reply.started":"2022-04-25T04:47:59.994139Z","shell.execute_reply":"2022-04-25T04:48:00.011117Z"},"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)   #<-- 数据增强方法调用dataset，dataset中我们将masks注销掉了，这部分在下一个cell中，接收的target没有masks这一样，这里也需要注销掉\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)   #<-- 数据增强方法调用dataset，dataset中我们将masks注销掉了，这部分在下一个cell中，接收的target没有masks这一样，这里也需要注销掉\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-04-25T04:48:00.060576Z","iopub.execute_input":"2022-04-25T04:48:00.060782Z","iopub.status.idle":"2022-04-25T04:48:00.072286Z","shell.execute_reply.started":"2022-04-25T04:48:00.060759Z","shell.execute_reply":"2022-04-25T04:48:00.071554Z"},"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)  #<-- 将 masks 注销只进行box预测 \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,   #<-- 将 masks 从输出结构体中删除，这里将masks这一Key去掉了，上面的cell中数据增强不能使用mask\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-04-25T04:48:00.255758Z","iopub.execute_input":"2022-04-25T04:48:00.255972Z","iopub.status.idle":"2022-04-25T04:48:00.273789Z","shell.execute_reply.started":"2022-04-25T04:48:00.255949Z","shell.execute_reply":"2022-04-25T04:48:00.273067Z"},"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-04-25T04:48:00.275577Z","iopub.execute_input":"2022-04-25T04:48:00.27592Z","iopub.status.idle":"2022-04-25T04:48:00.558776Z","shell.execute_reply.started":"2022-04-25T04:48:00.275806Z","shell.execute_reply":"2022-04-25T04:48:00.558006Z"},"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-04-25T04:48:00.560604Z","iopub.execute_input":"2022-04-25T04:48:00.560896Z","iopub.status.idle":"2022-04-25T04:48:00.621649Z","shell.execute_reply.started":"2022-04-25T04:48:00.560858Z","shell.execute_reply":"2022-04-25T04:48:00.620878Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_images.groupby(\"cell_type\").annotation.describe().astype(int)","metadata":{"id":"DQeF1Zi00zRf","outputId":"af89f7a7-245f-4583-85e3-4f4872c62171","papermill":{"duration":0.053443,"end_time":"2021-10-30T15:50:08.713717","exception":false,"start_time":"2021-10-30T15:50:08.660274","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-04-25T04:48:00.62312Z","iopub.execute_input":"2022-04-25T04:48:00.623384Z","iopub.status.idle":"2022-04-25T04:48:00.640757Z","shell.execute_reply.started":"2022-04-25T04:48:00.62335Z","shell.execute_reply":"2022-04-25T04:48:00.640098Z"},"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-04-25T04:48:00.642394Z","iopub.execute_input":"2022-04-25T04:48:00.64277Z","iopub.status.idle":"2022-04-25T04:48:00.656056Z","shell.execute_reply.started":"2022-04-25T04:48:00.642727Z","shell.execute_reply":"2022-04-25T04:48:00.655329Z"},"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-04-25T04:48:00.657142Z","iopub.execute_input":"2022-04-25T04:48:00.657749Z","iopub.status.idle":"2022-04-25T04:48:00.684178Z","shell.execute_reply.started":"2022-04-25T04:48:00.657711Z","shell.execute_reply":"2022-04-25T04:48:00.683502Z"},"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-04-25T04:48:00.685166Z","iopub.execute_input":"2022-04-25T04:48:00.686015Z","iopub.status.idle":"2022-04-25T04:48:00.767686Z","shell.execute_reply.started":"2022-04-25T04:48:00.685976Z","shell.execute_reply":"2022-04-25T04:48:00.767016Z"},"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-04-25T04:48:00.768866Z","iopub.execute_input":"2022-04-25T04:48:00.769104Z","iopub.status.idle":"2022-04-25T04:48:02.663088Z","shell.execute_reply.started":"2022-04-25T04:48:00.769071Z","shell.execute_reply":"2022-04-25T04:48:02.662155Z"},"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(\n#             pretrained=True, box_detections_per_img=BOX_DETECTIONS_PER_IMG,\n#             image_mean=RESNET_MEAN,image_std=RESNET_STD\n#         )\n        model = torchvision.models.detection.fasterrcnn_resnet50_fpn(  # <-- 这里我将 mask-rcnn 网络修改成faster-rcnn \n            pretrained=True, box_detections_per_img=BOX_DETECTIONS_PER_IMG,\n            image_mean=RESNET_MEAN,image_std=RESNET_STD\n        )                                                          \n    else:\n#         model = torchvision.models.detection.maskrcnn_resnet50_fpn(\n#             pretrained=True, box_detections_per_img=BOX_DETECTIONS_PER_IMG\n#         )\n        model = torchvision.models.detection.fasterrcnn_resnet50_fpn(  # <-- 这里我将 mask-rcnn 网络修改成faster-rcnn \n            pretrained=True, 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    # replace the pre-trained head with a new one\n    model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes+1)\n\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)  #<-- 用faster-rcnn，所以不需要MASK分支\n    \n#     if model_chkpt:\n#         model.load_state_dict(torch.load(model_chkpt, map_location=DEVICE))     #<-- 网络预训练参数加载，可以自动加载\n    return model\n\n\n# ============================================================================================================\n# 利用上面 get_model 函数建立 Faster-RCNN 模型（原来是建立Mask-RCNN）\n# The model does classification, bounding boxesfor individuals, all at the same time\n# We only care about MASKS\nmodel = get_model(num_classes=len(cell_type_dict))#调用get_model函数，传入的参数num_classes采用len的方法计算cell_type_dict中有几类目标，num_classes=3\nmodel.to(DEVICE)#把模型加载到cpu或gpu的框架里进行运算\n\n# TODO: try removing this for\nfor param in model.parameters():#一个训练过程，遍历了以后，将param.model所有参数都设置成了可以梯度下降的模式\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-04-25T04:48:02.666253Z","iopub.execute_input":"2022-04-25T04:48:02.666485Z","iopub.status.idle":"2022-04-25T04:48:03.429642Z","shell.execute_reply.started":"2022-04-25T04:48:02.666459Z","shell.execute_reply":"2022-04-25T04:48:03.428895Z"},"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\n# validation_mask_losses = []\n\nfor epoch in range(1, NUM_EPOCHS + 1): #之前定义了训练轮次等于30，通过循环进行30轮训练\n    print(f\"Starting epoch {epoch} of {NUM_EPOCHS}\") #输出当前进行的轮次\n\n    time_start = time.time() #训练开始记录时间\n    loss_accum = 0.0#计算损失的参数初始化为0.0\n    #loss_mask_accum = 0.0   # <-- loss_mask_accum用来累加mask分支的loss，由于换成faster-rcnn,所以没有mask分支，也就是没有mask分支的loss\n    loss_classifier_accum = 0.0#分类参数的初始化为0.0\n    for batch_idx, (images, targets) in enumerate(dl_train, 1): #采用enumerate方法，将dl——tarin以数据索引和数据内容的方式赋值到前边\n      #batch——idx表示第几个数据的索引，32.37\n    \n        # Predict\n        images = list(image.to(DEVICE) for image in images)#将图片转化成torch张量的形式，方便后续输入\n        targets = [{k: v.to(DEVICE) for k, v in t.items()} for t in targets]#将标签转化成gpu或cpu的张量格式，再输入模型中进行损失计算，返回loss dict\n\n        loss_dict = model(images, targets)\n        loss = sum(loss for loss in loss_dict.values()) #loss_dict.values方法会获取loss_dict字典里的所有值，不会获取键，把值提取处理采用sum求和的方法\n        #将每一个batch的计算的损失求和，再对损失求平均，得到平均损失\n        \n        #Backprop——反向传播，得到损失后，针对损失情况（预测结果和真实值的误差）对模型进行调整，然后再进行下一轮训练\n        optimizer.zero_grad()#对优化器进行0初始化\n        loss.backward()  #损失的反向传播\n        optimizer.step() #在反向传播过程中进行优化器的操作\n        \n        # Logging\n#         loss_mask = loss_dict['loss_mask'].item()  # <-- 这一行是提取mask分支的loss，由于换成faster-rcnn,所以没有mask分支，也就是没有mask分支的loss\n#         loss_mask_accum += loss_mask               # <-- 累加mask分支的loss\n        loss_accum += loss.item()\n        loss_classifier_accum += loss_dict['loss_classifier'].item()#将分类损失进行求和\n        \n        if batch_idx % 500 == 0: #在数据很多时，当batch批次可以被500整除时，输出训练各项损失的情况\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  # <-- mask loss 相关的\n    train_loss_classifier = loss_classifier_accum / n_batches #同上，得到分类损失\n\n    # Validation——验证过程，对训练好的模型进行精度测试\n    val_loss_accum = 0 #初始化了验证损失\n#     val_loss_mask_accum = 0   # <-- 验证集mask loss 累积，删除\n    val_loss_classifier_accum = 0#初始化验证分类损失\n    \n    with torch.no_grad(): #使用torch.no_grad的方法，固化参数，不允许进行梯度下降，对验证集进行遍历，最后对验证推理进行求和平均的计算\n #方法同训练一致\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()  #<-- # <-- 验证集mask loss 累积，删除\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   # 验证集 mask loss 均值，删除\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)     # 验证集mask loss 列表，删除\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)\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-04-25T04:48:03.431811Z","iopub.execute_input":"2022-04-25T04:48:03.43225Z","iopub.status.idle":"2022-04-25T04:50:48.960738Z","shell.execute_reply.started":"2022-04-25T04:48:03.432212Z","shell.execute_reply":"2022-04-25T04:50:48.959799Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"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): #定义analyze_train_sample函数， #返回图片和标签\n     \n    img, targets = ds_train[sample_index]\n    #print(img.shape)  #输出tagrets，对应下边的数字矩阵     \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    \n    \n\n    #img = img_tensor.cpu().data\n    ax[1].imshow(img.numpy().transpose((1,2,0)))\n    for i, box in enumerate(targets[\"boxes\"]):\n        xmin, ymin, xmax, ymax = box\n        rect = patches.Rectangle((xmin, ymin), (xmax - xmin), (ymax - ymin), linewidth=1, edgecolor='green',\n                                     facecolor='none')\n        ax[1].add_patch(rect)\n    plt.show()\n    \n   # masks = combine_masks(targets['boxes'], 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['area'])} cells\")\n #   ax[1].axis(\"off\")\n    #调用mask方法，再次画了一张图 ，画的是对原图进行标注的图形 \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)\n#调用analyze_train_sample方法，20代表从ds_train中选出的第20张图片，可以任意修改，出来的图片应该都不一样才对  \n#问题在于少一些东西，mask模型推理的结果是字典输出的和faster rcnn的键名是不一致的，对不上，又不知道应该输入的数据是什么，所以不知道怎么改","metadata":{"execution":{"iopub.status.busy":"2022-04-25T04:54:18.876143Z","iopub.execute_input":"2022-04-25T04:54:18.876496Z","iopub.status.idle":"2022-04-25T04:54:20.042192Z","shell.execute_reply.started":"2022-04-25T04:54:18.876461Z","shell.execute_reply":"2022-04-25T04:54:20.04144Z"},"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-04-25T04:50:50.08701Z","iopub.execute_input":"2022-04-25T04:50:50.087494Z","iopub.status.idle":"2022-04-25T04:50:50.762353Z","shell.execute_reply.started":"2022-04-25T04:50:50.087455Z","shell.execute_reply":"2022-04-25T04:50:50.761669Z"},"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-04-25T04:50:50.763728Z","iopub.execute_input":"2022-04-25T04:50:50.764209Z","iopub.status.idle":"2022-04-25T04:50:52.503467Z","shell.execute_reply.started":"2022-04-25T04:50:50.764171Z","shell.execute_reply":"2022-04-25T04:50:52.502705Z"},"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 val_scores = pd.DataFrame()\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    \n#display(val_scores.sort_values(\"score\", ascending=False))\n\n# best_epoch = np.argmax(val_scores[\"score\"])\n# print(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-04-25T04:50:52.504903Z","iopub.execute_input":"2022-04-25T04:50:52.505174Z","iopub.status.idle":"2022-04-25T04:50:52.524339Z","shell.execute_reply.started":"2022-04-25T04:50:52.505137Z","shell.execute_reply":"2022-04-25T04:50:52.523394Z"},"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-04-25T04:50:52.52551Z","iopub.status.idle":"2022-04-25T04:50:52.526243Z","shell.execute_reply.started":"2022-04-25T04:50:52.525965Z","shell.execute_reply":"2022-04-25T04:50:52.525993Z"},"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-04-25T04:50:52.527578Z","iopub.status.idle":"2022-04-25T04:50:52.528235Z","shell.execute_reply.started":"2022-04-25T04:50:52.527979Z","shell.execute_reply":"2022-04-25T04:50:52.528002Z"},"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-04-25T04:50:52.529507Z","iopub.status.idle":"2022-04-25T04:50:52.530337Z","shell.execute_reply.started":"2022-04-25T04:50:52.5301Z","shell.execute_reply":"2022-04-25T04:50:52.530124Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"id":"w73Jvhk20zRk","papermill":{"duration":0.080047,"end_time":"2021-10-30T18:36:32.10092","exception":false,"start_time":"2021-10-30T18:36:32.020873","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]}]}