{"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":"# Intro\n\nCompetition home page: https://www.kaggle.com/competitions/rsna-2022-cervical-spine-fracture-detection","metadata":{}},{"cell_type":"markdown","source":"# Import library","metadata":{}},{"cell_type":"code","source":"%%capture\n# Install detectron2\n!python -m pip install 'git+https://github.com/facebookresearch/detectron2.git'","metadata":{"_kg_hide-output":true,"_kg_hide-input":false,"execution":{"iopub.status.busy":"2022-08-02T23:59:25.121516Z","iopub.execute_input":"2022-08-02T23:59:25.122236Z","iopub.status.idle":"2022-08-02T23:59:27.807592Z","shell.execute_reply.started":"2022-08-02T23:59:25.122147Z","shell.execute_reply":"2022-08-02T23:59:27.805679Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport copy\nimport pickle\nimport argparse\nimport json\nimport random\nimport sys\nimport time\nimport datetime\nimport logging\n\n\nimport pandas as pd\nimport numpy as np\n\nfrom PIL import Image\nimport cv2\nimport pydicom\nfrom pydicom.pixel_data_handlers.util import apply_voi_lut\nimport matplotlib.pyplot as plt\n\nfrom sklearn.model_selection import StratifiedKFold\n\nimport torch\nfrom detectron2 import model_zoo\nfrom detectron2.structures import BoxMode\nimport detectron2.data.transforms as T\nfrom detectron2.data import detection_utils as utils\nfrom detectron2.data import build_detection_test_loader, build_detection_train_loader\nfrom detectron2.engine import DefaultPredictor, DefaultTrainer, launch\nfrom detectron2.evaluation import COCOEvaluator, PascalVOCDetectionEvaluator\nfrom detectron2.config import CfgNode as CN\nfrom detectron2.config import get_cfg\nimport detectron2\nfrom detectron2 import model_zoo\nfrom detectron2.config import get_cfg\nfrom detectron2.data import DatasetCatalog, MetadataCatalog\nfrom detectron2.utils.logger import setup_logger, log_every_n_seconds\nfrom detectron2.utils.visualizer import Visualizer\nfrom detectron2.engine.hooks import HookBase\nimport detectron2.utils.comm as comm\n\n","metadata":{"execution":{"iopub.status.busy":"2022-08-02T23:59:27.812264Z","iopub.execute_input":"2022-08-02T23:59:27.813288Z","iopub.status.idle":"2022-08-02T23:59:31.337435Z","shell.execute_reply.started":"2022-08-02T23:59:27.813241Z","shell.execute_reply":"2022-08-02T23:59:31.334305Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Set configs","metadata":{}},{"cell_type":"code","source":"thingClasses = [\n    \"Fractured\",\n    \"No finding\"\n]\n\ncfgDict = {\n    \"dicomPath\": \"../input/rsna-2022-cervical-spine-fracture-detection/train_images/\",\n    \"orgDataPath\": \"../input/rsna-2022-cervical-spine-fracture-detection/\",\n    \"newDataPath\": \"../input/rsna-csfd-256x256-jpg-dataset/\",\n    \"cachePath\": \"./\",\n    \"trainDataName\": \"csfdTrain\",\n    \"validDataName\": \"csfdValid\",\n    \"sampleSize\": 500,\n    \"imSize\": 256,\n    \"modelName\": \"COCO-Detection/faster_rcnn_R_50_FPN_3x.yaml\",\n    \"debug\": True,\n    \"outdir\": \"./results/\",\n    \"logFile\": \"log.txt\",\n    \"splitMode\": True,\n    \"seed\": 111,\n    \"device\": \"cuda\",\n    \"iter\": 100,\n    \"ims_per_batch\": 16,\n    \"roi_batch_size_per_image\": 128,\n    \"eval_period\": 20,\n    \"lr_scheduler_name\": \"WarmupCosineLR\",\n    \"base_lr\": 0.001,\n    \"checkpoint_period\":50,\n    \"num_workers\": 4,\n    \"score_thresh_test\": 0.05,\n    \"augKwargs\": {\n        \"RandomFlip\": {\"prob\": 0.5},\n        \"RandomRotation\": {\"angle\": [0,360]}\n    }\n}\n\nsetup_logger(os.path.join(cfgDict[\"outdir\"],cfgDict[\"logFile\"]))\nrandom.seed(cfgDict[\"seed\"])","metadata":{"execution":{"iopub.status.busy":"2022-08-02T23:59:31.338298Z","iopub.status.idle":"2022-08-02T23:59:31.338677Z","shell.execute_reply.started":"2022-08-02T23:59:31.3385Z","shell.execute_reply":"2022-08-02T23:59:31.338518Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Preprocess data\n\nWe use the dataset [RSNA-CSFD: 256x256 Jpg Dataset](https://www.kaggle.com/datasets/awsaf49/rsna-csfd-256x256-jpg-dataset).\n\nExample code is provided below.","metadata":{}},{"cell_type":"code","source":"dirPath = cfgDict[\"dicomPath\"]\nfor (dirPath, dirNames, fileNames) in os.walk(dirPath):\n    if fileNames:\n        filePath = os.path.join(dirPath,fileNames[0])\n        break\n# Read dicom\ndicom = pydicom.read_file(filePath)\n# Transform raw image to \"human-friendly\" view\nimgArray = apply_voi_lut(dicom.pixel_array,dicom)\n# Fix inverted image\nif dicom.PhotometricInterpretation == \"MONOCHROME1\":\n    imgArray = np.amax(imgArray) - imgArray\n# Scale image value to (0,255)        \nimgArray = imgArray - np.min(imgArray)\nimgArray = imgArray / np.max(imgArray)\nimgArray = (imgArray * 255).astype(np.uint8)\n# Resize image to (imSize x imSize)\nimSize = cfgDict[\"imSize\"]\nim = Image.fromarray(imgArray)\nim = im.resize((imSize,imSize),Image.LANCZOS)\n# Display image\nim","metadata":{"_uuid":"86566ab8-570a-4b8a-9743-7f819bbe790c","_cell_guid":"2b2af0a3-acfc-4b91-89bb-7587ea00405a","execution":{"iopub.status.busy":"2022-08-02T23:59:31.34016Z","iopub.status.idle":"2022-08-02T23:59:31.340993Z","shell.execute_reply.started":"2022-08-02T23:59:31.340747Z","shell.execute_reply":"2022-08-02T23:59:31.340773Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Prepare datasets","metadata":{}},{"cell_type":"code","source":"def getDatasetDicts(cfg,filenames,dfTrain,dataType=\"train\",cache=False):\n    \"\"\"Function to create dataset dicts\"\"\"\n    \n    imSize = cfg[\"imSize\"]\n    # Dicom image size. Most images with bounding box are 512x512. Others are 768x768.\n    # Update this when the dataset includes the original h and w for all images\n    h = 512\n    w = 512\n    cachePath = os.path.join(cfg[\"cachePath\"],\"cache\"+dataType+\".pkl\")\n    datasetDicts = []\n    \n    if not cache and os.path.exists(cachePath):\n        # Load dicts\n        with open(cachePath, mode=\"rb\") as f:\n            datasetDicts = pickle.load(f)\n    else:\n        # Cache dicts\n        for filename in filenames:\n            datasetDict = {}\n            annotations = []\n\n            datasetDict[\"file_name\"] = filename\n            datasetDict[\"image_id\"] = filename\n            datasetDict[\"height\"] = imSize\n            datasetDict[\"width\"] = imSize\n\n            # Add annotations for training/validation data\n            if dataType.lower() != \"test\":\n                dirnames = filename.split(\"/\")\n                uid = dirnames[-2]\n                sliceNum = dirnames[-1]\n                sliceNum = sliceNum.split(\".\")\n                sliceNum = int(sliceNum[0])\n                df = dfTrain[(dfTrain[\"StudyInstanceUID\"]==uid) & (dfTrain[\"slice_number\"]==sliceNum)]\n                if not df.empty:\n                    classId = 0\n                    hRatio = imSize/h\n                    wRatio = imSize/w\n                    bboxResized = [ float(df[\"x\"].values[0])*wRatio,\n                                    float(df[\"y\"].values[0])*hRatio,\n                                    float((df[\"x\"]+df[\"width\"]).values[0])*wRatio,\n                                    float((df[\"y\"]+df[\"height\"]).values[0])*hRatio ]\n                else: \n                    classId = 1\n                    bboxResized = [0, 0, imSize, imSize]      \n                annotation = { \"bbox\": bboxResized,\n                                \"bbox_mode\": BoxMode.XYXY_ABS,\n                                \"category_id\": classId }\n                annotations.append(annotation)\n                datasetDict[\"annotations\"] = annotations\n\n            datasetDicts.append(datasetDict)\n\n        with open(cachePath, mode=\"wb\") as f:\n            pickle.dump(datasetDicts, f)\n    \n    return datasetDicts\n","metadata":{"execution":{"iopub.status.busy":"2022-08-02T23:59:31.343688Z","iopub.status.idle":"2022-08-02T23:59:31.344158Z","shell.execute_reply.started":"2022-08-02T23:59:31.343913Z","shell.execute_reply":"2022-08-02T23:59:31.343936Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Prepare augmentation","metadata":{}},{"cell_type":"code","source":"class AugMapper:\n    \"\"\"Custom mapper class for augmentations\"\"\"\n\n    def __init__(self, cfg, isTrain=True):\n        augKwargs = cfg[\"augKwargs\"]\n        augList = []\n        # Define a sequence of augmentations\n        if isTrain:\n            augList.extend([getattr(T, name)(**kwargs) for name, kwargs in augKwargs.items()])\n        self.augmentations = T.AugmentationList(augList)\n        self.isTrain = isTrain\n\n    def __call__(self, datasetDict):\n        datasetDict = copy.deepcopy(datasetDict)  # it will be modified by code below\n        image = utils.read_image(datasetDict[\"file_name\"], format=\"BGR\")\n        augInput = T.AugInput(image) # the augmentation input\n        transforms = self.augmentations(augInput) # apply the augmentation\n        image = augInput.image # new image\n        imShape = image.shape[:2]  # h, w\n        datasetDict[\"image\"] = torch.as_tensor(image.transpose(2, 0, 1).astype(\"float32\")) # HWC to CHW\n        annos = [ utils.transform_instance_annotations(annotation, transforms, imShape) \n                    for annotation in datasetDict.pop(\"annotations\") \n                    if annotation.get(\"iscrowd\", 0) == 0 ] # apply the augmentation to annotation\n        instances = utils.annotations_to_instances(annos, imShape)\n        datasetDict[\"instances\"] = utils.filter_empty_instances(instances)\n        \n        return datasetDict","metadata":{"execution":{"iopub.status.busy":"2022-08-02T23:59:31.346193Z","iopub.status.idle":"2022-08-02T23:59:31.347184Z","shell.execute_reply.started":"2022-08-02T23:59:31.346917Z","shell.execute_reply":"2022-08-02T23:59:31.346942Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Prepare loss eval hook for validation","metadata":{}},{"cell_type":"code","source":"class 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        comm.synchronize()\n\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        \n    def after_step(self):\n        next_iter = 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","metadata":{"execution":{"iopub.status.busy":"2022-08-02T23:59:31.348401Z","iopub.status.idle":"2022-08-02T23:59:31.349096Z","shell.execute_reply.started":"2022-08-02T23:59:31.348814Z","shell.execute_reply":"2022-08-02T23:59:31.348839Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Custom DefaultTrainer","metadata":{}},{"cell_type":"code","source":"class MyTrainer(DefaultTrainer):\n    \"\"\"Overwrite DefaultTrainer methods\"\"\"\n    \n    @classmethod\n    def build_train_loader(cls, cfg, sampler=None):\n        return build_detection_train_loader(\n            cfg, mapper=AugMapper(cfg, True), sampler=sampler\n        )\n\n    @classmethod\n    def build_test_loader(cls, cfg, datasetName):\n        return build_detection_test_loader(\n            cfg, datasetName, mapper=AugMapper(cfg, False)\n        )\n\n    @classmethod\n    def build_evaluator(cls, cfg, datasetName, outputFolder=None):\n        if outputFolder is None:\n            outputFolder = os.path.join(cfg.OUTPUT_DIR, \"inference\")\n        return COCOEvaluator(datasetName, (\"bbox\",), False, output_dir=outputFolder)\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","metadata":{"execution":{"iopub.status.busy":"2022-08-02T23:59:31.350531Z","iopub.status.idle":"2022-08-02T23:59:31.351323Z","shell.execute_reply.started":"2022-08-02T23:59:31.351066Z","shell.execute_reply":"2022-08-02T23:59:31.351098Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Load, split, and register data","metadata":{}},{"cell_type":"code","source":"# Load train bounding boxes\norgDataPath = cfgDict[\"orgDataPath\"]\ntrainCSVPath = os.path.join(orgDataPath,\"train_bounding_boxes.csv\")\ndfTrain = pd.read_csv(trainCSVPath)","metadata":{"execution":{"iopub.status.busy":"2022-08-02T23:59:31.352971Z","iopub.status.idle":"2022-08-02T23:59:31.353456Z","shell.execute_reply.started":"2022-08-02T23:59:31.353199Z","shell.execute_reply":"2022-08-02T23:59:31.353221Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# List all image files\nnewDataPath = cfgDict[\"newDataPath\"]\ntrainImgPath = os.path.join(newDataPath,\"train_images\")\nfilenames = []\nfor (trainImgPath, dirNames, fileNames) in os.walk(trainImgPath):\n    if fileNames:\n        filenames += [trainImgPath+\"/\"+f for f in fileNames]","metadata":{"execution":{"iopub.status.busy":"2022-08-02T23:59:31.355054Z","iopub.status.idle":"2022-08-02T23:59:31.355543Z","shell.execute_reply.started":"2022-08-02T23:59:31.355288Z","shell.execute_reply":"2022-08-02T23:59:31.355311Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Cache dataset dicts\nif cfgDict[\"debug\"]:\n    datasetDicts = getDatasetDicts(cfgDict,filenames=random.sample(filenames,cfgDict[\"sampleSize\"]),dfTrain=dfTrain,cache=True)\nelse:\n    datasetDicts = getDatasetDicts(cfgDict,filenames=filenames,dfTrain=dfTrain,cache=True)","metadata":{"execution":{"iopub.status.busy":"2022-08-02T23:59:31.357168Z","iopub.status.idle":"2022-08-02T23:59:31.357821Z","shell.execute_reply.started":"2022-08-02T23:59:31.357571Z","shell.execute_reply":"2022-08-02T23:59:31.357594Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Split train and valid\nskf = StratifiedKFold(n_splits=5, shuffle=True, random_state=cfgDict[\"seed\"])\ny = np.array([d[\"annotations\"][0][\"category_id\"]==0 for d in datasetDicts])\nsplitIdx = list(skf.split(datasetDicts, y))\ntrainIdx, validIdx = splitIdx[0]","metadata":{"execution":{"iopub.status.busy":"2022-08-02T23:59:31.360169Z","iopub.status.idle":"2022-08-02T23:59:31.361526Z","shell.execute_reply.started":"2022-08-02T23:59:31.361197Z","shell.execute_reply":"2022-08-02T23:59:31.361244Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Register\nDatasetCatalog.clear()\nDatasetCatalog.register(\n        cfgDict[\"trainDataName\"],\n        lambda: getDatasetDicts(cfgDict,dfTrain=dfTrain,filenames=[filenames[x] for x in trainIdx],dataType=\"train\",cache=True)\n    )\nMetadataCatalog.get(cfgDict[\"trainDataName\"]).set(thing_classes=thingClasses)\nDatasetCatalog.register(\n        cfgDict[\"validDataName\"],\n        lambda: getDatasetDicts(cfgDict,dfTrain=dfTrain,filenames=[filenames[x] for x in validIdx],dataType=\"valid\",cache=True)\n    )\nMetadataCatalog.get(cfgDict[\"validDataName\"]).set(thing_classes=thingClasses)","metadata":{"execution":{"iopub.status.busy":"2022-08-02T23:59:31.362858Z","iopub.status.idle":"2022-08-02T23:59:31.363687Z","shell.execute_reply.started":"2022-08-02T23:59:31.363437Z","shell.execute_reply":"2022-08-02T23:59:31.363462Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Visualize data","metadata":{}},{"cell_type":"code","source":"csfdMetadata = MetadataCatalog.get(cfgDict[\"validDataName\"])\nd = datasetDicts[3]\nimg = cv2.imread(d[\"file_name\"])\nvisualizer = Visualizer(img[:, :, ::-1], metadata=csfdMetadata, scale=1.5)\nout = visualizer.draw_dataset_dict(d)\nImage.fromarray(out.get_image()[:, :, ::-1])","metadata":{"execution":{"iopub.status.busy":"2022-08-02T23:59:31.365306Z","iopub.status.idle":"2022-08-02T23:59:31.365872Z","shell.execute_reply.started":"2022-08-02T23:59:31.365622Z","shell.execute_reply":"2022-08-02T23:59:31.365647Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Create Yacs config","metadata":{}},{"cell_type":"code","source":"cfg = get_cfg()\n\ncfg.augKwargs = CN(cfgDict[\"augKwargs\"])  # pass augKwargs to cfg as a CN\ncfg.merge_from_file(model_zoo.get_config_file(cfgDict[\"modelName\"]))\ncfg.MODEL.DEVICE = cfgDict[\"device\"]\ncfg.OUTPUT_DIR = cfgDict[\"outdir\"]\ncfg.DATASETS.TRAIN = (cfgDict[\"trainDataName\"],)\nif cfgDict[\"splitMode\"] is None:\n    cfg.DATASETS.TEST = ()\nelse:\n    cfg.DATASETS.TEST = (cfgDict[\"validDataName\"],)\n    cfg.TEST.EVAL_PERIOD = cfgDict[\"eval_period\"]\ncfg.DATALOADER.NUM_WORKERS = cfgDict[\"num_workers\"]\ncfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url(cfgDict[\"modelName\"])\ncfg.SOLVER.IMS_PER_BATCH = cfgDict[\"ims_per_batch\"]\ncfg.SOLVER.LR_SCHEDULER_NAME = cfgDict[\"lr_scheduler_name\"]\ncfg.SOLVER.BASE_LR = cfgDict[\"base_lr\"]\ncfg.SOLVER.MAX_ITER = cfgDict[\"iter\"]\ncfg.SOLVER.CHECKPOINT_PERIOD = cfgDict[\"checkpoint_period\"]\ncfg.MODEL.ROI_HEADS.BATCH_SIZE_PER_IMAGE = cfgDict[\"roi_batch_size_per_image\"]\ncfg.MODEL.ROI_HEADS.NUM_CLASSES = len(thingClasses)\n\nos.makedirs(cfg.OUTPUT_DIR, exist_ok=True)","metadata":{"execution":{"iopub.status.busy":"2022-08-02T23:59:31.368307Z","iopub.status.idle":"2022-08-02T23:59:31.369006Z","shell.execute_reply.started":"2022-08-02T23:59:31.368759Z","shell.execute_reply":"2022-08-02T23:59:31.368783Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Train model","metadata":{}},{"cell_type":"code","source":"trainer = MyTrainer(cfg)\ntrainer.resume_or_load(resume=False)\ntrainer.train()","metadata":{"execution":{"iopub.status.busy":"2022-08-02T23:59:31.370305Z","iopub.status.idle":"2022-08-02T23:59:31.37102Z","shell.execute_reply.started":"2022-08-02T23:59:31.370767Z","shell.execute_reply":"2022-08-02T23:59:31.370791Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Evaluation","metadata":{}},{"cell_type":"code","source":"dfMetrics = pd.read_json(os.path.join(cfgDict[\"outdir\"],\"metrics.json\"), orient=\"records\", lines=True)\ndfMetrics = dfMetrics.sort_values(\"iteration\")\ndfMetrics.head()","metadata":{"execution":{"iopub.status.busy":"2022-08-02T23:59:31.372303Z","iopub.status.idle":"2022-08-02T23:59:31.373004Z","shell.execute_reply.started":"2022-08-02T23:59:31.372752Z","shell.execute_reply":"2022-08-02T23:59:31.372776Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dfTrainLoss = dfMetrics[~dfMetrics[\"total_loss\"].isna()]\nplt.plot(dfTrainLoss[\"iteration\"], dfTrainLoss[\"total_loss\"], c=\"C0\", label=\"train\")\nif \"validation_loss\" in dfMetrics.columns:\n    dfValidLoss = dfMetrics[~dfMetrics[\"validation_loss\"].isna()]\n    plt.plot(dfValidLoss[\"iteration\"], dfValidLoss[\"validation_loss\"], c=\"C1\", label=\"validation\")\n\nplt.legend()\nplt.title(\"Loss curve\")\nplt.xlabel(\"Iteration\")\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-08-02T23:59:31.374275Z","iopub.status.idle":"2022-08-02T23:59:31.374973Z","shell.execute_reply.started":"2022-08-02T23:59:31.374728Z","shell.execute_reply":"2022-08-02T23:59:31.374752Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Predict","metadata":{}},{"cell_type":"code","source":"# Same cfg from trainer and use the final model output to initialize the predictor\ncfg.MODEL.WEIGHTS = os.path.join(cfgDict[\"outdir\"],\"model_final.pth\")\ncfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = cfgDict[\"score_thresh_test\"]\npredictor = DefaultPredictor(cfg)\n\nd = datasetDicts[3]\nim = cv2.imread(d[\"file_name\"])\nif predictor.input_format == \"RGB\":\n    im = im[:, :, ::-1]\nheight, width = im.shape[:2]\nimage = torch.as_tensor(im.astype(\"float32\").transpose(2, 0, 1))\ninputs = [{\"image\": image, \"height\": height, \"width\": width}]\noutputs = predictor.model(inputs)\noutput = outputs[0]\n\nvisualizer = Visualizer(im,metadata=csfdMetadata, scale=1.5)\nout = visualizer.draw_instance_predictions(output[\"instances\"].to(\"cpu\"))\nImage.fromarray(out.get_image()[:, :, ::-1])","metadata":{"execution":{"iopub.status.busy":"2022-08-02T23:59:31.376234Z","iopub.status.idle":"2022-08-02T23:59:31.376941Z","shell.execute_reply.started":"2022-08-02T23:59:31.376686Z","shell.execute_reply":"2022-08-02T23:59:31.376711Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Reference\n\nhttps://www.kaggle.com/code/lhd0430/vinbigdata-chest-x-ray-abnormalities-detection","metadata":{}}]}