{"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":"2021-06-12T12:42:31.272166Z","iopub.execute_input":"2021-06-12T12:42:31.272433Z","iopub.status.idle":"2021-06-12T12:42:33.829088Z","shell.execute_reply.started":"2021-06-12T12:42:31.272384Z","shell.execute_reply":"2021-06-12T12:42:33.827897Z"},"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":"2021-06-12T12:42:33.834659Z","iopub.execute_input":"2021-06-12T12:42:33.835093Z","iopub.status.idle":"2021-06-12T12:42:34.611516Z","shell.execute_reply.started":"2021-06-12T12:42:33.834911Z","shell.execute_reply":"2021-06-12T12:42:34.610424Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import warnings \nwarnings.filterwarnings(\"ignore\")","metadata":{"execution":{"iopub.status.busy":"2021-06-12T12:42:34.615730Z","iopub.execute_input":"2021-06-12T12:42:34.616241Z","iopub.status.idle":"2021-06-12T12:42:34.620810Z","shell.execute_reply.started":"2021-06-12T12:42:34.616194Z","shell.execute_reply":"2021-06-12T12:42:34.620067Z"},"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":"2021-06-12T12:42:34.622820Z","iopub.execute_input":"2021-06-12T12:42:34.623994Z","iopub.status.idle":"2021-06-12T12:42:34.631493Z","shell.execute_reply.started":"2021-06-12T12:42:34.623937Z","shell.execute_reply":"2021-06-12T12:42:34.630686Z"},"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":"2021-06-12T12:42:34.632840Z","iopub.execute_input":"2021-06-12T12:42:34.633477Z","iopub.status.idle":"2021-06-12T12:42:41.822413Z","shell.execute_reply.started":"2021-06-12T12:42:34.633428Z","shell.execute_reply":"2021-06-12T12:42:41.821529Z"},"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":"2021-06-12T12:42:41.823837Z","iopub.execute_input":"2021-06-12T12:42:41.824098Z","iopub.status.idle":"2021-06-12T12:42:41.860838Z","shell.execute_reply.started":"2021-06-12T12:42:41.824054Z","shell.execute_reply":"2021-06-12T12:42:41.860239Z"},"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":"2021-06-12T12:42:41.861949Z","iopub.execute_input":"2021-06-12T12:42:41.862198Z","iopub.status.idle":"2021-06-12T12:42:41.866747Z","shell.execute_reply.started":"2021-06-12T12:42:41.862144Z","shell.execute_reply":"2021-06-12T12:42:41.865715Z"},"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":"2021-06-12T12:42:41.867722Z","iopub.execute_input":"2021-06-12T12:42:41.867959Z","iopub.status.idle":"2021-06-12T12:42:47.368713Z","shell.execute_reply.started":"2021-06-12T12:42:41.867917Z","shell.execute_reply":"2021-06-12T12:42:47.367742Z"},"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":"2021-06-12T12:42:47.370108Z","iopub.execute_input":"2021-06-12T12:42:47.370382Z","iopub.status.idle":"2021-06-12T12:42:47.376363Z","shell.execute_reply.started":"2021-06-12T12:42:47.370335Z","shell.execute_reply":"2021-06-12T12:42:47.375501Z"},"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":"2021-06-12T12:42:47.377509Z","iopub.execute_input":"2021-06-12T12:42:47.377931Z","iopub.status.idle":"2021-06-12T12:42:47.430362Z","shell.execute_reply.started":"2021-06-12T12:42:47.377884Z","shell.execute_reply":"2021-06-12T12:42:47.429586Z"},"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":"2021-06-12T12:42:47.433327Z","iopub.execute_input":"2021-06-12T12:42:47.433603Z","iopub.status.idle":"2021-06-12T12:42:47.513143Z","shell.execute_reply.started":"2021-06-12T12:42:47.433551Z","shell.execute_reply":"2021-06-12T12:42:47.512381Z"},"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":"2021-06-12T12:42:47.514365Z","iopub.execute_input":"2021-06-12T12:42:47.514645Z","iopub.status.idle":"2021-06-12T12:42:51.080559Z","shell.execute_reply.started":"2021-06-12T12:42:47.514601Z","shell.execute_reply":"2021-06-12T12:42:51.079868Z"},"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":"2021-06-12T12:42:51.081752Z","iopub.execute_input":"2021-06-12T12:42:51.082010Z","iopub.status.idle":"2021-06-12T12:42:51.119369Z","shell.execute_reply.started":"2021-06-12T12:42:51.081968Z","shell.execute_reply":"2021-06-12T12:42:51.118766Z"},"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":"2021-06-12T12:42:51.120555Z","iopub.execute_input":"2021-06-12T12:42:51.120827Z","iopub.status.idle":"2021-06-12T12:42:51.127820Z","shell.execute_reply.started":"2021-06-12T12:42:51.120781Z","shell.execute_reply":"2021-06-12T12:42:51.126989Z"},"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":"2021-06-12T12:42:51.128990Z","iopub.execute_input":"2021-06-12T12:42:51.129326Z","iopub.status.idle":"2021-06-12T12:42:51.137477Z","shell.execute_reply.started":"2021-06-12T12:42:51.129270Z","shell.execute_reply":"2021-06-12T12:42:51.136347Z"},"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":"2021-06-12T12:42:51.138798Z","iopub.execute_input":"2021-06-12T12:42:51.139111Z","iopub.status.idle":"2021-06-12T12:42:51.161502Z","shell.execute_reply.started":"2021-06-12T12:42:51.139054Z","shell.execute_reply":"2021-06-12T12:42:51.160598Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# c=math.ceil(len(image_fps)*0.7)\n# image_fps_train,image_fps_val=image_fps[:c],image_fps[c:]\n# image_fps_train, image_fps_test=image_fps_train[:2000], image_fps_train[2000:2500]\n# image_fps_val=image_fps_val[:500]\n","metadata":{"execution":{"iopub.status.busy":"2021-06-12T12:42:51.162735Z","iopub.execute_input":"2021-06-12T12:42:51.163147Z","iopub.status.idle":"2021-06-12T12:42:51.166824Z","shell.execute_reply.started":"2021-06-12T12:42:51.162958Z","shell.execute_reply":"2021-06-12T12:42:51.165849Z"},"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":"2021-06-12T12:42:51.167943Z","iopub.execute_input":"2021-06-12T12:42:51.168415Z","iopub.status.idle":"2021-06-12T12:42:51.181392Z","shell.execute_reply.started":"2021-06-12T12:42:51.168367Z","shell.execute_reply":"2021-06-12T12:42:51.180490Z"},"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":"2021-06-12T12:42:51.183526Z","iopub.execute_input":"2021-06-12T12:42:51.183745Z","iopub.status.idle":"2021-06-12T12:42:51.195172Z","shell.execute_reply.started":"2021-06-12T12:42:51.183704Z","shell.execute_reply":"2021-06-12T12:42:51.194490Z"},"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":"2021-06-12T12:42:51.196435Z","iopub.execute_input":"2021-06-12T12:42:51.196919Z","iopub.status.idle":"2021-06-12T12:42:51.216972Z","shell.execute_reply.started":"2021-06-12T12:42:51.196872Z","shell.execute_reply":"2021-06-12T12:42:51.216294Z"},"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":"2021-06-12T12:42:51.219341Z","iopub.execute_input":"2021-06-12T12:42:51.219855Z","iopub.status.idle":"2021-06-12T12:42:51.229735Z","shell.execute_reply.started":"2021-06-12T12:42:51.219806Z","shell.execute_reply":"2021-06-12T12:42:51.229161Z"},"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":"2021-06-12T12:42:51.231275Z","iopub.execute_input":"2021-06-12T12:42:51.231755Z","iopub.status.idle":"2021-06-12T12:42:51.644752Z","shell.execute_reply.started":"2021-06-12T12:42:51.231568Z","shell.execute_reply":"2021-06-12T12:42:51.643913Z"},"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":"2021-06-12T12:42:51.645714Z","iopub.execute_input":"2021-06-12T12:42:51.646138Z","iopub.status.idle":"2021-06-12T12:42:56.909370Z","shell.execute_reply.started":"2021-06-12T12:42:51.646091Z","shell.execute_reply":"2021-06-12T12:42:56.908718Z"},"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":"2021-06-12T12:42:56.910525Z","iopub.execute_input":"2021-06-12T12:42:56.910928Z","iopub.status.idle":"2021-06-12T12:42:56.921350Z","shell.execute_reply.started":"2021-06-12T12:42:56.910880Z","shell.execute_reply":"2021-06-12T12:42:56.920571Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"config = DetectorConfig()\nconfig.display()","metadata":{"execution":{"iopub.status.busy":"2021-06-12T12:42:56.922496Z","iopub.execute_input":"2021-06-12T12:42:56.922963Z","iopub.status.idle":"2021-06-12T12:42:56.950242Z","shell.execute_reply.started":"2021-06-12T12:42:56.922914Z","shell.execute_reply":"2021-06-12T12:42:56.949601Z"},"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":"2021-06-12T12:42:56.952237Z","iopub.execute_input":"2021-06-12T12:42:56.952518Z","iopub.status.idle":"2021-06-12T12:43:11.268624Z","shell.execute_reply.started":"2021-06-12T12:42:56.952460Z","shell.execute_reply":"2021-06-12T12:43:11.267866Z"},"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":"2021-06-12T12:43:11.272111Z","iopub.execute_input":"2021-06-12T12:43:11.272344Z","iopub.status.idle":"2021-06-12T13:32:15.980112Z","shell.execute_reply.started":"2021-06-12T12:43:11.272294Z","shell.execute_reply":"2021-06-12T13:32:15.975397Z"},"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":"2021-06-12T13:32:15.989849Z","iopub.execute_input":"2021-06-12T13:32:15.996929Z","iopub.status.idle":"2021-06-12T13:32:16.214991Z","shell.execute_reply.started":"2021-06-12T13:32:15.996867Z","shell.execute_reply":"2021-06-12T13:32:16.213747Z"},"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":"2021-06-12T13:32:16.219357Z","iopub.execute_input":"2021-06-12T13:32:16.221561Z","iopub.status.idle":"2021-06-12T13:32:18.007585Z","shell.execute_reply.started":"2021-06-12T13:32:16.221502Z","shell.execute_reply":"2021-06-12T13:32:18.006313Z"},"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":"2021-06-12T13:32:18.010579Z","iopub.execute_input":"2021-06-12T13:32:18.012926Z","iopub.status.idle":"2021-06-12T13:32:19.959956Z","shell.execute_reply.started":"2021-06-12T13:32:18.010832Z","shell.execute_reply":"2021-06-12T13:32:19.958451Z"},"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":"2021-06-12T13:32:19.961372Z","iopub.execute_input":"2021-06-12T13:32:19.965739Z","iopub.status.idle":"2021-06-12T13:32:21.716485Z","shell.execute_reply.started":"2021-06-12T13:32:19.961630Z","shell.execute_reply":"2021-06-12T13:32:21.715363Z"},"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":"2021-06-12T13:32:21.723362Z","iopub.execute_input":"2021-06-12T13:32:21.726564Z","iopub.status.idle":"2021-06-12T13:32:21.741707Z","shell.execute_reply.started":"2021-06-12T13:32:21.726511Z","shell.execute_reply":"2021-06-12T13:32:21.740746Z"},"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":"2021-06-12T13:32:21.748847Z","iopub.execute_input":"2021-06-12T13:32:21.752712Z","iopub.status.idle":"2021-06-12T13:32:21.773278Z","shell.execute_reply.started":"2021-06-12T13:32:21.752652Z","shell.execute_reply":"2021-06-12T13:32:21.771550Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# # select trained model \n# dir_names = next(os.walk(model.model_dir))[1]\n# key = config.NAME.lower()\n# dir_names = filter(lambda f: f.startswith(key), dir_names)\n# dir_names = sorted(dir_names)\n    \n# fps = []\n# # Pick last directory\n# for d in dir_names: \n#     dir_name = os.path.join(model.model_dir, d)\n#     # Find the last checkpoint\n#     checkpoints = next(os.walk(dir_name))[2]\n#     checkpoints = filter(lambda f: f.startswith(\"mask_rcnn\"), checkpoints)\n#     checkpoints = sorted(checkpoints)\n#     if not checkpoints:\n#         print('No weight files in {}'.format(dir_name))\n#     else:\n#         checkpoint = os.path.join(dir_name, checkpoints[best_epoch])\n#         fps.append(checkpoint)\n\n# model_path = sorted(fps)[-1]\n# print('Found model {}'.format(model_path))","metadata":{"execution":{"iopub.status.busy":"2021-06-12T13:32:21.780069Z","iopub.execute_input":"2021-06-12T13:32:21.785889Z","iopub.status.idle":"2021-06-12T13:32:21.814566Z","shell.execute_reply.started":"2021-06-12T13:32:21.785791Z","shell.execute_reply":"2021-06-12T13:32:21.812028Z"},"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":"2021-06-12T13:32:21.820391Z","iopub.execute_input":"2021-06-12T13:32:21.826731Z","iopub.status.idle":"2021-06-12T13:33:03.902807Z","shell.execute_reply.started":"2021-06-12T13:32:21.826638Z","shell.execute_reply":"2021-06-12T13:33:03.900521Z"},"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":"2021-06-12T13:33:03.904933Z","iopub.execute_input":"2021-06-12T13:33:03.905208Z","iopub.status.idle":"2021-06-12T13:33:03.920780Z","shell.execute_reply.started":"2021-06-12T13:33:03.905161Z","shell.execute_reply":"2021-06-12T13:33:03.919830Z"},"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":"2021-06-12T13:33:03.925860Z","iopub.execute_input":"2021-06-12T13:33:03.928931Z","iopub.status.idle":"2021-06-12T13:33:03.943332Z","shell.execute_reply.started":"2021-06-12T13:33:03.926098Z","shell.execute_reply":"2021-06-12T13:33:03.942535Z"},"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":"2021-06-12T13:33:03.947655Z","iopub.execute_input":"2021-06-12T13:33:03.950643Z","iopub.status.idle":"2021-06-12T13:35:37.761587Z","shell.execute_reply.started":"2021-06-12T13:33:03.947911Z","shell.execute_reply":"2021-06-12T13:35:37.760572Z"},"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":"2021-06-12T13:42:16.115776Z","iopub.execute_input":"2021-06-12T13:42:16.116052Z","iopub.status.idle":"2021-06-12T13:42:19.061434Z","shell.execute_reply.started":"2021-06-12T13:42:16.116004Z","shell.execute_reply":"2021-06-12T13:42:19.060509Z"},"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":"2021-06-12T13:35:45.607202Z","iopub.execute_input":"2021-06-12T13:35:45.613665Z","iopub.status.idle":"2021-06-12T13:35:45.632848Z","shell.execute_reply.started":"2021-06-12T13:35:45.613612Z","shell.execute_reply":"2021-06-12T13:35:45.632092Z"},"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":"2021-06-12T13:35:45.637193Z","iopub.execute_input":"2021-06-12T13:35:45.638721Z","iopub.status.idle":"2021-06-12T13:35:58.753093Z","shell.execute_reply.started":"2021-06-12T13:35:45.638666Z","shell.execute_reply":"2021-06-12T13:35:58.752140Z"},"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":"2021-06-12T13:35:58.757106Z","iopub.execute_input":"2021-06-12T13:35:58.759134Z","iopub.status.idle":"2021-06-12T13:35:58.782872Z","shell.execute_reply.started":"2021-06-12T13:35:58.757334Z","shell.execute_reply":"2021-06-12T13:35:58.781977Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"hpc.head()","metadata":{"execution":{"iopub.status.busy":"2021-06-12T13:35:58.786569Z","iopub.execute_input":"2021-06-12T13:35:58.788583Z","iopub.status.idle":"2021-06-12T13:35:58.821869Z","shell.execute_reply.started":"2021-06-12T13:35:58.786804Z","shell.execute_reply":"2021-06-12T13:35:58.821138Z"},"trusted":true},"execution_count":null,"outputs":[]}]}