{"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":"2022-07-04T07:27:40.040092Z","iopub.execute_input":"2022-07-04T07:27:40.040663Z","iopub.status.idle":"2022-07-04T07:27:42.275546Z","shell.execute_reply.started":"2022-07-04T07:27:40.040408Z","shell.execute_reply":"2022-07-04T07:27:42.274541Z"},"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":"2022-07-04T07:27:42.276848Z","iopub.execute_input":"2022-07-04T07:27:42.277266Z","iopub.status.idle":"2022-07-04T07:27:43.100075Z","shell.execute_reply.started":"2022-07-04T07:27:42.277217Z","shell.execute_reply":"2022-07-04T07:27:43.098798Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import warnings \nwarnings.filterwarnings(\"ignore\")","metadata":{"execution":{"iopub.status.busy":"2022-07-04T07:27:43.106077Z","iopub.execute_input":"2022-07-04T07:27:43.106657Z","iopub.status.idle":"2022-07-04T07:27:43.113414Z","shell.execute_reply.started":"2022-07-04T07:27:43.106353Z","shell.execute_reply":"2022-07-04T07:27:43.112529Z"},"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":"2022-07-04T07:27:43.117551Z","iopub.execute_input":"2022-07-04T07:27:43.118038Z","iopub.status.idle":"2022-07-04T07:27:43.122489Z","shell.execute_reply.started":"2022-07-04T07:27:43.117821Z","shell.execute_reply":"2022-07-04T07:27:43.121256Z"},"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":"2022-07-04T07:27:43.124109Z","iopub.execute_input":"2022-07-04T07:27:43.126639Z","iopub.status.idle":"2022-07-04T07:27:44.180153Z","shell.execute_reply.started":"2022-07-04T07:27:43.124386Z","shell.execute_reply":"2022-07-04T07:27:44.179191Z"},"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":"2022-07-04T07:27:44.181826Z","iopub.execute_input":"2022-07-04T07:27:44.182109Z","iopub.status.idle":"2022-07-04T07:27:44.329662Z","shell.execute_reply.started":"2022-07-04T07:27:44.182066Z","shell.execute_reply":"2022-07-04T07:27:44.328935Z"},"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":"2022-07-04T07:27:44.335243Z","iopub.execute_input":"2022-07-04T07:27:44.338338Z","iopub.status.idle":"2022-07-04T07:27:44.345365Z","shell.execute_reply.started":"2022-07-04T07:27:44.338284Z","shell.execute_reply":"2022-07-04T07:27:44.344626Z"},"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":"2022-07-04T07:27:44.349355Z","iopub.execute_input":"2022-07-04T07:27:44.35137Z","iopub.status.idle":"2022-07-04T07:27:53.966339Z","shell.execute_reply.started":"2022-07-04T07:27:44.351315Z","shell.execute_reply":"2022-07-04T07:27:53.96536Z"},"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":"2022-07-04T07:27:53.968107Z","iopub.execute_input":"2022-07-04T07:27:53.9684Z","iopub.status.idle":"2022-07-04T07:27:53.974662Z","shell.execute_reply.started":"2022-07-04T07:27:53.968349Z","shell.execute_reply":"2022-07-04T07:27:53.973943Z"},"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":"2022-07-04T07:27:53.976019Z","iopub.execute_input":"2022-07-04T07:27:53.97661Z","iopub.status.idle":"2022-07-04T07:27:54.02337Z","shell.execute_reply.started":"2022-07-04T07:27:53.976559Z","shell.execute_reply":"2022-07-04T07:27:54.022621Z"},"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":"2022-07-04T07:27:54.024761Z","iopub.execute_input":"2022-07-04T07:27:54.025223Z","iopub.status.idle":"2022-07-04T07:27:54.099369Z","shell.execute_reply.started":"2022-07-04T07:27:54.025171Z","shell.execute_reply":"2022-07-04T07:27:54.098607Z"},"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":"2022-07-04T07:27:54.102252Z","iopub.execute_input":"2022-07-04T07:27:54.102477Z","iopub.status.idle":"2022-07-04T07:27:57.08348Z","shell.execute_reply.started":"2022-07-04T07:27:54.102432Z","shell.execute_reply":"2022-07-04T07:27:57.08272Z"},"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":"2022-07-04T07:27:57.084745Z","iopub.execute_input":"2022-07-04T07:27:57.085046Z","iopub.status.idle":"2022-07-04T07:27:57.237954Z","shell.execute_reply.started":"2022-07-04T07:27:57.084976Z","shell.execute_reply":"2022-07-04T07:27:57.237241Z"},"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":"2022-07-04T07:27:57.239224Z","iopub.execute_input":"2022-07-04T07:27:57.239763Z","iopub.status.idle":"2022-07-04T07:27:57.244163Z","shell.execute_reply.started":"2022-07-04T07:27:57.239696Z","shell.execute_reply":"2022-07-04T07:27:57.24329Z"},"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":"2022-07-04T07:27:57.245664Z","iopub.execute_input":"2022-07-04T07:27:57.246191Z","iopub.status.idle":"2022-07-04T07:27:57.257448Z","shell.execute_reply.started":"2022-07-04T07:27:57.24603Z","shell.execute_reply":"2022-07-04T07:27:57.256642Z"},"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":"2022-07-04T07:27:57.259123Z","iopub.execute_input":"2022-07-04T07:27:57.259775Z","iopub.status.idle":"2022-07-04T07:27:57.285468Z","shell.execute_reply.started":"2022-07-04T07:27:57.259707Z","shell.execute_reply":"2022-07-04T07:27:57.284629Z"},"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":"2022-07-04T07:27:57.292531Z","iopub.execute_input":"2022-07-04T07:27:57.293058Z","iopub.status.idle":"2022-07-04T07:27:57.302728Z","shell.execute_reply.started":"2022-07-04T07:27:57.293007Z","shell.execute_reply":"2022-07-04T07:27:57.30181Z"},"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":"2022-07-04T07:27:57.304228Z","iopub.execute_input":"2022-07-04T07:27:57.304827Z","iopub.status.idle":"2022-07-04T07:27:57.319263Z","shell.execute_reply.started":"2022-07-04T07:27:57.304776Z","shell.execute_reply":"2022-07-04T07:27:57.318229Z"},"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":"2022-07-04T07:27:57.320578Z","iopub.execute_input":"2022-07-04T07:27:57.321005Z","iopub.status.idle":"2022-07-04T07:27:57.337547Z","shell.execute_reply.started":"2022-07-04T07:27:57.320801Z","shell.execute_reply":"2022-07-04T07:27:57.336798Z"},"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":"2022-07-04T07:27:57.341274Z","iopub.execute_input":"2022-07-04T07:27:57.341503Z","iopub.status.idle":"2022-07-04T07:27:57.350312Z","shell.execute_reply.started":"2022-07-04T07:27:57.341452Z","shell.execute_reply":"2022-07-04T07:27:57.349368Z"},"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":"2022-07-04T07:27:57.351558Z","iopub.execute_input":"2022-07-04T07:27:57.352024Z","iopub.status.idle":"2022-07-04T07:27:57.783058Z","shell.execute_reply.started":"2022-07-04T07:27:57.351974Z","shell.execute_reply":"2022-07-04T07:27:57.780188Z"},"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":"2022-07-04T07:27:57.784129Z","iopub.execute_input":"2022-07-04T07:27:57.784465Z","iopub.status.idle":"2022-07-04T07:28:03.406608Z","shell.execute_reply.started":"2022-07-04T07:27:57.784409Z","shell.execute_reply":"2022-07-04T07:28:03.405947Z"},"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":"2022-07-04T07:28:03.407664Z","iopub.execute_input":"2022-07-04T07:28:03.408033Z","iopub.status.idle":"2022-07-04T07:28:03.419136Z","shell.execute_reply.started":"2022-07-04T07:28:03.407989Z","shell.execute_reply":"2022-07-04T07:28:03.418415Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"config = DetectorConfig()\nconfig.display()","metadata":{"execution":{"iopub.status.busy":"2022-07-04T07:28:03.420323Z","iopub.execute_input":"2022-07-04T07:28:03.420857Z","iopub.status.idle":"2022-07-04T07:28:03.442689Z","shell.execute_reply.started":"2022-07-04T07:28:03.420798Z","shell.execute_reply":"2022-07-04T07:28:03.442024Z"},"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":"2022-07-04T07:28:03.443762Z","iopub.execute_input":"2022-07-04T07:28:03.444173Z","iopub.status.idle":"2022-07-04T07:28:15.890788Z","shell.execute_reply.started":"2022-07-04T07:28:03.444126Z","shell.execute_reply":"2022-07-04T07:28:15.889869Z"},"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":"2022-07-04T07:28:15.896265Z","iopub.execute_input":"2022-07-04T07:28:15.899166Z","iopub.status.idle":"2022-07-04T08:19:18.268628Z","shell.execute_reply.started":"2022-07-04T07:28:15.899107Z","shell.execute_reply":"2022-07-04T08:19:18.262335Z"},"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":"2022-07-04T08:19:18.273532Z","iopub.execute_input":"2022-07-04T08:19:18.281068Z","iopub.status.idle":"2022-07-04T08:19:18.620045Z","shell.execute_reply.started":"2022-07-04T08:19:18.273841Z","shell.execute_reply":"2022-07-04T08:19:18.616362Z"},"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":"2022-07-04T08:19:18.623567Z","iopub.execute_input":"2022-07-04T08:19:18.624246Z","iopub.status.idle":"2022-07-04T08:19:20.592547Z","shell.execute_reply.started":"2022-07-04T08:19:18.623819Z","shell.execute_reply":"2022-07-04T08:19:20.589839Z"},"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":"2022-07-04T08:19:20.599611Z","iopub.execute_input":"2022-07-04T08:19:20.606209Z","iopub.status.idle":"2022-07-04T08:19:22.252375Z","shell.execute_reply.started":"2022-07-04T08:19:20.606137Z","shell.execute_reply":"2022-07-04T08:19:22.243619Z"},"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":"2022-07-04T08:19:22.258998Z","iopub.execute_input":"2022-07-04T08:19:22.265219Z","iopub.status.idle":"2022-07-04T08:19:24.156139Z","shell.execute_reply.started":"2022-07-04T08:19:22.259334Z","shell.execute_reply":"2022-07-04T08:19:24.154267Z"},"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":"2022-07-04T08:19:24.16544Z","iopub.execute_input":"2022-07-04T08:19:24.168593Z","iopub.status.idle":"2022-07-04T08:19:24.183458Z","shell.execute_reply.started":"2022-07-04T08:19:24.168539Z","shell.execute_reply":"2022-07-04T08:19:24.181318Z"},"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":"2022-07-04T08:19:24.189537Z","iopub.execute_input":"2022-07-04T08:19:24.190944Z","iopub.status.idle":"2022-07-04T08:19:24.211156Z","shell.execute_reply.started":"2022-07-04T08:19:24.190893Z","shell.execute_reply":"2022-07-04T08:19:24.209911Z"},"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":"2022-07-04T08:19:24.248697Z","iopub.execute_input":"2022-07-04T08:19:24.267017Z","iopub.status.idle":"2022-07-04T08:20:11.767766Z","shell.execute_reply.started":"2022-07-04T08:19:24.26696Z","shell.execute_reply":"2022-07-04T08:20:11.766672Z"},"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":"2022-07-04T08:20:11.774052Z","iopub.execute_input":"2022-07-04T08:20:11.778339Z","iopub.status.idle":"2022-07-04T08:20:11.790233Z","shell.execute_reply.started":"2022-07-04T08:20:11.778272Z","shell.execute_reply":"2022-07-04T08:20:11.788743Z"},"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":"2022-07-04T08:20:11.797872Z","iopub.execute_input":"2022-07-04T08:20:11.801485Z","iopub.status.idle":"2022-07-04T08:20:11.815341Z","shell.execute_reply.started":"2022-07-04T08:20:11.801435Z","shell.execute_reply":"2022-07-04T08:20:11.814546Z"},"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":"2022-07-04T08:20:11.821388Z","iopub.execute_input":"2022-07-04T08:20:11.822391Z","iopub.status.idle":"2022-07-04T08:22:54.433559Z","shell.execute_reply.started":"2022-07-04T08:20:11.82231Z","shell.execute_reply":"2022-07-04T08:22:54.431562Z"},"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":"2022-07-04T08:22:54.435909Z","iopub.execute_input":"2022-07-04T08:22:54.437969Z","iopub.status.idle":"2022-07-04T08:23:03.068379Z","shell.execute_reply.started":"2022-07-04T08:22:54.437913Z","shell.execute_reply":"2022-07-04T08:23:03.067639Z"},"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":"2022-07-04T08:23:03.069826Z","iopub.execute_input":"2022-07-04T08:23:03.072315Z","iopub.status.idle":"2022-07-04T08:23:03.085036Z","shell.execute_reply.started":"2022-07-04T08:23:03.072245Z","shell.execute_reply":"2022-07-04T08:23:03.084031Z"},"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":"2022-07-04T08:23:03.086878Z","iopub.execute_input":"2022-07-04T08:23:03.087512Z","iopub.status.idle":"2022-07-04T08:23:20.092343Z","shell.execute_reply.started":"2022-07-04T08:23:03.087116Z","shell.execute_reply":"2022-07-04T08:23:20.091515Z"},"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":"2022-07-04T08:23:20.093598Z","iopub.execute_input":"2022-07-04T08:23:20.09405Z","iopub.status.idle":"2022-07-04T08:23:20.109571Z","shell.execute_reply.started":"2022-07-04T08:23:20.093994Z","shell.execute_reply":"2022-07-04T08:23:20.108735Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"hpc.head()","metadata":{"execution":{"iopub.status.busy":"2022-07-04T08:23:20.110963Z","iopub.execute_input":"2022-07-04T08:23:20.111393Z","iopub.status.idle":"2022-07-04T08:23:20.141029Z","shell.execute_reply.started":"2022-07-04T08:23:20.111336Z","shell.execute_reply":"2022-07-04T08:23:20.140326Z"},"trusted":true},"execution_count":null,"outputs":[]}]}