{"cells":[{"metadata":{},"cell_type":"markdown","source":"\n<h1 style=\"font-size: 24px; text-align: center;\"> Detectron-2 Training and weights and biases integration </h1>\n<h1 style=\"font-family: Lucida Sans Typewriter; font-size: 16px; text-align: center;\"> Author- Sourabh Chauhan</h1>\n\nGoals:- \n- Integrate the Detectron2 models for computer vision with wandb api for hyperparameter optimization in VBD project.\n\nNotes:- \n\n- This notebook uses [corochan's Detectron2 implementation for VBD dataset](http://https://www.kaggle.com/corochann/vinbigdata-detectron2-train)\n- This notebook includes a Weights and biases integration of the Detectron2 models to follow hyperparameters of the datasets. \n- [Jump directly to weights and biases integration cell](#training), Make sure to add wandb_api key to your notebook using Add-ons. \n\n- The output will be in the following directory \n    * '/kaggle/working/results/v23/' \n    * model_final.path, flags.yaml and metrics.json files can be directly used for inference.  \n- Inference from the notebook should be combined with 2 Class filter to obtain a incerement of public leaderboard metric of about 0.08. \n\n![](http://)\n\n\nfile:///home/sourabh/kaggle/xrays/VBD-chestxray/hyper_param_06-03.png\n<img src=\"../input/hyper-parameter-vbd-march-6/hyper_param_06-03.png\">\n\n\n\n## Detectron 2 Training with weights and biases monitoring\n[UPDATE 2021/2/21] Training 512 512 on R101 backbone 3,000 iterations, comparison with the laptop output   (v16)  \n\n[UPDATE 2021/2/20] Training 1024 1024 on R101 backbone 10,000 iterations, training anchor box change things ---     \n\n[UPDATE 2021/2/20] Training 1024 1024 on R101 backbone 18,000 iterations\n\n[UPDATE 2021/2/16] Training 1024 1024 on R101 backbone 30,000 iterations (did not run... overflew 9 hour limit of GPU time on kaggle sessions)\n\n[UPDATE 2021/2/16] Training 1024 1024 on R101 backbone\n\n[UPDATE 2021/2/12]  Training on the full size image instead of 256*256\n\n"},{"metadata":{},"cell_type":"markdown","source":"# Table of Contents\n\n** [Dataset preparation](#dataset)** <br/>\n** [Installation](#installation)** <br/>\n** [Training method implementations](#train_method)** <br/>\n** [Customizing detectron2 trainer](#custom_trainer) ** [Advanced topic, skip it first time] <br/>\n**   - [Mapper for augmentation](#mapper)** <br/>\n**   - [Evaluator](#evaluator)** <br/>\n**   - [Loss evaluation hook](#loss_hook)** <br/>\n** [Loading Data](#load_data)** <br/>\n** [Data Visualization](#data_vis)** <br/>\n** [Training](#training)** <br/>\n** [Visualize loss curve & competition metric AP40](#vis_loss)** <br/>\n** [Visualization of augmentation by Mapper](#vis_aug)** <br/>\n** [Next step](#next_step)** <br/>"},{"metadata":{},"cell_type":"markdown","source":"<a id=\"dataset\"></a>\n# Dataset preparation\n\nPreprocessing x-ray image format (dicom) into normal png image format is already done by @xhlulu in the below discussion:\n - [Multiple preprocessed datasets: 256/512/1024px, PNG and JPG, modified and original ratio](https://www.kaggle.com/c/vinbigdata-chest-xray-abnormalities-detection/discussion/207955).\n\nHere I will just use the dataset [VinBigData Chest X-ray Resized PNG (256x256)](https://www.kaggle.com/xhlulu/vinbigdata-chest-xray-resized-png-256x256) to skip the preprocessing and focus on modeling part. Please upvote the dataset as well!"},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"import gc\nimport os\nfrom pathlib import Path\nimport random\nimport sys\n\nfrom tqdm.notebook import tqdm\nimport numpy as np\nimport pandas as pd\nimport scipy as sp\n\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom IPython.core.display import display, HTML\n\n# --- plotly ---\nfrom plotly import tools, subplots\nimport plotly.offline as py\npy.init_notebook_mode(connected=True)\nimport plotly.graph_objs as go\nimport plotly.express as px\nimport plotly.figure_factory as ff\nimport plotly.io as pio\npio.templates.default = \"plotly_dark\"\n\n# --- models ---\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import KFold\nimport lightgbm as lgb\nimport xgboost as xgb\nimport catboost as cb\n\n# --- setup ---\npd.set_option('max_columns', 50)\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<a id=\"installation\"></a>\n# Installation\n\ndetectron2 is not pre-installed in this kaggle docker, so let's install it. \nWe can follow [installation instruction](https://github.com/facebookresearch/detectron2/blob/master/INSTALL.md), we need to know CUDA and pytorch version to install correct `detectron2`."},{"metadata":{},"cell_type":"markdown","source":""},{"metadata":{"_kg_hide-input":true,"_kg_hide-output":true,"trusted":true},"cell_type":"code","source":"# GPU check\n!nvidia-smi\n!nvcc --version\nimport torch\n\ntorch.__version__","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-output":true,"trusted":true},"cell_type":"code","source":"# Installing Detectron2\n!pip install detectron2 -f \\\n  https://dl.fbaipublicfiles.com/detectron2/wheels/cu102/torch1.7/index.html","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<a id=\"train_method\"></a>\n\n# Training method implementations\n\nBasically we don't need to implement neural network part, `detectron2` already implements famous architectures and provides its pre-trained weights. We can finetune these pre-trained architectures.\n\nThese models are summarized in [MODEL_ZOO.md](https://github.com/facebookresearch/detectron2/blob/master/MODEL_ZOO.md).\n\nIn this competition, we need object detection model, I will choose [R50-FPN](https://github.com/facebookresearch/detectron2/blob/master/configs/COCO-Detection/faster_rcnn_R_50_FPN_3x.yaml) for this kernel."},{"metadata":{},"cell_type":"markdown","source":"## Data preparation\n\n`detectron2` provides high-level API for training custom dataset.\n\nTo define custom dataset, we need to create **list of dict** (`dataset_dicts`) where each dict contains following:\n\n - file_name: file name of the image.\n - image_id: id of the image, index is used here.\n - height: height of the image.\n - width: width of the image.\n - annotation: This is the ground truth annotation data for object detection, which contains following\n     - bbox: bounding box pixel location with shape (n_boxes, 4)\n     - bbox_mode: `BoxMode.XYXY_ABS` is used here, meaning that absolute value of (xmin, ymin, xmax, ymax) annotation is used in the `bbox`.\n     - category_id: class label id for each bounding box, with shape (n_boxes,)\n\n`get_vinbigdata_dicts` is for train dataset preparation and `get_vinbigdata_dicts_test` is for test dataset preparation.\n\nThis `dataset_dicts` contains the metadata for actual data fed into the neural network.<br/>\nIt is loaded beforehand of the training **on memory**, so it should contain all the metadata (image filepath etc) to construct training dataset, but **should not contain heavy data**.<br/>\n\nIn practice, loading all the taining image arrays are too heavy to be loaded on memory, so these are loaded inside `DataLoader` on-demand (This is done by mapper class in `detectron2`, as I will expain later)."},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"\nimport pickle\nfrom pathlib import Path\nfrom typing import Optional\n\nimport cv2\nimport numpy as np\nimport pandas as pd\nfrom detectron2.structures import BoxMode\nfrom tqdm import tqdm\n\n\ndef get_vinbigdata_dicts(\n    imgdir: Path,\n    train_df: pd.DataFrame,\n    train_data_type: str = \"original\",\n    use_cache: bool = True,\n    debug: bool = True,\n    target_indices: Optional[np.ndarray] = None,\n    use_class14: bool = False,\n):\n    debug_str = f\"_debug{int(debug)}\"\n    train_data_type_str = f\"_{train_data_type}\"\n    class14_str = f\"_14class{int(use_class14)}\"\n    cache_path = Path(\".\") / f\"dataset_dicts_cache{train_data_type_str}{class14_str}{debug_str}.pkl\"\n    if not use_cache or not cache_path.exists():\n        print(\"Creating data...\")\n        train_meta = pd.read_csv(\"../input/vinbigdata-chest-xray-original-png/train_meta.csv\")\n        if debug:\n            train_meta = train_meta.iloc[:500]  # For debug....\n        print (imgdir)\n        # Load 1 image to get image size.\n        image_id = train_meta.loc[0, \"image_id\"]\n        image_path = str(imgdir / \"train\" / f\"{image_id}.png\")\n        print (image_path)\n        image = cv2.imread(image_path)\n        \n        \n        resized_height, resized_width, ch = image.shape\n        print(f\"image shape: {image.shape}\")\n\n        dataset_dicts = []\n        for index, train_meta_row in tqdm(train_meta.iterrows(), total=len(train_meta)):\n            record = {}\n            image_id, height, width = train_meta_row.values\n            filename = str(imgdir / \"train\" / f\"{image_id}.png\")\n            record[\"file_name\"] = filename\n            record[\"image_id\"] = image_id\n            record[\"height\"] = resized_height\n            record[\"width\"] = resized_width\n            objs = []\n            for index2, row in train_df.query(\"image_id == @image_id\").iterrows():\n                # print(row)\n                # print(row[\"class_name\"])\n                # class_name = row[\"class_name\"]\n                class_id = row[\"class_id\"]\n                if class_id == 14:\n                    # It is \"No finding\"\n                    if use_class14:\n                        # Use this No finding class with the bbox covering all image area.\n                        bbox_resized = [0, 0, resized_width, resized_height]\n                        obj = {\n                            \"bbox\": bbox_resized,\n                            \"bbox_mode\": BoxMode.XYXY_ABS,\n                            \"category_id\": class_id,\n                        }\n                        objs.append(obj)\n                    else:\n                        # This annotator does not find anything, skip.\n                        pass\n                else:\n                    bbox_original = [int(row[\"x_min\"]), int(row[\"y_min\"]), int(row[\"x_max\"]), int(row[\"y_max\"])]\n                    '''\n                    h_ratio = resized_height / height\n                    w_ratio = resized_width / width\n                    bbox_resized = [\n                        float(row[\"x_min\"]) * w_ratio,\n                        float(row[\"y_min\"]) * h_ratio,\n                        float(row[\"x_max\"]) * w_ratio,\n                        float(row[\"y_max\"]) * h_ratio,\n                    ]\n                    '''\n                    obj = {\n                        \"bbox\": bbox_original,\n                        \"bbox_mode\": BoxMode.XYXY_ABS,\n                        \"category_id\": class_id,\n                    }\n                    objs.append(obj)\n            record[\"annotations\"] = objs\n            dataset_dicts.append(record)\n        with open(cache_path, mode=\"wb\") as f:\n            pickle.dump(dataset_dicts, f)\n\n    print(f\"Load from cache {cache_path}\")\n    with open(cache_path, mode=\"rb\") as f:\n        dataset_dicts = pickle.load(f)\n    if target_indices is not None:\n        dataset_dicts = [dataset_dicts[i] for i in target_indices]\n    return dataset_dicts\n\n\ndef get_vinbigdata_dicts_test(\n    imgdir: Path, test_meta: pd.DataFrame, use_cache: bool = True, debug: bool = True,\n):\n    debug_str = f\"_debug{int(debug)}\"\n    cache_path = Path(\".\") + \"/\"+ f\"dataset_dicts_cache_test{debug_str}.pkl\"\n    if not use_cache or not cache_path.exists():\n        print(\"Creating data...\")\n        # test_meta = pd.read_csv(imgdir / \"test_meta.csv\")\n        if debug:\n            test_meta = test_meta.iloc[:500]  # For debug....\n\n        # Load 1 image to get image size.\n        image_id = test_meta.loc[0, \"image_id\"]\n        image_path = str(imgdir + \"test\" + f\"{image_id}.png\")\n        image = cv2.imread(image_path)\n        resized_height, resized_width, ch = image.shape\n        print(f\"image shape: {image.shape}\")\n\n        dataset_dicts = []\n        for index, test_meta_row in tqdm(test_meta.iterrows(), total=len(test_meta)):\n            record = {}\n\n            image_id, height, width = test_meta_row.values\n            filename = str(imgdir + \"/test/\" + f\"{image_id}.png\")\n            record[\"file_name\"] = filename\n            # record[\"image_id\"] = index\n            record[\"image_id\"] = image_id\n            record[\"height\"] = resized_height\n            record[\"width\"] = resized_width\n            # objs = []\n            # record[\"annotations\"] = objs\n            dataset_dicts.append(record)\n        with open(cache_path, mode=\"wb\") as f:\n            pickle.dump(dataset_dicts, f)\n\n    print(f\"Load from cache {cache_path}\")\n    with open(cache_path, mode=\"rb\") as f:\n        dataset_dicts = pickle.load(f)\n    return dataset_dicts\n","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"_kg_hide-output":true,"trusted":true},"cell_type":"code","source":"# --- utils ---\nfrom pathlib import Path\nfrom typing import Any, Union\n\nimport yaml\n\n\ndef save_yaml(filepath: Union[str, Path], content: Any, width: int = 120):\n    with open(filepath, \"w\") as f:\n        yaml.dump(content, f, width=width)\n\n\ndef load_yaml(filepath: Union[str, Path]) -> Any:\n    with open(filepath, \"r\") as f:\n        content = yaml.full_load(f)\n    return content\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# --- configs ---\nthing_classes = [\n    \"Aortic enlargement\",\n    \"Atelectasis\",\n    \"Calcification\",\n    \"Cardiomegaly\",\n    \"Consolidation\",\n    \"ILD\",\n    \"Infiltration\",\n    \"Lung Opacity\",\n    \"Nodule/Mass\",\n    \"Other lesion\",\n    \"Pleural effusion\",\n    \"Pleural thickening\",\n    \"Pneumothorax\",\n    \"Pulmonary fibrosis\"\n]\ncategory_name_to_id = {class_name: index for index, class_name in enumerate(thing_classes)}\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<a id=\"custom_trainer\"></a>\n# Customizing detectron2 trainer\n\n※ This section is advanced, I recommend to jump to **Training scripts** section for the first time of reading.\n\nYou can refer the [Detectron2 Beginner's Tutorial](https://colab.research.google.com/drive/16jcaJoc6bCFAQ96jDe2HwtXj7BMD_-m5#scrollTo=QHnVupBBn9eR) Colab Notebook (or [version 7 of this kernel](https://www.kaggle.com/corochann/vinbigdata-detectron2-train?scriptVersionId=51628272)) for the simple usage of detectron2 how to train custom dataset. `DefaultTrainer` is used in the example which provides the starting point to train your model with custom dataset.\n\nIt is nice to start with, however I want to customize the training behavior more to improve the model's performance.\nWe can make own Trainer class (`MyTrainer` here) for this purpose, and override methods to provide customized behavior."},{"metadata":{},"cell_type":"markdown","source":"<a id=\"mapper\"></a>\n## Mapper for augmentation\n\n`Mapper` class is used inside pytorch `DataLoader`. It is responsible for converting `dataset_dicts` into actual data fed into the neural network, and we can insert augmentation process in this Mapper class.\n\n - Ref: [detectron2 docs \"Dataloader\"](https://detectron2.readthedocs.io/en/latest/tutorials/data_loading.html)\n\nI implemented `MyMapper` which uses augmentations implemented in `detectron2`, and `AlbumentationsMapper` which uses albumentations library augmentations.<br/> \nI will demonstrate these augmentations later, so you can skip reading the code and please just jump to next."},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"\"\"\"\nReferenced:\n - https://detectron2.readthedocs.io/en/latest/tutorials/data_loading.html\n - https://www.kaggle.com/dhiiyaur/detectron-2-compare-models-augmentation/#data\n\"\"\"\nimport copy\nimport logging\n\nimport detectron2.data.transforms as T\nimport torch\nfrom detectron2.data import detection_utils as utils\n\n\nclass MyMapper:\n    \"\"\"Mapper which uses `detectron2.data.transforms` augmentations\"\"\"\n\n    def __init__(self, cfg, is_train: bool = True):\n        aug_kwargs = cfg.aug_kwargs\n        aug_list = [\n            # T.Resize((800, 800)),\n        ]\n        if is_train:\n            aug_list.extend([getattr(T, name)(**kwargs) for name, kwargs in aug_kwargs.items()])\n        self.augmentations = T.AugmentationList(aug_list)\n        self.is_train = is_train\n\n        mode = \"training\" if is_train else \"inference\"\n        print(f\"[MyDatasetMapper] Augmentations used in {mode}: {self.augmentations}\")\n\n    def __call__(self, dataset_dict):\n        dataset_dict = copy.deepcopy(dataset_dict)  # it will be modified by code below\n        image = utils.read_image(dataset_dict[\"file_name\"], format=\"BGR\")\n\n        aug_input = T.AugInput(image)\n        transforms = self.augmentations(aug_input)\n        image = aug_input.image\n\n        # if not self.is_train:\n        #     # USER: Modify this if you want to keep them for some reason.\n        #     dataset_dict.pop(\"annotations\", None)\n        #     dataset_dict.pop(\"sem_seg_file_name\", None)\n        #     return dataset_dict\n\n        image_shape = image.shape[:2]  # h, w\n        dataset_dict[\"image\"] = torch.as_tensor(image.transpose(2, 0, 1).astype(\"float32\"))\n        annos = [\n            utils.transform_instance_annotations(obj, transforms, image_shape)\n            for obj in dataset_dict.pop(\"annotations\")\n            if obj.get(\"iscrowd\", 0) == 0\n        ]\n        instances = utils.annotations_to_instances(annos, image_shape)\n        dataset_dict[\"instances\"] = utils.filter_empty_instances(instances)\n        return dataset_dict","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"\"\"\"\nReferenced:\n - https://detectron2.readthedocs.io/en/latest/tutorials/data_loading.html\n - https://www.kaggle.com/dhiiyaur/detectron-2-compare-models-augmentation/#data\n\"\"\"\nimport albumentations as A\nimport copy\nimport numpy as np\n\nimport torch\nfrom detectron2.data import detection_utils as utils\n\n\nclass AlbumentationsMapper:\n    \"\"\"Mapper which uses `albumentations` augmentations\"\"\"\n    def __init__(self, cfg, is_train: bool = True):\n        aug_kwargs = cfg.aug_kwargs\n        aug_list = [\n        ]\n        if is_train:\n            aug_list.extend([getattr(A, name)(**kwargs) for name, kwargs in aug_kwargs.items()])\n        self.transform = A.Compose(\n            aug_list, bbox_params=A.BboxParams(format=\"pascal_voc\", label_fields=[\"category_ids\"])\n        )\n        self.is_train = is_train\n\n        mode = \"training\" if is_train else \"inference\"\n        print(f\"[AlbumentationsMapper] Augmentations used in {mode}: {self.transform}\")\n\n    def __call__(self, dataset_dict):\n        dataset_dict = copy.deepcopy(dataset_dict)  # it will be modified by code below\n        image = utils.read_image(dataset_dict[\"file_name\"], format=\"BGR\")\n\n        # aug_input = T.AugInput(image)\n        # transforms = self.augmentations(aug_input)\n        # image = aug_input.image\n\n        prev_anno = dataset_dict[\"annotations\"]\n        bboxes = np.array([obj[\"bbox\"] for obj in prev_anno], dtype=np.float32)\n        # category_id = np.array([obj[\"category_id\"] for obj in dataset_dict[\"annotations\"]], dtype=np.int64)\n        category_id = np.arange(len(dataset_dict[\"annotations\"]))\n\n        transformed = self.transform(image=image, bboxes=bboxes, category_ids=category_id)\n        image = transformed[\"image\"]\n        annos = []\n        for i, j in enumerate(transformed[\"category_ids\"]):\n            d = prev_anno[j]\n            d[\"bbox\"] = transformed[\"bboxes\"][i]\n            annos.append(d)\n        dataset_dict.pop(\"annotations\", None)  # Remove unnecessary field.\n\n        # if not self.is_train:\n        #     # USER: Modify this if you want to keep them for some reason.\n        #     dataset_dict.pop(\"annotations\", None)\n        #     dataset_dict.pop(\"sem_seg_file_name\", None)\n        #     return dataset_dict\n\n        image_shape = image.shape[:2]  # h, w\n        dataset_dict[\"image\"] = torch.as_tensor(image.transpose(2, 0, 1).astype(\"float32\"))\n        instances = utils.annotations_to_instances(annos, image_shape)\n        dataset_dict[\"instances\"] = utils.filter_empty_instances(instances)\n        return dataset_dict\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<a id=\"evaluator\"></a>\n## Evaluator\n\nTo evaluate validation dataset to calculate competition metric, we need `Evaluator`.\n\nFamouns dataset's evaluator is already implemented in `detectron2`. <br/>\nFor example, many kinds of AP (Average Precision) is calculted in `COCOEvaluator`.<br/>\n`COCOEvaluator` only calculates AP with IoU from 0.50 to 0.95, but we need AP with IoU 0.40.\n\nHere, I modified `COCOEvaluator` implementation to calculate AP with IoU 0.40 and replaced to show this value instead of AP with IoU 0.70."},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"\"\"\"\nOriginal code from https://github.com/cocodataset/cocoapi/blob/8c9bcc3cf640524c4c20a9c40e89cb6a2f2fa0e9/PythonAPI/pycocotools/cocoeval.py\nJust modified to show AP@40\n\"\"\"\n# Copyright (c) Facebook, Inc. and its affiliates.\nimport contextlib\nimport copy\nimport io\nimport itertools\nimport json\nimport logging\nimport numpy as np\nimport os\nimport pickle\nfrom collections import OrderedDict\nimport pycocotools.mask as mask_util\nimport torch\nfrom pycocotools.coco import COCO\nfrom pycocotools.cocoeval import COCOeval\nfrom tabulate import tabulate\n\nimport detectron2.utils.comm as comm\nfrom detectron2.config import CfgNode\nfrom detectron2.data import MetadataCatalog\nfrom detectron2.data.datasets.coco import convert_to_coco_json\nfrom detectron2.evaluation.evaluator import DatasetEvaluator\nfrom detectron2.evaluation.fast_eval_api import COCOeval_opt\nfrom detectron2.structures import Boxes, BoxMode, pairwise_iou\nfrom detectron2.utils.file_io import PathManager\nfrom detectron2.utils.logger import create_small_table\n\n\ndef vin_summarize(self):\n    '''\n    Compute and display summary metrics for evaluation results.\n    Note this functin can *only* be applied on the default parameter setting\n    '''\n\n    def _summarize(ap=1, iouThr=None, areaRng='all', maxDets=100):\n        p = self.params\n        iStr = ' {:<18} {} @[ IoU={:<9} | area={:>6s} | maxDets={:>3d} ] = {:0.3f}'\n        titleStr = 'Average Precision' if ap == 1 else 'Average Recall'\n        typeStr = '(AP)' if ap == 1 else '(AR)'\n        iouStr = '{:0.2f}:{:0.2f}'.format(p.iouThrs[0], p.iouThrs[-1]) \\\n            if iouThr is None else '{:0.2f}'.format(iouThr)\n\n        aind = [i for i, aRng in enumerate(p.areaRngLbl) if aRng == areaRng]\n        mind = [i for i, mDet in enumerate(p.maxDets) if mDet == maxDets]\n        if ap == 1:\n            # dimension of precision: [TxRxKxAxM]\n            s = self.eval['precision']\n            # IoU\n            if iouThr is not None:\n                t = np.where(iouThr == p.iouThrs)[0]\n                s = s[t]\n            s = s[:, :, :, aind, mind]\n        else:\n            # dimension of recall: [TxKxAxM]\n            s = self.eval['recall']\n            if iouThr is not None:\n                t = np.where(iouThr == p.iouThrs)[0]\n                s = s[t]\n            s = s[:, :, aind, mind]\n        if len(s[s > -1]) == 0:\n            mean_s = -1\n        else:\n            mean_s = np.mean(s[s > -1])\n        print(iStr.format(titleStr, typeStr, iouStr, areaRng, maxDets, mean_s))\n        return mean_s\n\n    def _summarizeDets():\n        stats = np.zeros((12,))\n        stats[0] = _summarize(1)\n        stats[1] = _summarize(1, iouThr=.5, maxDets=self.params.maxDets[2])\n        # stats[2] = _summarize(1, iouThr=.75, maxDets=self.params.maxDets[2])\n        stats[2] = _summarize(1, iouThr=.4, maxDets=self.params.maxDets[2])\n        stats[3] = _summarize(1, areaRng='small', maxDets=self.params.maxDets[2])\n        stats[4] = _summarize(1, areaRng='medium', maxDets=self.params.maxDets[2])\n        stats[5] = _summarize(1, areaRng='large', maxDets=self.params.maxDets[2])\n        stats[6] = _summarize(0, maxDets=self.params.maxDets[0])\n        stats[7] = _summarize(0, maxDets=self.params.maxDets[1])\n        stats[8] = _summarize(0, maxDets=self.params.maxDets[2])\n        stats[9] = _summarize(0, areaRng='small', maxDets=self.params.maxDets[2])\n        stats[10] = _summarize(0, areaRng='medium', maxDets=self.params.maxDets[2])\n        stats[11] = _summarize(0, areaRng='large', maxDets=self.params.maxDets[2])\n        return stats\n\n    def _summarizeKps():\n        stats = np.zeros((10,))\n        stats[0] = _summarize(1, maxDets=20)\n        stats[1] = _summarize(1, maxDets=20, iouThr=.5)\n        stats[2] = _summarize(1, maxDets=20, iouThr=.75)\n        stats[3] = _summarize(1, maxDets=20, areaRng='medium')\n        stats[4] = _summarize(1, maxDets=20, areaRng='large')\n        stats[5] = _summarize(0, maxDets=20)\n        stats[6] = _summarize(0, maxDets=20, iouThr=.5)\n        stats[7] = _summarize(0, maxDets=20, iouThr=.75)\n        stats[8] = _summarize(0, maxDets=20, areaRng='medium')\n        stats[9] = _summarize(0, maxDets=20, areaRng='large')\n        return stats\n\n    if not self.eval:\n        raise Exception('Please run accumulate() first')\n    iouType = self.params.iouType\n    if iouType == 'segm' or iouType == 'bbox':\n        summarize = _summarizeDets\n    elif iouType == 'keypoints':\n        summarize = _summarizeKps\n    self.stats = summarize()\n\n\nprint(\"HACKING: overriding COCOeval.summarize = vin_summarize...\")\nCOCOeval.summarize = vin_summarize\n\n\nclass VinbigdataEvaluator(DatasetEvaluator):\n    \"\"\"\n    Evaluate AR for object proposals, AP for instance detection/segmentation, AP\n    for keypoint detection outputs using COCO's metrics.\n    See http://cocodataset.org/#detection-eval and\n    http://cocodataset.org/#keypoints-eval to understand its metrics.\n\n    In addition to COCO, this evaluator is able to support any bounding box detection,\n    instance segmentation, or keypoint detection dataset.\n    \"\"\"\n\n    def __init__(\n        self,\n        dataset_name,\n        tasks=None,\n        distributed=True,\n        output_dir=None,\n        *,\n        use_fast_impl=True,\n        kpt_oks_sigmas=(),\n    ):\n        \"\"\"\n        Args:\n            dataset_name (str): name of the dataset to be evaluated.\n                It must have either the following corresponding metadata:\n\n                    \"json_file\": the path to the COCO format annotation\n\n                Or it must be in detectron2's standard dataset format\n                so it can be converted to COCO format automatically.\n            tasks (tuple[str]): tasks that can be evaluated under the given\n                configuration. A task is one of \"bbox\", \"segm\", \"keypoints\".\n                By default, will infer this automatically from predictions.\n            distributed (True): if True, will collect results from all ranks and run evaluation\n                in the main process.\n                Otherwise, will only evaluate the results in the current process.\n            output_dir (str): optional, an output directory to dump all\n                results predicted on the dataset. The dump contains two files:\n\n                1. \"instances_predictions.pth\" a file in torch serialization\n                   format that contains all the raw original predictions.\n                2. \"coco_instances_results.json\" a json file in COCO's result\n                   format.\n            use_fast_impl (bool): use a fast but **unofficial** implementation to compute AP.\n                Although the results should be very close to the official implementation in COCO\n                API, it is still recommended to compute results with the official API for use in\n                papers. The faster implementation also uses more RAM.\n            kpt_oks_sigmas (list[float]): The sigmas used to calculate keypoint OKS.\n                See http://cocodataset.org/#keypoints-eval\n                When empty, it will use the defaults in COCO.\n                Otherwise it should be the same length as ROI_KEYPOINT_HEAD.NUM_KEYPOINTS.\n        \"\"\"\n        self._logger = logging.getLogger(__name__)\n        self._distributed = distributed\n        self._output_dir = output_dir\n        self._use_fast_impl = use_fast_impl\n\n        if tasks is not None and isinstance(tasks, CfgNode):\n            kpt_oks_sigmas = (\n                tasks.TEST.KEYPOINT_OKS_SIGMAS if not kpt_oks_sigmas else kpt_oks_sigmas\n            )\n            self._logger.warn(\n                \"COCO Evaluator instantiated using config, this is deprecated behavior.\"\n                \" Please pass in explicit arguments instead.\"\n            )\n            self._tasks = None  # Infering it from predictions should be better\n        else:\n            self._tasks = tasks\n\n        self._cpu_device = torch.device(\"cpu\")\n\n        self._metadata = MetadataCatalog.get(dataset_name)\n        if not hasattr(self._metadata, \"json_file\"):\n            self._logger.info(\n                f\"'{dataset_name}' is not registered by `register_coco_instances`.\"\n                \" Therefore trying to convert it to COCO format ...\"\n            )\n\n            cache_path = os.path.join(output_dir, f\"{dataset_name}_coco_format.json\")\n            self._metadata.json_file = cache_path\n            convert_to_coco_json(dataset_name, cache_path)\n\n        json_file = PathManager.get_local_path(self._metadata.json_file)\n        with contextlib.redirect_stdout(io.StringIO()):\n            self._coco_api = COCO(json_file)\n\n        # Test set json files do not contain annotations (evaluation must be\n        # performed using the COCO evaluation server).\n        self._do_evaluation = \"annotations\" in self._coco_api.dataset\n        if self._do_evaluation:\n            self._kpt_oks_sigmas = kpt_oks_sigmas\n\n    def reset(self):\n        self._predictions = []\n\n    def process(self, inputs, outputs):\n        \"\"\"\n        Args:\n            inputs: the inputs to a COCO model (e.g., GeneralizedRCNN).\n                It is a list of dict. Each dict corresponds to an image andb\n                contains keys like \"height\", \"width\", \"file_name\", \"image_id\".\n            outputs: the outputs of a COCO model. It is a list of dicts with key\n                \"instances\" that contains :class:`Instances`.\n        \"\"\"\n        for input, output in zip(inputs, outputs):\n            prediction = {\"image_id\": input[\"image_id\"]}\n\n            if \"instances\" in output:\n                instances = output[\"instances\"].to(self._cpu_device)\n                prediction[\"instances\"] = instances_to_coco_json(instances, input[\"image_id\"])\n            if \"proposals\" in output:\n                prediction[\"proposals\"] = output[\"proposals\"].to(self._cpu_device)\n            if len(prediction) > 1:\n                self._predictions.append(prediction)\n\n    def evaluate(self, img_ids=None):\n        \"\"\"\n        Args:\n            img_ids: a list of image IDs to evaluate on. Default to None for the whole dataset\n        \"\"\"\n        if self._distributed:\n            comm.synchronize()\n            predictions = comm.gather(self._predictions, dst=0)\n            predictions = list(itertools.chain(*predictions))\n\n            if not comm.is_main_process():\n                return {}\n        else:\n            predictions = self._predictions\n\n        if len(predictions) == 0:\n            self._logger.warning(\"[VinbigdataEvaluator] Did not receive valid predictions.\")\n            return {}\n\n        if self._output_dir:\n            PathManager.mkdirs(self._output_dir)\n            file_path = os.path.join(self._output_dir, \"instances_predictions.pth\")\n            with PathManager.open(file_path, \"wb\") as f:\n                torch.save(predictions, f)\n\n        self._results = OrderedDict()\n        if \"proposals\" in predictions[0]:\n            self._eval_box_proposals(predictions)\n        if \"instances\" in predictions[0]:\n            self._eval_predictions(predictions, img_ids=img_ids)\n        # Copy so the caller can do whatever with results\n        return copy.deepcopy(self._results)\n\n    def _tasks_from_predictions(self, predictions):\n        \"\"\"\n        Get COCO API \"tasks\" (i.e. iou_type) from COCO-format predictions.\n        \"\"\"\n        tasks = {\"bbox\"}\n        for pred in predictions:\n            if \"segmentation\" in pred:\n                tasks.add(\"segm\")\n            if \"keypoints\" in pred:\n                tasks.add(\"keypoints\")\n        return sorted(tasks)\n\n    def _eval_predictions(self, predictions, img_ids=None):\n        \"\"\"\n        Evaluate predictions. Fill self._results with the metrics of the tasks.\n        \"\"\"\n        self._logger.info(\"Preparing results for COCO format ...\")\n        coco_results = list(itertools.chain(*[x[\"instances\"] for x in predictions]))\n        tasks = self._tasks or self._tasks_from_predictions(coco_results)\n\n        # unmap the category ids for COCO\n        if hasattr(self._metadata, \"thing_dataset_id_to_contiguous_id\"):\n            dataset_id_to_contiguous_id = self._metadata.thing_dataset_id_to_contiguous_id\n            all_contiguous_ids = list(dataset_id_to_contiguous_id.values())\n            num_classes = len(all_contiguous_ids)\n            assert min(all_contiguous_ids) == 0 and max(all_contiguous_ids) == num_classes - 1\n\n            reverse_id_mapping = {v: k for k, v in dataset_id_to_contiguous_id.items()}\n            for result in coco_results:\n                category_id = result[\"category_id\"]\n                assert category_id < num_classes, (\n                    f\"A prediction has class={category_id}, \"\n                    f\"but the dataset only has {num_classes} classes and \"\n                    f\"predicted class id should be in [0, {num_classes - 1}].\"\n                )\n                result[\"category_id\"] = reverse_id_mapping[category_id]\n\n        if self._output_dir:\n            file_path = os.path.join(self._output_dir, \"coco_instances_results.json\")\n            self._logger.info(\"Saving results to {}\".format(file_path))\n            with PathManager.open(file_path, \"w\") as f:\n                f.write(json.dumps(coco_results))\n                f.flush()\n\n        if not self._do_evaluation:\n            self._logger.info(\"Annotations are not available for evaluation.\")\n            return\n\n        self._logger.info(\n            \"Evaluating predictions with {} COCO API...\".format(\n                \"unofficial\" if self._use_fast_impl else \"official\"\n            )\n        )\n        for task in sorted(tasks):\n            coco_eval = (\n                _evaluate_predictions_on_coco(\n                    self._coco_api,\n                    coco_results,\n                    task,\n                    kpt_oks_sigmas=self._kpt_oks_sigmas,\n                    use_fast_impl=self._use_fast_impl,\n                    img_ids=img_ids,\n                )\n                if len(coco_results) > 0\n                else None  # cocoapi does not handle empty results very well\n            )\n\n            res = self._derive_coco_results(\n                coco_eval, task, class_names=self._metadata.get(\"thing_classes\")\n            )\n            self._results[task] = res\n\n    def _eval_box_proposals(self, predictions):\n        \"\"\"\n        Evaluate the box proposals in predictions.\n        Fill self._results with the metrics for \"box_proposals\" task.\n        \"\"\"\n        if self._output_dir:\n            # Saving generated box proposals to file.\n            # Predicted box_proposals are in XYXY_ABS mode.\n            bbox_mode = BoxMode.XYXY_ABS.value\n            ids, boxes, objectness_logits = [], [], []\n            for prediction in predictions:\n                ids.append(prediction[\"image_id\"])\n                boxes.append(prediction[\"proposals\"].proposal_boxes.tensor.numpy())\n                objectness_logits.append(prediction[\"proposals\"].objectness_logits.numpy())\n\n            proposal_data = {\n                \"boxes\": boxes,\n                \"objectness_logits\": objectness_logits,\n                \"ids\": ids,\n                \"bbox_mode\": bbox_mode,\n            }\n            with PathManager.open(os.path.join(self._output_dir, \"box_proposals.pkl\"), \"wb\") as f:\n                pickle.dump(proposal_data, f)\n\n        if not self._do_evaluation:\n            self._logger.info(\"Annotations are not available for evaluation.\")\n            return\n\n        self._logger.info(\"Evaluating bbox proposals ...\")\n        res = {}\n        areas = {\"all\": \"\", \"small\": \"s\", \"medium\": \"m\", \"large\": \"l\"}\n        for limit in [100, 1000]:\n            for area, suffix in areas.items():\n                stats = _evaluate_box_proposals(predictions, self._coco_api, area=area, limit=limit)\n                key = \"AR{}@{:d}\".format(suffix, limit)\n                res[key] = float(stats[\"ar\"].item() * 100)\n        self._logger.info(\"Proposal metrics: \\n\" + create_small_table(res))\n        self._results[\"box_proposals\"] = res\n\n    def _derive_coco_results(self, coco_eval, iou_type, class_names=None):\n        \"\"\"\n        Derive the desired score numbers from summarized COCOeval.\n\n        Args:\n            coco_eval (None or COCOEval): None represents no predictions from model.\n            iou_type (str):\n            class_names (None or list[str]): if provided, will use it to predict\n                per-category AP.\n\n        Returns:\n            a dict of {metric name: score}\n        \"\"\"\n\n        metrics = {\n            \"bbox\": [\"AP\", \"AP50\", \"AP75\", \"APs\", \"APm\", \"APl\"],\n            \"segm\": [\"AP\", \"AP50\", \"AP75\", \"APs\", \"APm\", \"APl\"],\n            \"keypoints\": [\"AP\", \"AP50\", \"AP75\", \"APm\", \"APl\"],\n        }[iou_type]\n\n        if coco_eval is None:\n            self._logger.warn(\"No predictions from the model!\")\n            return {metric: float(\"nan\") for metric in metrics}\n\n        # the standard metrics\n        results = {\n            metric: float(coco_eval.stats[idx] * 100 if coco_eval.stats[idx] >= 0 else \"nan\")\n            for idx, metric in enumerate(metrics)\n        }\n        self._logger.info(\n            \"Evaluation results for {}: \\n\".format(iou_type) + create_small_table(results)\n        )\n        if not np.isfinite(sum(results.values())):\n            self._logger.info(\"Some metrics cannot be computed and is shown as NaN.\")\n\n        if class_names is None or len(class_names) <= 1:\n            return results\n        # Compute per-category AP\n        # from https://github.com/facebookresearch/Detectron/blob/a6a835f5b8208c45d0dce217ce9bbda915f44df7/detectron/datasets/json_dataset_evaluator.py#L222-L252 # noqa\n        precisions = coco_eval.eval[\"precision\"]\n        # precision has dims (iou, recall, cls, area range, max dets)\n        assert len(class_names) == precisions.shape[2]\n\n        results_per_category = []\n        for idx, name in enumerate(class_names):\n            # area range index 0: all area ranges\n            # max dets index -1: typically 100 per image\n            precision = precisions[:, :, idx, 0, -1]\n            precision = precision[precision > -1]\n            ap = np.mean(precision) if precision.size else float(\"nan\")\n            results_per_category.append((\"{}\".format(name), float(ap * 100)))\n\n        # tabulate it\n        N_COLS = min(6, len(results_per_category) * 2)\n        results_flatten = list(itertools.chain(*results_per_category))\n        results_2d = itertools.zip_longest(*[results_flatten[i::N_COLS] for i in range(N_COLS)])\n        table = tabulate(\n            results_2d,\n            tablefmt=\"pipe\",\n            floatfmt=\".3f\",\n            headers=[\"category\", \"AP\"] * (N_COLS // 2),\n            numalign=\"left\",\n        )\n        self._logger.info(\"Per-category {} AP: \\n\".format(iou_type) + table)\n\n        results.update({\"AP-\" + name: ap for name, ap in results_per_category})\n        return results\n\n\ndef instances_to_coco_json(instances, img_id):\n    \"\"\"\n    Dump an \"Instances\" object to a COCO-format json that's used for evaluation.\n\n    Args:\n        instances (Instances):\n        img_id (int): the image id\n\n    Returns:\n        list[dict]: list of json annotations in COCO format.\n    \"\"\"\n    num_instance = len(instances)\n    if num_instance == 0:\n        return []\n\n    boxes = instances.pred_boxes.tensor.numpy()\n    boxes = BoxMode.convert(boxes, BoxMode.XYXY_ABS, BoxMode.XYWH_ABS)\n    boxes = boxes.tolist()\n    scores = instances.scores.tolist()\n    classes = instances.pred_classes.tolist()\n\n    has_mask = instances.has(\"pred_masks\")\n    if has_mask:\n        # use RLE to encode the masks, because they are too large and takes memory\n        # since this evaluator stores outputs of the entire dataset\n        rles = [\n            mask_util.encode(np.array(mask[:, :, None], order=\"F\", dtype=\"uint8\"))[0]\n            for mask in instances.pred_masks\n        ]\n        for rle in rles:\n            # \"counts\" is an array encoded by mask_util as a byte-stream. Python3's\n            # json writer which always produces strings cannot serialize a bytestream\n            # unless you decode it. Thankfully, utf-8 works out (which is also what\n            # the pycocotools/_mask.pyx does).\n            rle[\"counts\"] = rle[\"counts\"].decode(\"utf-8\")\n\n    has_keypoints = instances.has(\"pred_keypoints\")\n    if has_keypoints:\n        keypoints = instances.pred_keypoints\n\n    results = []\n    for k in range(num_instance):\n        result = {\n            \"image_id\": img_id,\n            \"category_id\": classes[k],\n            \"bbox\": boxes[k],\n            \"score\": scores[k],\n        }\n        if has_mask:\n            result[\"segmentation\"] = rles[k]\n        if has_keypoints:\n            # In COCO annotations,\n            # keypoints coordinates are pixel indices.\n            # However our predictions are floating point coordinates.\n            # Therefore we subtract 0.5 to be consistent with the annotation format.\n            # This is the inverse of data loading logic in `datasets/coco.py`.\n            keypoints[k][:, :2] -= 0.5\n            result[\"keypoints\"] = keypoints[k].flatten().tolist()\n        results.append(result)\n    return results\n\n\n# inspired from Detectron:\n# https://github.com/facebookresearch/Detectron/blob/a6a835f5b8208c45d0dce217ce9bbda915f44df7/detectron/datasets/json_dataset_evaluator.py#L255 # noqa\ndef _evaluate_box_proposals(dataset_predictions, coco_api, thresholds=None, area=\"all\", limit=None):\n    \"\"\"\n    Evaluate detection proposal recall metrics. This function is a much\n    faster alternative to the official COCO API recall evaluation code. However,\n    it produces slightly different results.\n    \"\"\"\n    # Record max overlap value for each gt box\n    # Return vector of overlap values\n    areas = {\n        \"all\": 0,\n        \"small\": 1,\n        \"medium\": 2,\n        \"large\": 3,\n        \"96-128\": 4,\n        \"128-256\": 5,\n        \"256-512\": 6,\n        \"512-inf\": 7,\n    }\n    area_ranges = [\n        [0 ** 2, 1e5 ** 2],  # all\n        [0 ** 2, 32 ** 2],  # small\n        [32 ** 2, 96 ** 2],  # medium\n        [96 ** 2, 1e5 ** 2],  # large\n        [96 ** 2, 128 ** 2],  # 96-128\n        [128 ** 2, 256 ** 2],  # 128-256\n        [256 ** 2, 512 ** 2],  # 256-512\n        [512 ** 2, 1e5 ** 2],\n    ]  # 512-inf\n    assert area in areas, \"Unknown area range: {}\".format(area)\n    area_range = area_ranges[areas[area]]\n    gt_overlaps = []\n    num_pos = 0\n\n    for prediction_dict in dataset_predictions:\n        predictions = prediction_dict[\"proposals\"]\n\n        # sort predictions in descending order\n        # TODO maybe remove this and make it explicit in the documentation\n        inds = predictions.objectness_logits.sort(descending=True)[1]\n        predictions = predictions[inds]\n\n        ann_ids = coco_api.getAnnIds(imgIds=prediction_dict[\"image_id\"])\n        anno = coco_api.loadAnns(ann_ids)\n        gt_boxes = [\n            BoxMode.convert(obj[\"bbox\"], BoxMode.XYWH_ABS, BoxMode.XYXY_ABS)\n            for obj in anno\n            if obj[\"iscrowd\"] == 0\n        ]\n        gt_boxes = torch.as_tensor(gt_boxes).reshape(-1, 4)  # guard against no boxes\n        gt_boxes = Boxes(gt_boxes)\n        gt_areas = torch.as_tensor([obj[\"area\"] for obj in anno if obj[\"iscrowd\"] == 0])\n\n        if len(gt_boxes) == 0 or len(predictions) == 0:\n            continue\n\n        valid_gt_inds = (gt_areas >= area_range[0]) & (gt_areas <= area_range[1])\n        gt_boxes = gt_boxes[valid_gt_inds]\n\n        num_pos += len(gt_boxes)\n\n        if len(gt_boxes) == 0:\n            continue\n\n        if limit is not None and len(predictions) > limit:\n            predictions = predictions[:limit]\n\n        overlaps = pairwise_iou(predictions.proposal_boxes, gt_boxes)\n\n        _gt_overlaps = torch.zeros(len(gt_boxes))\n        for j in range(min(len(predictions), len(gt_boxes))):\n            # find which proposal box maximally covers each gt box\n            # and get the iou amount of coverage for each gt box\n            max_overlaps, argmax_overlaps = overlaps.max(dim=0)\n\n            # find which gt box is 'best' covered (i.e. 'best' = most iou)\n            gt_ovr, gt_ind = max_overlaps.max(dim=0)\n            assert gt_ovr >= 0\n            # find the proposal box that covers the best covered gt box\n            box_ind = argmax_overlaps[gt_ind]\n            # record the iou coverage of this gt box\n            _gt_overlaps[j] = overlaps[box_ind, gt_ind]\n            assert _gt_overlaps[j] == gt_ovr\n            # mark the proposal box and the gt box as used\n            overlaps[box_ind, :] = -1\n            overlaps[:, gt_ind] = -1\n\n        # append recorded iou coverage level\n        gt_overlaps.append(_gt_overlaps)\n    gt_overlaps = (\n        torch.cat(gt_overlaps, dim=0) if len(gt_overlaps) else torch.zeros(0, dtype=torch.float32)\n    )\n    gt_overlaps, _ = torch.sort(gt_overlaps)\n\n    if thresholds is None:\n        step = 0.05\n        # thresholds = torch.arange(0.5, 0.95 + 1e-5, step, dtype=torch.float32)\n        thresholds = torch.arange(0.4, 0.95 + 1e-5, step, dtype=torch.float32)\n    recalls = torch.zeros_like(thresholds)\n    # compute recall for each iou threshold\n    for i, t in enumerate(thresholds):\n        recalls[i] = (gt_overlaps >= t).float().sum() / float(num_pos)\n    # ar = 2 * np.trapz(recalls, thresholds)\n    ar = recalls.mean()\n    return {\n        \"ar\": ar,\n        \"recalls\": recalls,\n        \"thresholds\": thresholds,\n        \"gt_overlaps\": gt_overlaps,\n        \"num_pos\": num_pos,\n    }\n\n\ndef _evaluate_predictions_on_coco(\n    coco_gt, coco_results, iou_type, kpt_oks_sigmas=None, use_fast_impl=True, img_ids=None\n):\n    \"\"\"\n    Evaluate the coco results using COCOEval API.\n    \"\"\"\n    assert len(coco_results) > 0\n\n    if iou_type == \"segm\":\n        coco_results = copy.deepcopy(coco_results)\n        # When evaluating mask AP, if the results contain bbox, cocoapi will\n        # use the box area as the area of the instance, instead of the mask area.\n        # This leads to a different definition of small/medium/large.\n        # We remove the bbox field to let mask AP use mask area.\n        for c in coco_results:\n            c.pop(\"bbox\", None)\n\n    coco_dt = coco_gt.loadRes(coco_results)\n    coco_eval = (COCOeval_opt if use_fast_impl else COCOeval)(coco_gt, coco_dt, iou_type)\n\n    # HACKING: overwrite iouThrs to calc ious 0.4\n    coco_eval.params.iouThrs = np.linspace(\n        .4, 0.95, int(np.round((0.95 - .4) / .05)) + 1, endpoint=True)\n\n    if img_ids is not None:\n        coco_eval.params.imgIds = img_ids\n\n    if iou_type == \"keypoints\":\n        # Use the COCO default keypoint OKS sigmas unless overrides are specified\n        if kpt_oks_sigmas:\n            assert hasattr(coco_eval.params, \"kpt_oks_sigmas\"), \"pycocotools is too old!\"\n            coco_eval.params.kpt_oks_sigmas = np.array(kpt_oks_sigmas)\n        # COCOAPI requires every detection and every gt to have keypoints, so\n        # we just take the first entry from both\n        num_keypoints_dt = len(coco_results[0][\"keypoints\"]) // 3\n        num_keypoints_gt = len(next(iter(coco_gt.anns.values()))[\"keypoints\"]) // 3\n        num_keypoints_oks = len(coco_eval.params.kpt_oks_sigmas)\n        assert num_keypoints_oks == num_keypoints_dt == num_keypoints_gt, (\n            f\"[VinbigdataEvaluator] Prediction contain {num_keypoints_dt} keypoints. \"\n            f\"Ground truth contains {num_keypoints_gt} keypoints. \"\n            f\"The length of cfg.TEST.KEYPOINT_OKS_SIGMAS is {num_keypoints_oks}. \"\n            \"They have to agree with each other. For meaning of OKS, please refer to \"\n            \"http://cocodataset.org/#keypoints-eval.\"\n        )\n\n    coco_eval.evaluate()\n    coco_eval.accumulate()\n    coco_eval.summarize()\n\n    return coco_eval\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<a id=\"loss_hook\"></a>\n## Loss evaluation hook\n\nWe implemented Evaluator and now we can calculate competition metric, however, validation loss is not calculated inside Evaluator. This is because model's evaluation is done in `model.eval()` mode and it outputs bounding box prediction but does not output `loss`.\n\nTo calculate validation loss, we need to call `model` with the training mode. This can be done by adding `Hook` which calculates the loss to the trainer.<br/>\nTrainer has attribute `storage` and calculated metrics are summarized. Its content is saved to `metric.json` (jsonl format) during training.\n\nBelow `LossEvalHook` calculates validation loss in `_do_loss_eval` method, and `self.trainer.storage.put_scalars(validation_loss=mean_loss)` is called to put this validation loss to the `storage`, which will be saved to `metrics.json`.<br/>\nNote that current implementation is not efficient in the sense that Evaluator's evaluation and `LossEvalHook`'s loss calculation run separately, even if both need a model forward calculation for same validation data.\n\n - Ref: [Training on Detectron2 with a Validation set, and plot loss on it to avoid overfitting](https://medium.com/@apofeniaco/training-on-detectron2-with-a-validation-set-and-plot-loss-on-it-to-avoid-overfitting-6449418fbf4e)"},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"\"\"\"\nTo calculate & record validation loss\n\nOriginal code from https://medium.com/@apofeniaco/training-on-detectron2-with-a-validation-set-and-plot-loss-on-it-to-avoid-overfitting-6449418fbf4e\nby @apofeniaco\n\"\"\"\nimport numpy as np\nimport logging\n\nfrom detectron2.engine.hooks import HookBase\nfrom detectron2.utils.logger import log_every_n_seconds\nimport detectron2.utils.comm as comm\nimport torch\nimport time\nimport datetime\n\n\nclass LossEvalHook(HookBase):\n    def __init__(self, eval_period, model, data_loader):\n        self._model = model\n        self._period = eval_period\n        self._data_loader = data_loader\n\n    def _do_loss_eval(self):\n        # Copying inference_on_dataset from evaluator.py\n        total = len(self._data_loader)\n        num_warmup = min(5, total - 1)\n\n        start_time = time.perf_counter()\n        total_compute_time = 0\n        losses = []\n        for idx, inputs in enumerate(self._data_loader):\n            if idx == num_warmup:\n                start_time = time.perf_counter()\n                total_compute_time = 0\n            start_compute_time = time.perf_counter()\n            if torch.cuda.is_available():\n                torch.cuda.synchronize()\n            total_compute_time += time.perf_counter() - start_compute_time\n            iters_after_start = idx + 1 - num_warmup * int(idx >= num_warmup)\n            seconds_per_img = total_compute_time / iters_after_start\n            if idx >= num_warmup * 2 or seconds_per_img > 5:\n                total_seconds_per_img = (time.perf_counter() - start_time) / iters_after_start\n                eta = datetime.timedelta(seconds=int(total_seconds_per_img * (total - idx - 1)))\n                log_every_n_seconds(\n                    logging.INFO,\n                    \"Loss on Validation  done {}/{}. {:.4f} s / img. ETA={}\".format(\n                        idx + 1, total, seconds_per_img, str(eta)\n                    ),\n                    n=5,\n                )\n            loss_batch = self._get_loss(inputs)\n            losses.append(loss_batch)\n        mean_loss = np.mean(losses)\n        # self.trainer.storage.put_scalar('validation_loss', mean_loss)\n        comm.synchronize()\n\n        # return losses\n        return mean_loss\n\n    def _get_loss(self, data):\n        # How loss is calculated on train_loop\n        metrics_dict = self._model(data)\n        metrics_dict = {\n            k: v.detach().cpu().item() if isinstance(v, torch.Tensor) else float(v)\n            for k, v in metrics_dict.items()\n        }\n        total_losses_reduced = sum(loss for loss in metrics_dict.values())\n        return total_losses_reduced\n\n    def after_step(self):\n        next_iter = int(self.trainer.iter) + 1\n        is_final = next_iter == self.trainer.max_iter\n        if is_final or (self._period > 0 and next_iter % self._period == 0):\n            mean_loss = self._do_loss_eval()\n            self.trainer.storage.put_scalars(validation_loss=mean_loss)\n            print(\"validation do loss eval\", mean_loss)\n        else:\n            pass\n            # self.trainer.storage.put_scalars(timetest=11)\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Now all the preparation has done!\n\n`MyTrainer` overwraps `build_evaluator` method of `DefaultTrainer` provided by `detectron2` to support validation dataset evaluation.\n\n\n1. `build_train_loader` & `build_test_loader`: \nThese class methods deine how to construct DataLoader for training data & validation data respectively.\nHere `AlbumentationMapper` is passed to construct DataLoader to insert customized augmentation process.\n\n2. `build_evaluator`:\nThis class method defines how to construct Evaluator. \nHere implemented `VinbigdataEvaluator` is constructed (we can also use `COCOEvaluator` here).\n\n3. `build_hooks`:\nThis method defines how to construct hooks. I insert `LossEvalHook` before evalutor to work well."},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"import os\n\nfrom detectron2.data import build_detection_test_loader, build_detection_train_loader\nfrom detectron2.engine import DefaultPredictor, DefaultTrainer, launch\n\n# from detectron2.evaluation import COCOEvaluator, PascalVOCDetectionEvaluator\n\n\nclass MyTrainer(DefaultTrainer):\n    @classmethod\n    def build_train_loader(cls, cfg, sampler=None):\n        return build_detection_train_loader(\n            cfg, mapper=AlbumentationsMapper(cfg, True), sampler=sampler\n        )\n\n    @classmethod\n    def build_test_loader(cls, cfg, dataset_name):\n        return build_detection_test_loader(\n            cfg, dataset_name, mapper=AlbumentationsMapper(cfg, False)\n        )\n\n    @classmethod\n    def build_evaluator(cls, cfg, dataset_name, output_folder=None):\n        if output_folder is None:\n            output_folder = os.path.join(cfg.OUTPUT_DIR, \"inference\")\n        # return PascalVOCDetectionEvaluator(dataset_name)  # not working\n        # return COCOEvaluator(dataset_name, (\"bbox\",), False, output_dir=output_folder)\n        return VinbigdataEvaluator(dataset_name, (\"bbox\",), False, output_dir=output_folder)\n\n    def build_hooks(self):\n        hooks = super(MyTrainer, self).build_hooks()\n        cfg = self.cfg\n        if len(cfg.DATASETS.TEST) > 0:\n            loss_eval_hook = LossEvalHook(\n                cfg.TEST.EVAL_PERIOD,\n                self.model,\n                MyTrainer.build_test_loader(cfg, cfg.DATASETS.TEST[0]),\n            )\n            hooks.insert(-1, loss_eval_hook)\n\n        return hooks\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## LR scheduling\n\nTo further customize learning rate scheduling you may override `build_lr_scheduler` class method to construct any pytorch LRScheduler.\n\nDefault `build_lr_schduler` method ([docs](https://detectron2.readthedocs.io/en/latest/_modules/detectron2/solver/build.html#build_lr_scheduler)) supports only 2 types of LR scheduling, WarmupMultiStepLR (default) & WarmupCosineLR. You can change which one to use by setting `cfg.SOLVER.LR_SCHEDULER_NAME` as you can see from the docs."},{"metadata":{},"cell_type":"markdown","source":"Now the methods are ready. main scripts starts from here."},{"metadata":{},"cell_type":"markdown","source":"<a id=\"load_data\"></a>\n# Loading Data\n\nThis `Flags` class is to manage experiments. I will tune these parameters through the competition to improve model's performance."},{"metadata":{"_kg_hide-input":true,"_kg_hide-output":true,"trusted":true},"cell_type":"code","source":"import argparse\nimport dataclasses\nimport json\nimport os\nimport pickle\nimport random\nimport sys\nfrom dataclasses import dataclass\nfrom distutils.util import strtobool\nfrom pathlib import Path\n\nimport cv2\nimport detectron2\nimport numpy as np\nimport pandas as pd\nimport torch\nfrom detectron2 import model_zoo\nfrom detectron2.config import get_cfg\nfrom detectron2.data import DatasetCatalog, MetadataCatalog\nfrom detectron2.engine import DefaultPredictor, DefaultTrainer, launch\nfrom detectron2.evaluation import COCOEvaluator\nfrom detectron2.structures import BoxMode\nfrom detectron2.utils.logger import setup_logger\nfrom detectron2.utils.visualizer import Visualizer\nfrom tqdm import tqdm\n\nsetup_logger()","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"# --- flags ---\nfrom dataclasses import dataclass, field\nfrom typing import Dict\n\n\n@dataclass\nclass Flags:\n    # General\n    debug: bool = True\n    outdir: str = \"results/det\"\n\n    # Data config\n    imgdir_name: str = \"../input/vinbigdata-512-image-dataset/vinbigdata/\"\n    split_mode: str = \"all_train\"  # all_train or valid20\n    seed: int = 111\n    train_data_type: str = \"original\"  # original or wbf\n    use_class14: bool = False\n    # Training config\n    iter: int = 10000\n    ims_per_batch: int = 1  # images per batch, this corresponds to \"total batch size\"\n    num_workers: int = 4\n    lr_scheduler_name: str = \"WarmupMultiStepLR\"  # WarmupMultiStepLR (default) or WarmupCosineLR\n    base_lr: float = 0.00025\n    roi_batch_size_per_image: int = 512\n    eval_period: int = 10000\n    aug_kwargs: Dict = field(default_factory=lambda: {})\n\n    def update(self, param_dict: Dict) -> \"Flags\":\n        # Overwrite by `param_dict`\n        for key, value in param_dict.items():\n            if not hasattr(self, key):\n                raise ValueError(f\"[ERROR] Unexpected key for flag = {key}\")\n            setattr(self, key, value)\n        return self","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"# flags_dict = {\n#     \"debug\": True,\n#     \"outdir\": \"results/debug\", \n#     \"imgdir_name\": \"vinbigdata-chest-xray-resized-png-256x256\",\n#     \"split_mode\": \"valid20\",\n#     \"iter\": 100,  # debug, small value should be set.\n#     \"roi_batch_size_per_image\": 128,  # faster, and good enough for this toy dataset (default: 512)\n#     \"eval_period\": 20,\n#     \"aug_kwargs\": {\n#         \"HorizontalFlip\": {\"p\": 0.5},\n#         \"ShiftScaleRotate\": {\"scale_limit\": 0.15, \"rotate_limit\": 10, \"p\": 0.5},\n#         \"RandomBrightnessContrast\": {\"p\": 0.5}\n#     }\n# }","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"flags_dict = {\n    \"debug\": False,\n    \"outdir\": \"results/v30\", \n    \"imgdir_name\": \"vinbigdata-chest-xray-original-png\",\n    \"split_mode\": \"valid20\",\n    \"iter\": 6500,\n    \"roi_batch_size_per_image\": 256,\n    \"eval_period\": 500,\n    \"lr_scheduler_name\": \"WarmupCosineLR\", #\"WarmupMultiStepLR\" ,\n    \"base_lr\": 0.005,### ##changed base lr ###0.005 worked better taken from v22\n    \"num_workers\": 4,\n    \"aug_kwargs\": {\n        \"HorizontalFlip\": {\"p\": 0.75}, ##horiozontal flip changed !!!!!!!!!!!!!!!! 0.25\n        \"ShiftScaleRotate\": {\"scale_limit\": 0.15, \"rotate_limit\": 10, \"p\": 0.5},\n        \"RandomBrightnessContrast\": {\"p\": 0.5},\n        #\"RandomGamma\": {\"p\": 0.3},\n        #\"RandomContrast\": {\"p\": 0.3},\n        \n        \n        #\"OpticalDistortion\": {\"distort_limit\":2, \"shift_limit\":0.5 , \"p\":0.3}, ##optical distrotion not applied here \n        #\"ElasticTransform\": {\"alpha\":120, \"sigma\":120 * 0.05, \"alpha_affine\":120 * 0.03}, ### same problem with elastic transform \n        #\"RandomResizedCrop\": {\"height\":100, \"width\":100, \"p\":0.1}\n        \n    }\n}\n\n'''\n A.HorizontalFlip(),\n            A.OneOf([\n                A.RandomContrast(),\n                A.RandomGamma(),\n                A.RandomBrightness(),\n                ], p=0.3),\n            A.OneOf([\n                A.ElasticTransform(alpha=120, sigma=120 * 0.05, alpha_affine=120 * 0.03),\n                A.GridDistortion(),\n                A.OpticalDistortion(distort_limit=2, shift_limit=0.5),\n                ], p=0.3),\n            A.ShiftScaleRotate(p=0.2),\n\n'''\n\n\n\n\n''' \n        albu.Compose([\n        albu.HorizontalFlip(),\n        albu.OneOf([\n        albu.RandomContrast(),\n        albu.RandomGamma(),\n        albu.RandomBrightness(),\n        ], p=0.3),\n        albu.OneOf([\n        albu.ElasticTransform(alpha=120, sigma=120 * 0.05, alpha_affine=120 * 0.03),\n        albu.GridDistortion(),\n        albu.OpticalDistortion(distort_limit=2, shift_limit=0.5), #### not for bbox\n        ], p=0.3),\n        albu.ShiftScaleRotate(),\n        albu.Resize(img_size,img_size,always_apply=True),\n        ])\n'''","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"_kg_hide-output":true,"trusted":true},"cell_type":"code","source":"# args = parse()\nprint(\"torch\", torch.__version__)\nflags = Flags().update(flags_dict)\nprint(\"flags\", flags)\ndebug = flags.debug\noutdir = Path(flags.outdir)\nos.makedirs(str(outdir), exist_ok=True)\nflags_dict = dataclasses.asdict(flags)\nsave_yaml(outdir / \"flags.yaml\", flags_dict)\n\n# --- Read data ---\ninputdir = Path(\"/kaggle/input\")\ndatadir = inputdir / \"vinbigdata-chest-xray-abnormalities-detection\"\nimgdir = inputdir / flags.imgdir_name #  \"/kaggle/input/vinbigdata-1024-image-dataset/vinbigdata\"\nprint (imgdir, inputdir)\n# Read in the data CSV files\ntrain_df = pd.read_csv(datadir / \"train.csv\")\ntrain = train_df  # alias\n# sample_submission = pd.read_csv(datadir / 'sample_submission.csv')","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"train_data_type = flags.train_data_type\nif flags.use_class14:\n    thing_classes.append(\"No finding\")\n\nsplit_mode = flags.split_mode\nif split_mode == \"all_train\":\n    DatasetCatalog.register(\n        \"vinbigdata_train\",\n        lambda: get_vinbigdata_dicts(\n            imgdir, train_df, train_data_type, debug=debug, use_class14=flags.use_class14\n        ),\n    )\n    MetadataCatalog.get(\"vinbigdata_train\").set(thing_classes=thing_classes)\nelif split_mode == \"valid20\":\n    # To get number of data...\n    n_dataset = len(\n        get_vinbigdata_dicts(\n            imgdir, train_df, train_data_type, debug=debug, use_class14=flags.use_class14\n        )\n    )\n    n_train = int(n_dataset * 0.8)\n    print(\"n_dataset\", n_dataset, \"n_train\", n_train)\n    rs = np.random.RandomState(flags.seed)\n    inds = rs.permutation(n_dataset)\n    train_inds, valid_inds = inds[:n_train], inds[n_train:]\n    DatasetCatalog.register(\n        \"vinbigdata_train\",\n        lambda: get_vinbigdata_dicts(\n            imgdir,\n            train_df,\n            train_data_type,\n            debug=debug,\n            target_indices=train_inds,\n            use_class14=flags.use_class14,\n        ),\n    )\n    MetadataCatalog.get(\"vinbigdata_train\").set(thing_classes=thing_classes)\n    DatasetCatalog.register(\n        \"vinbigdata_valid\",\n        lambda: get_vinbigdata_dicts(\n            imgdir,\n            train_df,\n            train_data_type,\n            debug=debug,\n            target_indices=valid_inds,\n            use_class14=flags.use_class14,\n            \n        ),\n    )\n    MetadataCatalog.get(\"vinbigdata_valid\").set(thing_classes=thing_classes)\nelse:\n    raise ValueError(f\"[ERROR] Unexpected value split_mode={split_mode}\")\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"dataset_dicts = get_vinbigdata_dicts(imgdir, train, debug=debug)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<a id=\"data_vis\"></a>\n# Data Visualization\n\nIt's also very easy to visualize prepared training dataset with `detectron2`.<br/>\nIt provides `Visualizer` class, we can use it to draw an image with bounding box as following."},{"metadata":{},"cell_type":"markdown","source":"<a id=\"training\"></a>\n# Training"},{"metadata":{"trusted":true},"cell_type":"code","source":"from detectron2.config.config import CfgNode as CN\n\ncfg = get_cfg()\ncfg.aug_kwargs = CN(flags.aug_kwargs)  # pass aug_kwargs to cfg\n\noriginal_output_dir = cfg.OUTPUT_DIR\ncfg.OUTPUT_DIR = str(outdir)\nprint(f\"cfg.OUTPUT_DIR {original_output_dir} -> {cfg.OUTPUT_DIR}\")\n\nconfig_name = \"COCO-Detection/faster_rcnn_R_50_FPN_3x.yaml\"\ncfg.merge_from_file(model_zoo.get_config_file(config_name))\ncfg.DATASETS.TRAIN = (\"vinbigdata_train\",)\nprint (cfg.DATASETS.TRAIN)\nif split_mode == \"all_train\":\n    cfg.DATASETS.TEST = ()\nelse:\n    cfg.DATASETS.TEST = (\"vinbigdata_valid\",)\n    cfg.TEST.EVAL_PERIOD = flags.eval_period\n\ncfg.DATALOADER.NUM_WORKERS = flags.num_workers\n# Let training initialize from model zoo\ncfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url(config_name)\ncfg.SOLVER.IMS_PER_BATCH = flags.ims_per_batch\ncfg.SOLVER.LR_SCHEDULER_NAME = flags.lr_scheduler_name\ncfg.SOLVER.BASE_LR = flags.base_lr  # pick a good LR\ncfg.SOLVER.MAX_ITER = flags.iter\ncfg.SOLVER.CHECKPOINT_PERIOD = 100000  # Small value=Frequent save need a lot of storage.\ncfg.MODEL.ROI_HEADS.BATCH_SIZE_PER_IMAGE = flags.roi_batch_size_per_image\ncfg.MODEL.ROI_HEADS.NUM_CLASSES = len(thing_classes)\n# NOTE: this config means the number of classes,\n# but a few popular unofficial tutorials incorrect uses num_classes+1 here.\n\n\n\n\n### working with weights and biases to test things now \nos.environ['WANDB_SILENT'] = 'true'\n\n\nimport wandb\nimport yaml\n\nfrom kaggle_secrets import UserSecretsClient\nuser_secrets = UserSecretsClient()\nwandb_api = user_secrets.get_secret(\"wandb_api\")\n\nwandb.login(key=wandb_api)\n\ncfg_wandb = yaml.safe_load(cfg.dump())\nrun = wandb.init(project=\"vbd-xrays-hyperparam\", name=\"R50_img_orig_kaggle_sc_v17\", config = cfg_wandb, sync_tensorboard=True)\n\n\n\n\n\n## uncommented to test laptop outputs\n\n'''\ncfg.MODEL.ANCHOR_GENERATOR.SIZES = [[16], [32], [64], [128], [256], [512], [1024]]\ncfg.MODEL.RPN.IN_FEATURES = ['p2', 'p2', 'p3', 'p4', 'p5', 'p6', 'p6']\n\ncfg.MODEL.ANCHOR_GENERATOR.ASPECT_RATIOS = [[0.33, 0.5, 1.0, 2.0, 3.0]]\n'''\n\n\nos.makedirs(cfg.OUTPUT_DIR, exist_ok=True)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"trainer = MyTrainer(cfg)\ntrainer.resume_or_load(resume=False)\ntrainer.train()\n#wandb.agent(sweep_id, trainer.train())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"run.finish()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#dict_mylaptop_val_loss = {'x':[49, 99, 149], 'y':[ 0.326954, 0.305528, 0.284102]}\n\n#wandb.log('validation loss local': dict_mylaptop_val_loss['x'], 'step_local': dict_mylaptop_val_loss['y'])\n#wandb.log(dict_mylaptop_val_loss)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"It's actually very easy to use multiple gpus for training.\n\nYou just need to wrap above training scripts by `main` method and use `launch` method provided by `detectron2`.\n\nPlease refer official example [train_net.py](https://github.com/facebookresearch/detectron2/blob/master/tools/train_net.py#L161) for details."},{"metadata":{},"cell_type":"markdown","source":"<a id=\"vis_loss\"></a>\n# Visualize loss curve & competition metric AP40\n\nAs I explained, the calculated metrics are saved in `metrics.json`. We can analyze/plot them to check how the training proceeded."},{"metadata":{"trusted":true},"cell_type":"code","source":"#cfg.MODEL.WEIGHTS = os.path.join(cfg.OUTPUT_DIR, \"model_final.pth\")  # path to the model we just trained\nprint (cfg.MODEL.WEIGHTS)\n","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"metrics_df = pd.read_json(outdir / \"metrics.json\", orient=\"records\", lines=True)\nmdf = metrics_df.sort_values(\"iteration\")\nmdf","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"# 1. Loss curve\nfig, ax = plt.subplots(1,2, figsize =(15,6))\n\nmdf1 = mdf[~mdf[\"total_loss\"].isna()]\nax[0].plot(mdf1[\"iteration\"], mdf1[\"total_loss\"], c=\"C0\", label=\"train\")\nif \"validation_loss\" in mdf.columns:\n    mdf2 = mdf[~mdf[\"validation_loss\"].isna()]\n    ax[1].plot(mdf2[\"iteration\"], mdf2[\"validation_loss\"], c=\"C1\", label=\"validation\")\n\n# ax.set_ylim([0, 0.5])\nax[0].legend()\nax[0].set_title(\"Loss curve\")\nax[1].set_title(\"Validation loss\")\n\nplt.show()\nplt.savefig(outdir/\"loss.png\")","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"fig, ax = plt.subplots()\nmdf3 = mdf[~mdf[\"bbox/AP75\"].isna()]\nax.plot(mdf3[\"iteration\"], mdf3[\"bbox/AP75\"] / 100., c=\"C2\", label=\"validation\")\n\nax.legend()\nax.set_title(\"AP40\")\nplt.show()\nplt.savefig(outdir / \"AP40.png\")\nprint (mdf3[\"bbox/AP75\"] )","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"fig, ax = plt.subplots()\nmdf_bbox_class = mdf3.iloc[-1][[f\"bbox/AP-{col}\" for col in thing_classes]]\nprint (mdf_bbox_class)\nmdf_bbox_class.plot(kind=\"bar\", ax=ax)\n_ = ax.set_title(\"AP by class\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"\n"},{"metadata":{},"cell_type":"markdown","source":""},{"metadata":{},"cell_type":"markdown","source":""},{"metadata":{},"cell_type":"markdown","source":""},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"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":4,"nbformat_minor":4}