{"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":"code","source":"import os \nimport sys\nimport random\nimport math\nimport numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\nimport json\nimport pydicom\nfrom imgaug import augmenters as iaa\nfrom tqdm import tqdm\nimport pandas as pd \nimport glob\nimport keras\nimport tensorflow\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import precision_recall_fscore_support as prf\n","metadata":{"execution":{"iopub.status.busy":"2023-03-28T05:16:54.745483Z","iopub.execute_input":"2023-03-28T05:16:54.745778Z","iopub.status.idle":"2023-03-28T05:16:57.167087Z","shell.execute_reply.started":"2023-03-28T05:16:54.745726Z","shell.execute_reply":"2023-03-28T05:16:57.165818Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('keras:', keras.__version__)\nprint('tensorflow:',tensorflow.__version__)\n!python3 --version","metadata":{"execution":{"iopub.status.busy":"2023-03-28T05:16:59.608845Z","iopub.execute_input":"2023-03-28T05:16:59.609169Z","iopub.status.idle":"2023-03-28T05:17:00.578585Z","shell.execute_reply.started":"2023-03-28T05:16:59.609111Z","shell.execute_reply":"2023-03-28T05:17:00.577642Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import warnings \nwarnings.filterwarnings(\"ignore\")","metadata":{"execution":{"iopub.status.busy":"2023-03-28T05:17:03.424277Z","iopub.execute_input":"2023-03-28T05:17:03.424604Z","iopub.status.idle":"2023-03-28T05:17:03.428982Z","shell.execute_reply.started":"2023-03-28T05:17:03.424545Z","shell.execute_reply":"2023-03-28T05:17:03.428168Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"DATA_DIR = '/kaggle/input'\n\n# Directory to save logs and trained model\nROOT_DIR = '/kaggle/working'","metadata":{"execution":{"iopub.status.busy":"2023-03-28T05:17:06.036660Z","iopub.execute_input":"2023-03-28T05:17:06.036952Z","iopub.status.idle":"2023-03-28T05:17:06.041515Z","shell.execute_reply.started":"2023-03-28T05:17:06.036892Z","shell.execute_reply":"2023-03-28T05:17:06.040241Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!git clone https://www.github.com/matterport/Mask_RCNN.git\nos.chdir('Mask_RCNN')\n#!python setup.py -q install","metadata":{"execution":{"iopub.status.busy":"2023-03-28T05:17:08.061276Z","iopub.execute_input":"2023-03-28T05:17:08.061580Z","iopub.status.idle":"2023-03-28T05:17:17.205035Z","shell.execute_reply.started":"2023-03-28T05:17:08.061526Z","shell.execute_reply":"2023-03-28T05:17:17.204117Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Import Mask RCNN\nsys.path.append(os.path.join(ROOT_DIR, 'Mask_RCNN'))  # To find local version of the library\nfrom mrcnn.config import Config\nfrom mrcnn import utils\nimport mrcnn.model as modellib\nfrom mrcnn import visualize\nfrom mrcnn.model import log","metadata":{"execution":{"iopub.status.busy":"2023-03-28T05:17:20.106140Z","iopub.execute_input":"2023-03-28T05:17:20.106506Z","iopub.status.idle":"2023-03-28T05:17:20.147666Z","shell.execute_reply.started":"2023-03-28T05:17:20.106426Z","shell.execute_reply":"2023-03-28T05:17:20.146842Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_dicom_dir = os.path.join(DATA_DIR, 'rsna-pneumonia-detection-challenge/stage_2_train_images')\ntest_dicom_dir = os.path.join(DATA_DIR, 'rsna-pneumonia-detection-challenge/stage_2_test_images')","metadata":{"execution":{"iopub.status.busy":"2023-03-28T05:17:26.088856Z","iopub.execute_input":"2023-03-28T05:17:26.089164Z","iopub.status.idle":"2023-03-28T05:17:26.094197Z","shell.execute_reply.started":"2023-03-28T05:17:26.089111Z","shell.execute_reply":"2023-03-28T05:17:26.093272Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"### Download COCO pre-trained weights\n!wget --quiet https://github.com/matterport/Mask_RCNN/releases/download/v2.0/mask_rcnn_coco.h5\n!ls -lh mask_rcnn_coco.h5\n\nCOCO_WEIGHTS_PATH = \"/kaggle/input/mask-rcnn-coco/mask_rcnn_coco.h5\"","metadata":{"execution":{"iopub.status.busy":"2023-03-28T05:17:30.319965Z","iopub.execute_input":"2023-03-28T05:17:30.320264Z","iopub.status.idle":"2023-03-28T05:17:33.317032Z","shell.execute_reply.started":"2023-03-28T05:17:30.320211Z","shell.execute_reply":"2023-03-28T05:17:33.316039Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_dicom_fps(dicom_dir):\n    dicom_fps = glob.glob(dicom_dir+'/'+'*.dcm')\n    return list(set(dicom_fps))\n\ndef parse_dataset(dicom_dir, anns):\n    image_fps = get_dicom_fps(dicom_dir)\n    image_annotations = {fp: [] for fp in image_fps}\n    for index, row in anns.iterrows(): \n        fp = os.path.join(dicom_dir, row['patientId']+'.dcm')\n        image_annotations[fp].append(row)\n    return image_fps, image_annotations ","metadata":{"execution":{"iopub.status.busy":"2023-03-28T05:17:42.997338Z","iopub.execute_input":"2023-03-28T05:17:42.997689Z","iopub.status.idle":"2023-03-28T05:17:43.003451Z","shell.execute_reply.started":"2023-03-28T05:17:42.997630Z","shell.execute_reply":"2023-03-28T05:17:43.002648Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"hyper_paramters_comb={\n    'backbone':['resnet50'],\n    'learning_rate':[0.005],\n    'batch_size':[8],\n    'epochs':[10],\n    'det_min_conf':[0.9],\n    'det_nms_th':[0.8],\n    'rpn_nms_th':[0.7],\n    'steps_per_epoch':[135],\n    'layers': ['heads']\n}\n\nhpc=pd.DataFrame(hyper_paramters_comb)\n\nhpc['learning_rate'] = hpc['learning_rate'].astype(np.float32)\nhpc['det_min_conf'] = hpc['det_min_conf'].astype(np.float32)\nhpc['det_nms_th'] = hpc['det_nms_th'].astype(np.float32)\nhpc['rpn_nms_th'] = hpc['rpn_nms_th'].astype(np.float32)\n\nhpc.head()","metadata":{"execution":{"iopub.status.busy":"2023-03-28T05:17:46.539983Z","iopub.execute_input":"2023-03-28T05:17:46.540283Z","iopub.status.idle":"2023-03-28T05:17:46.591802Z","shell.execute_reply.started":"2023-03-28T05:17:46.540228Z","shell.execute_reply":"2023-03-28T05:17:46.591043Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# training dataset\nanns = pd.read_csv(os.path.join(DATA_DIR, 'rsna-pneumonia-detection-challenge/stage_2_train_labels.csv'))\nanns.head()","metadata":{"execution":{"iopub.status.busy":"2023-03-28T05:17:50.357238Z","iopub.execute_input":"2023-03-28T05:17:50.357566Z","iopub.status.idle":"2023-03-28T05:17:50.443635Z","shell.execute_reply.started":"2023-03-28T05:17:50.357504Z","shell.execute_reply":"2023-03-28T05:17:50.442587Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image_fps, image_annotations = parse_dataset(train_dicom_dir, anns=anns)","metadata":{"execution":{"iopub.status.busy":"2023-03-28T05:17:54.228510Z","iopub.execute_input":"2023-03-28T05:17:54.228815Z","iopub.status.idle":"2023-03-28T05:17:57.228456Z","shell.execute_reply.started":"2023-03-28T05:17:54.228765Z","shell.execute_reply":"2023-03-28T05:17:57.227528Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ds = pydicom.read_file(image_fps[0]) # read dicom image from filepath \nimage = ds.pixel_array # get image array","metadata":{"execution":{"iopub.status.busy":"2023-03-28T05:18:02.966707Z","iopub.execute_input":"2023-03-28T05:18:02.967021Z","iopub.status.idle":"2023-03-28T05:18:02.982586Z","shell.execute_reply.started":"2023-03-28T05:18:02.966963Z","shell.execute_reply":"2023-03-28T05:18:02.981840Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Original DICOM image size: 1024 x 1024\nORIG_SIZE = 1024","metadata":{"execution":{"iopub.status.busy":"2023-03-28T05:18:07.675056Z","iopub.execute_input":"2023-03-28T05:18:07.675348Z","iopub.status.idle":"2023-03-28T05:18:07.680570Z","shell.execute_reply.started":"2023-03-28T05:18:07.675293Z","shell.execute_reply":"2023-03-28T05:18:07.678640Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Split the data into training and validation datasets that exctly macthes the dataset used for other models in the project**","metadata":{}},{"cell_type":"code","source":"def dataset_model(image_names):\n    org_train, org_val = train_test_split(anns, test_size=0.30, random_state=32)\n    \n    #  taking subset of train and validation dataset\n    org_train_1=org_train[org_train.Target==1]\n    org_train_0=org_train[org_train.Target==0]\n    image_fps_train=org_train_1.patientId[:1500].tolist() + org_train_0.patientId[:500].tolist()\n    image_fps_train=[train_dicom_dir+'/'+x+'.dcm' for x in image_fps_train]\n\n    org_val_1=org_val[org_val.Target==1]\n    org_val_0=org_val[org_val.Target==0]\n    image_fps_val=org_val_1.patientId[:350].tolist() + org_val_0.patientId[:150].tolist()\n    image_fps_val=[train_dicom_dir+'/'+x+'.dcm' for x in image_fps_val]\n    \n    image_fps_test=org_val_1.patientId[1500:1800].tolist() + org_val_0.patientId[500:700].tolist()\n    image_fps_test=[train_dicom_dir+'/'+x+'.dcm' for x in image_fps_test]\n    print(len(image_fps_train), len(image_fps_val), len(image_fps_test))\n\n    return image_fps_train, image_fps_val, image_fps_test\n","metadata":{"execution":{"iopub.status.busy":"2023-03-28T05:18:13.206472Z","iopub.execute_input":"2023-03-28T05:18:13.206799Z","iopub.status.idle":"2023-03-28T05:18:13.215856Z","shell.execute_reply.started":"2023-03-28T05:18:13.206740Z","shell.execute_reply":"2023-03-28T05:18:13.212746Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image_fps_train, image_fps_val, image_fps_test=dataset_model(image_fps)","metadata":{"execution":{"iopub.status.busy":"2023-03-28T05:18:15.298917Z","iopub.execute_input":"2023-03-28T05:18:15.299207Z","iopub.status.idle":"2023-03-28T05:18:15.318865Z","shell.execute_reply.started":"2023-03-28T05:18:15.299155Z","shell.execute_reply":"2023-03-28T05:18:15.318021Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"len(image_fps_train), len(image_fps_val), len(image_fps_test)","metadata":{"execution":{"iopub.status.busy":"2023-03-28T05:19:16.540933Z","iopub.execute_input":"2023-03-28T05:19:16.541245Z","iopub.status.idle":"2023-03-28T05:19:16.546622Z","shell.execute_reply.started":"2023-03-28T05:19:16.541192Z","shell.execute_reply":"2023-03-28T05:19:16.545449Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class DetectorDataset(utils.Dataset):\n    \"\"\"Dataset class for training pneumonia detection on the RSNA pneumonia dataset.\n    \"\"\"\n\n    def __init__(self, image_fps, image_annotations, orig_height, orig_width):\n        super().__init__(self)\n        \n        # Add classes\n        self.add_class('pneumonia', 1, 'Lung Opacity')\n        \n        # add images \n        for i, fp in enumerate(image_fps):\n            annotations = image_annotations[fp]\n            self.add_image('pneumonia', image_id=i, path=fp, \n                           annotations=annotations, orig_height=orig_height, orig_width=orig_width)\n            \n    def image_reference(self, image_id):\n        info = self.image_info[image_id]\n        return info['path']\n\n    def load_image(self, image_id):\n        info = self.image_info[image_id]\n        fp = info['path']\n        ds = pydicom.read_file(fp)\n        image = ds.pixel_array\n        # If grayscale. Convert to RGB for consistency.\n        if len(image.shape) != 3 or image.shape[2] != 3:\n            image = np.stack((image,) * 3, -1)\n        return image\n\n    def load_mask(self, image_id):\n        info = self.image_info[image_id]\n        annotations = info['annotations']\n        count = len(annotations)\n        if count == 0:\n            mask = np.zeros((info['orig_height'], info['orig_width'], 1), dtype=np.uint8)\n            class_ids = np.zeros((1,), dtype=np.int32)\n        else:\n            mask = np.zeros((info['orig_height'], info['orig_width'], count), dtype=np.uint8)\n            class_ids = np.zeros((count,), dtype=np.int32)\n            for i, a in enumerate(annotations):\n                if a['Target'] == 1:\n                    x = int(a['x'])\n                    y = int(a['y'])\n                    w = int(a['width'])\n                    h = int(a['height'])\n                    mask_instance = mask[:, :, i].copy()\n                    cv2.rectangle(mask_instance, (x, y), (x+w, y+h), 255, -1)\n                    mask[:, :, i] = mask_instance\n                    class_ids[i] = 1\n        return mask.astype(np.bool), class_ids.astype(np.int32)","metadata":{"execution":{"iopub.status.busy":"2023-03-28T05:19:25.134011Z","iopub.execute_input":"2023-03-28T05:19:25.134644Z","iopub.status.idle":"2023-03-28T05:19:25.157962Z","shell.execute_reply.started":"2023-03-28T05:19:25.134572Z","shell.execute_reply":"2023-03-28T05:19:25.157108Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# prepare the training dataset\ndataset_train = DetectorDataset(image_fps_train, image_annotations, ORIG_SIZE, ORIG_SIZE)\ndataset_train.prepare()","metadata":{"execution":{"iopub.status.busy":"2023-03-28T05:19:30.066113Z","iopub.execute_input":"2023-03-28T05:19:30.066406Z","iopub.status.idle":"2023-03-28T05:19:30.076311Z","shell.execute_reply.started":"2023-03-28T05:19:30.066353Z","shell.execute_reply":"2023-03-28T05:19:30.075180Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# prepare the validation dataset\ndataset_val = DetectorDataset(image_fps_val, image_annotations, ORIG_SIZE, ORIG_SIZE)\ndataset_val.prepare()","metadata":{"execution":{"iopub.status.busy":"2023-03-28T05:19:34.065556Z","iopub.execute_input":"2023-03-28T05:19:34.065873Z","iopub.status.idle":"2023-03-28T05:19:34.072393Z","shell.execute_reply.started":"2023-03-28T05:19:34.065821Z","shell.execute_reply":"2023-03-28T05:19:34.071614Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Display a random image with bounding boxes**","metadata":{}},{"cell_type":"code","source":"# Load and display a random sample and their bounding boxes\n\nclass_ids = [0]\nwhile class_ids[0] == 0:  ## look for a mask\n    image_id = random.choice(dataset_train.image_ids)\n    image_fp = dataset_train.image_reference(image_id)\n    image = dataset_train.load_image(image_id)\n    mask, class_ids = dataset_train.load_mask(image_id)\n\nprint(image.shape)\n\nplt.figure(figsize=(10, 10))\nplt.subplot(1, 2, 1)\nplt.imshow(image)\nplt.axis('off')\n\nplt.subplot(1, 2, 2)\nmasked = np.zeros(image.shape[:2])\nfor i in range(mask.shape[2]):\n    masked += image[:, :, 0] * mask[:, :, i]\nplt.imshow(masked, cmap='gray')\nplt.axis('off')\n\n\nprint(image_fp)\nprint(class_ids)","metadata":{"execution":{"iopub.status.busy":"2023-03-28T05:19:50.494834Z","iopub.execute_input":"2023-03-28T05:19:50.495144Z","iopub.status.idle":"2023-03-28T05:19:50.926839Z","shell.execute_reply.started":"2023-03-28T05:19:50.495092Z","shell.execute_reply":"2023-03-28T05:19:50.926055Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Image augmentation (light but constant)\naugmentation = iaa.Sequential([\n    iaa.OneOf([ ## geometric transform\n        iaa.Affine(\n            scale={\"x\": (0.98, 1.02), \"y\": (0.98, 1.04)},\n            translate_percent={\"x\": (-0.02, 0.02), \"y\": (-0.04, 0.04)},\n            rotate=(-2, 2),\n            shear=(-1, 1),\n        ),\n        iaa.PiecewiseAffine(scale=(0.001, 0.025)),\n    ]),\n    iaa.OneOf([ ## brightness or contrast\n        iaa.Multiply((0.9, 1.1)),\n        iaa.ContrastNormalization((0.9, 1.1)),\n    ]),\n    iaa.OneOf([ ## blur or sharpen\n        iaa.GaussianBlur(sigma=(0.0, 0.1)),\n        iaa.Sharpen(alpha=(0.0, 0.1)),\n    ]),\n])\n\n# test on the same image as above\nimggrid = augmentation.draw_grid(image[:, :, 0], cols=5, rows=2)\nplt.figure(figsize=(30, 12))\n_ = plt.imshow(imggrid[:, :, 0], cmap='gray')","metadata":{"execution":{"iopub.status.busy":"2023-03-28T05:19:56.777729Z","iopub.execute_input":"2023-03-28T05:19:56.778041Z","iopub.status.idle":"2023-03-28T05:20:02.726990Z","shell.execute_reply.started":"2023-03-28T05:19:56.777990Z","shell.execute_reply":"2023-03-28T05:20:02.725465Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# The following parameters have been selected to reduce running time for demonstration purposes \n# These are not optimal \n\nclass DetectorConfig(Config):\n    \"\"\"Configuration for training pneumonia detection on the RSNA pneumonia dataset.\n    Overrides values in the base Config class.\n    \"\"\"\n    \n    # Give the configuration a recognizable name  \n    NAME = 'pneumonia'\n    \n    # Train on 1 GPU and 8 images per GPU. We can put multiple images on each\n    # GPU because the images are small. Batch size is 8 (GPUs * images/GPU).\n    GPU_COUNT = 1\n    IMAGES_PER_GPU = 8\n    \n    BACKBONE = hpc.iloc[0]['backbone']\n    BATCH_SIZE=hpc.iloc[0]['batch_size']\n    NUM_CLASSES = 2  # background + 1 pneumonia classes\n    \n    IMAGE_MIN_DIM = 256\n    IMAGE_MAX_DIM = 256\n    RPN_ANCHOR_SCALES = (32, 64, 128, 256)\n    TRAIN_ROIS_PER_IMAGE = 32\n    MAX_GT_INSTANCES = 3\n    DETECTION_MAX_INSTANCES = 3\n    DETECTION_MIN_CONFIDENCE = hpc.iloc[0]['det_min_conf']\n    DETECTION_NMS_THRESHOLD = hpc.iloc[0]['det_nms_th']\n    RPN_NMS_THRESHOLD = hpc.iloc[0]['rpn_nms_th']\n    STEPS_PER_EPOCH = hpc.iloc[0]['steps_per_epoch']\n","metadata":{"execution":{"iopub.status.busy":"2023-03-28T05:20:21.962573Z","iopub.execute_input":"2023-03-28T05:20:21.962877Z","iopub.status.idle":"2023-03-28T05:20:21.970515Z","shell.execute_reply.started":"2023-03-28T05:20:21.962828Z","shell.execute_reply":"2023-03-28T05:20:21.969592Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"config = DetectorConfig()\nconfig.display()","metadata":{"execution":{"iopub.status.busy":"2023-03-28T05:20:24.329253Z","iopub.execute_input":"2023-03-28T05:20:24.329603Z","iopub.status.idle":"2023-03-28T05:20:24.345028Z","shell.execute_reply.started":"2023-03-28T05:20:24.329540Z","shell.execute_reply":"2023-03-28T05:20:24.344145Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = modellib.MaskRCNN(mode='training', config=config, model_dir=ROOT_DIR)\n\n# Exclude the last layers because they require a matching number of classes\nmodel.load_weights(COCO_WEIGHTS_PATH, by_name=True, exclude=[\n    \"mrcnn_class_logits\", \"mrcnn_bbox_fc\", \"mrcnn_bbox\", \"mrcnn_mask\"])","metadata":{"execution":{"iopub.status.busy":"2023-03-28T05:21:02.016403Z","iopub.execute_input":"2023-03-28T05:21:02.016736Z","iopub.status.idle":"2023-03-28T05:21:15.693939Z","shell.execute_reply.started":"2023-03-28T05:21:02.016680Z","shell.execute_reply":"2023-03-28T05:21:15.693168Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\ncheckpoint_path = os.path.join(ROOT_DIR, \"mask_rcnn_{}_*epoch*.h5\".format(config.NAME.lower()))\ncheckpoint_path = checkpoint_path.replace(\"*epoch*\", \"{epoch:04d}\")\ncallbacks = [keras.callbacks.ModelCheckpoint(checkpoint_path,verbose=1, save_weights_only=True,period=1)]\n\nmodel.train(dataset_train, dataset_val, \n            learning_rate=hpc.iloc[0]['learning_rate'], \n            epochs=hpc.iloc[0]['epochs'], \n            custom_callbacks=callbacks,\n            layers=hpc.iloc[0]['layers'],\n            augmentation=augmentation)\n\nhistory = model.keras_model.history.history","metadata":{"execution":{"iopub.status.busy":"2023-03-28T05:21:23.220586Z","iopub.execute_input":"2023-03-28T05:21:23.220902Z","iopub.status.idle":"2023-03-28T06:14:06.915862Z","shell.execute_reply.started":"2023-03-28T05:21:23.220835Z","shell.execute_reply":"2023-03-28T06:14:06.912819Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"epochs = range(1,len(next(iter(history.values())))+1)\npd.DataFrame(history, index=epochs)","metadata":{"execution":{"iopub.status.busy":"2023-03-28T06:51:27.558716Z","iopub.execute_input":"2023-03-28T06:51:27.559169Z","iopub.status.idle":"2023-03-28T06:51:27.595720Z","shell.execute_reply.started":"2023-03-28T06:51:27.559073Z","shell.execute_reply":"2023-03-28T06:51:27.594943Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(10,10))\nplt.subplot(111)\nplt.plot(epochs, history[\"loss\"], label=\"Train loss\")\nplt.plot(epochs, history[\"val_loss\"], label=\"Valid loss\")\nplt.legend()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-03-28T06:51:29.728285Z","iopub.execute_input":"2023-03-28T06:51:29.728585Z","iopub.status.idle":"2023-03-28T06:51:30.114148Z","shell.execute_reply.started":"2023-03-28T06:51:29.728532Z","shell.execute_reply":"2023-03-28T06:51:30.113407Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(10,10))\nplt.subplot(111)\nplt.plot(epochs, history[\"mrcnn_class_loss\"], label=\"Train class ce\")\nplt.plot(epochs, history[\"val_mrcnn_class_loss\"], label=\"Valid class ce\")\nplt.legend()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-03-28T06:51:39.727964Z","iopub.execute_input":"2023-03-28T06:51:39.728271Z","iopub.status.idle":"2023-03-28T06:51:40.103257Z","shell.execute_reply.started":"2023-03-28T06:51:39.728217Z","shell.execute_reply":"2023-03-28T06:51:40.102496Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(10,10))\nplt.subplot(111)\nplt.plot(epochs, history[\"mrcnn_bbox_loss\"], label=\"Train box loss\")\nplt.plot(epochs, history[\"val_mrcnn_bbox_loss\"], label=\"Valid box loss\")\nplt.legend()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-03-28T06:51:46.719012Z","iopub.execute_input":"2023-03-28T06:51:46.719300Z","iopub.status.idle":"2023-03-28T06:51:47.145201Z","shell.execute_reply.started":"2023-03-28T06:51:46.719248Z","shell.execute_reply":"2023-03-28T06:51:47.144263Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"best_epoch = np.argmin(history[\"val_loss\"])\nprint(\"Best Epoch:\", best_epoch + 1, history[\"val_loss\"][best_epoch])","metadata":{"execution":{"iopub.status.busy":"2023-03-28T06:51:52.314882Z","iopub.execute_input":"2023-03-28T06:51:52.315171Z","iopub.status.idle":"2023-03-28T06:51:52.320353Z","shell.execute_reply.started":"2023-03-28T06:51:52.315119Z","shell.execute_reply":"2023-03-28T06:51:52.319485Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x=filter(lambda f : (f.startswith('mask_rcnn_pneumonia') and ((4-len(str(best_epoch+1)))*str(0)+str(best_epoch+1)) in f), os.listdir(model.model_dir))\nmodel_path=model.model_dir+'/'+list(x)[0]\nprint('Found model at {}'.format(model_path))","metadata":{"execution":{"iopub.status.busy":"2023-03-28T06:51:55.668963Z","iopub.execute_input":"2023-03-28T06:51:55.669265Z","iopub.status.idle":"2023-03-28T06:51:55.675780Z","shell.execute_reply.started":"2023-03-28T06:51:55.669208Z","shell.execute_reply":"2023-03-28T06:51:55.674887Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class InferenceConfig(DetectorConfig):\n    GPU_COUNT = 1\n    IMAGES_PER_GPU = 1\n\ninference_config = InferenceConfig()\n\n# Recreate the model in inference mode\nmodel = modellib.MaskRCNN(mode='inference', config=inference_config, model_dir=ROOT_DIR)\n\n# Load trained weights (fill in path to trained weights here)\nassert model_path != \"\", \"Provide path to trained weights\"\nprint(\"Loading weights from \", model_path)\nmodel.load_weights(model_path, by_name=True)","metadata":{"execution":{"iopub.status.busy":"2023-03-28T06:51:58.659081Z","iopub.execute_input":"2023-03-28T06:51:58.659380Z","iopub.status.idle":"2023-03-28T06:52:05.672801Z","shell.execute_reply.started":"2023-03-28T06:51:58.659320Z","shell.execute_reply":"2023-03-28T06:52:05.671954Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# set color for class\ndef get_colors_for_class_ids(class_ids):\n    colors = []\n    for class_id in class_ids:\n        if class_id == 1:\n            colors.append((.941, .204, .204))\n    return colors","metadata":{"execution":{"iopub.status.busy":"2023-03-28T06:52:12.922019Z","iopub.execute_input":"2023-03-28T06:52:12.922315Z","iopub.status.idle":"2023-03-28T06:52:12.926552Z","shell.execute_reply.started":"2023-03-28T06:52:12.922259Z","shell.execute_reply":"2023-03-28T06:52:12.925677Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**How does the predicted box compared to the expected value? Let's use the validation dataset to check.**","metadata":{}},{"cell_type":"code","source":"# prepare the validation dataset\ndataset_test = DetectorDataset(image_fps_test, image_annotations, ORIG_SIZE, ORIG_SIZE)\ndataset_test.prepare()","metadata":{"execution":{"iopub.status.busy":"2023-03-28T06:52:15.051068Z","iopub.execute_input":"2023-03-28T06:52:15.051379Z","iopub.status.idle":"2023-03-28T06:52:15.057775Z","shell.execute_reply.started":"2023-03-28T06:52:15.051316Z","shell.execute_reply":"2023-03-28T06:52:15.056672Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"images=dataset_test.image_ids\n\nytrue=[]\nypred=[]\n\nfor i in range(len(images)):\n        original_image,_, _, gt_bbox, gt_mask =\\\n            modellib.load_image_gt(dataset_test, inference_config, images[i], use_mini_mask=False)\n        ytrue.append(gt_bbox)\n        results=model.detect([original_image])\n        ypred.append(results[0]['rois'])","metadata":{"execution":{"iopub.status.busy":"2023-03-28T06:52:17.962636Z","iopub.execute_input":"2023-03-28T06:52:17.962933Z","iopub.status.idle":"2023-03-28T06:53:42.578609Z","shell.execute_reply.started":"2023-03-28T06:52:17.962872Z","shell.execute_reply":"2023-03-28T06:53:42.577740Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Show few example of ground truth vs. predictions on the test dataset \ndataset = dataset_test\nfig = plt.figure(figsize=(10, 30))\nimg_array=[]\nfor i in range(6):\n\n    image_id = random.choice(dataset.image_ids)\n    \n    original_image, image_meta, gt_class_id, gt_bbox, gt_mask =\\\n        modellib.load_image_gt(dataset_val, inference_config, \n                               image_id, use_mini_mask=False)\n    img_array.append(original_image)\n    print(original_image.shape)\n    plt.subplot(6, 2, 2*i + 1)\n    visualize.display_instances(original_image, gt_bbox, gt_mask, gt_class_id, \n                                dataset.class_names,\n                                colors=get_colors_for_class_ids(gt_class_id), ax=fig.axes[-1])\n    \n    plt.subplot(6, 2, 2*i + 2)\n    results = model.detect([original_image]) #, verbose=1)\n    r = results[0]\n    visualize.display_instances(original_image, r['rois'], r['masks'], r['class_ids'], \n                                dataset.class_names, r['scores'], \n                                colors=get_colors_for_class_ids(r['class_ids']), ax=fig.axes[-1])\n","metadata":{"execution":{"iopub.status.busy":"2023-03-28T06:53:42.579829Z","iopub.execute_input":"2023-03-28T06:53:42.580111Z","iopub.status.idle":"2023-03-28T06:53:45.427352Z","shell.execute_reply.started":"2023-03-28T06:53:42.580066Z","shell.execute_reply":"2023-03-28T06:53:45.426692Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def loadmasks(bboxes):\n    mask = np.zeros((bboxes.shape[0], ORIG_SIZE, ORIG_SIZE))\n    for i in range(bboxes.shape[0]):\n        if bboxes[i]==[]:\n            continue\n        else:\n            for bbox in bboxes[i]:\n                x, y, w, h = bbox\n                x1=math.floor(x)\n                y1=math.floor(y)\n                x2=math.ceil(x+w)\n                y2=math.ceil(y+h)\n                mask[i, y1:y2,x1:x2] = 1\n\n    return mask","metadata":{"execution":{"iopub.status.busy":"2023-03-28T07:03:28.541861Z","iopub.execute_input":"2023-03-28T07:03:28.542177Z","iopub.status.idle":"2023-03-28T07:03:28.547667Z","shell.execute_reply.started":"2023-03-28T07:03:28.542122Z","shell.execute_reply":"2023-03-28T07:03:28.546974Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def npmean_iou(bbox1, bbox2):\n    mask1=loadmasks(np.array(bbox1))\n    mask2=loadmasks(np.array(bbox2))\n    union=np.count_nonzero(mask1, 1).astype(np.float32) + np.count_nonzero(mask2, 1).astype(np.float32)\n    intersection = np.count_nonzero(np.logical_and(mask1, mask2), 1).astype(np.float32)\n    smooth = np.ones(intersection.shape)\n    iou = np.mean((intersection+smooth)/(union-intersection+smooth))\n    return iou\n\niou=npmean_iou(ytrue, ypred)\niou","metadata":{"execution":{"iopub.status.busy":"2023-03-28T07:03:30.494721Z","iopub.execute_input":"2023-03-28T07:03:30.495018Z","iopub.status.idle":"2023-03-28T07:03:37.329917Z","shell.execute_reply.started":"2023-03-28T07:03:30.494959Z","shell.execute_reply":"2023-03-28T07:03:37.328881Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"prec, rec, f1s, _ = prf([1 if np.sum(x)>1 else 0 for x in ytrue], [1 if np.sum(x)>1 else 0 for x in ypred], average='binary')\nprec, rec, f1s","metadata":{"execution":{"iopub.status.busy":"2023-03-28T07:03:42.484731Z","iopub.execute_input":"2023-03-28T07:03:42.485136Z","iopub.status.idle":"2023-03-28T07:03:42.498608Z","shell.execute_reply.started":"2023-03-28T07:03:42.485061Z","shell.execute_reply":"2023-03-28T07:03:42.497696Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"hpc.head()","metadata":{"execution":{"iopub.status.busy":"2023-03-28T07:03:44.191764Z","iopub.execute_input":"2023-03-28T07:03:44.192070Z","iopub.status.idle":"2023-03-28T07:03:44.217161Z","shell.execute_reply.started":"2023-03-28T07:03:44.192017Z","shell.execute_reply":"2023-03-28T07:03:44.216231Z"},"trusted":true},"execution_count":null,"outputs":[]}]}