{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 5GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Problem Statement:\n\nPneumonia is an infection in one or both lungs. Bacteria, viruses, and fungi cause it. The infection causes inflammation in the air sacs in your lungs, which are called alveoli.\n\nNow to detection Pneumonia we need to detect Inflammation of the lungs. In this project, you’re challenged to build an algorithm to detect a visual signal for pneumonia in medical images. Specifically, your algorithm needs to automatically locate lung opacities on chest radiographs.\n\nBusiness Domain Value Automating Pneumonia screening in chest radiographs, providing affected area details through bounding box. Assist physicians to make better clinical decisions or even replace human judgement in certain functional areas of healthcare (eg, radiology).\n\nProject objective In this capstone project, the goal is to build a pneumonia detection system, to locate the position of inflammation in an image.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"pip install keras==2.2.5","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pip install tensorflow==1.13.0rc1","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Importing all the standard libraries\n#..... array/martrix operations and dataframe libraries\nimport numpy as np\nimport pandas as pd\nimport os\nimport sys\nimport random\nimport tensorflow as tf\n#...........\n#.......... Visulaization libraries\nimport pydicom\nfrom imgaug import augmenters as iaa\nimport pylab\nimport cv2\nimport matplotlib.pyplot as plt\nimport seaborn as sn\nfrom skimage.transform import resize\n\n#......\nfrom sklearn.model_selection import train_test_split\n\n# NN model building linraries\nfrom keras.utils import to_categorical\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D\nfrom keras.layers import MaxPooling2D\nfrom keras.layers import Flatten\nfrom keras.layers import Dense\nfrom keras.layers import Dropout\n#...................................................","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Directory to save logs and trained model\nROOT_DIR = '/kaggle/working'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!git clone https://github.com/matterport/Mask_RCNN.git\nos.chdir('Mask_RCNN')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"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","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# setting path for each of the files\nclass_path='/kaggle/input/rsna-pneumonia-detection-challenge/stage_2_detailed_class_info.csv'\nlabels_path='/kaggle/input/rsna-pneumonia-detection-challenge/stage_2_train_labels.csv'\nImage_train_path='/kaggle/input/rsna-pneumonia-detection-challenge/stage_2_train_images/'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Files descrition\n#1. stage_2_detailed_class_info.csv- contains the information of target label\n#2. stage_2_train_labels.csv- contains information on Target and bounding box\n#3. stage_2_train_images- contains training images in dcm format","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Reading class file (first file) as dataframe and check few entries and shape\ndf_class=pd.read_csv(class_path)\nprint(df_class.head(10))\nprint(df_class.shape[0])\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_class['class'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Observation:\n# This file ocntains patient Id and repective class ifnormation. \n#. There are 30277 records\n# There are three classes- \n#    1. Lung Opacity- Patient havinig pneumonia, \n#    2. Normal- Patient not having pnemonia and not having any other lung problem\n#    3. No Lung Opacity/Not Normal- Patient not having pnemonia but having any other lung problem","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_class.info()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#Observation- There are no null values ","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# checking the number of unique entries with respect to patient ID\nprint(df_class['patientId'].value_counts().shape[0],'patient cases')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# # Reading label file (second file) as dataframe and check few entries and shape\ndf_label=pd.read_csv(labels_path)\nprint(df_label.head())\nprint(df_label.shape)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Observation\n#1. There are 30277 lables record (same as the class dataframe)\n#2. There are 6 columns - pateint ID (same as order as in class dataframe), bounding box co-ordinates, height and widht and Target label","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# Now lets drop the duplicate cases\ndf=pd.concat([df_label,df_class.drop('patientId',1)],1)\nprint(df.shape)\nprint(df.head())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Classes and Targets based on Patient count\ndf.groupby(['class','Target']).size().reset_index(name='patient_numbers')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print('Number of duplicate entries accross rows:\\n', df[df.duplicated()].count())\nprint('Number of duplicate Patient Id entries :\\n', df[df.duplicated(subset='patientId')].count())\nprint('Number of unique Patient Id entries: \\n', df['patientId'].nunique())\nprint('Count of various classes: \\n',df.groupby('class')['patientId'].nunique())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Observation\n#1. All the Normal and No Lung Opacity / Not Normal\tpatients are grouped under Target label 0 (no pnemonia)\n#2. Data Imabalance- there are ~30% pneumonia records and rest ~70% no pneumonia\n#3  There are no duplicates accross rows\n#4. Checking for duplicate patientId's, there are 26684 unique Patient Ids","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#--------------------------------------- Exploring training images data -------------------","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# chekcing the type of image file format and total number of images\nimage_path='/kaggle/input/rsna-pneumonia-detection-challenge/stage_2_train_images/'\nprint(os.listdir(image_path)[0])\nimport glob\nprint(len(list(glob.iglob(\"/kaggle/input/rsna-pneumonia-detection-challenge/stage_2_train_images/*.dcm\", recursive=True))))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#Observations:\n# All the images are in dcm format \n# these image file saved in the Digital Imaging and Communications in Medicine (DICOM) image format. \n#It stores a medical image, such as a CT scan or ultrasound\n# There are in total 26684 images which matches with the unique patient IDs. Seems there is no missing image file","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# Checking sample image file for first entry in dataframe which is normal case\nprint(df.iloc[3])\npatientId = df['patientId'][3]\nimage_path_1='/kaggle/input/rsna-pneumonia-detection-challenge/stage_2_train_images/%s.dcm' %patientId\ndcm_data=pydicom.read_file(image_path_1)\nprint(dcm_data)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#Observations:\n# dcm file contains metadata information about Patient (sample with no pnemonia): \n#             name, ID, Age, Sex, body part examines, view position, pixel data of image","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"#size of image\ndcm_data.pixel_array.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Original DICOM image size: 1024 x 1024\nORIG_SIZE = 1024","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#observations:\n#1. All the 26684 images have same size of 1024 X 1024","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"#Plotting the image \nplt.figure(figsize=(12,10))\nplt.subplot(121)\nplt.title('Pateint- Normal case class')\nplt.imshow(dcm_data.pixel_array)\nplt.subplot(122)\nplt.title('Pateint- Normal case class')\nplt.imshow(dcm_data.pixel_array,cmap=plt.cm.gist_gray)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#... Sample No Lung Opacity / Not Normal case ----------------\nprint(df.iloc[0])\npatientId = df['patientId'][0]\nimage_path_1='/kaggle/input/rsna-pneumonia-detection-challenge/stage_2_train_images/%s.dcm' %patientId\ndcm_data=pydicom.read_file(image_path_1)\nprint(dcm_data)\n\n#Plotting the image \nplt.figure(figsize=(12,10))\nplt.subplot(121)\nplt.title('Pateint- No Lung Opacity / Not Normal case')\nplt.imshow(dcm_data.pixel_array)\nplt.subplot(122)\nplt.title('Pateint- No Lung Opacity / Not Normal case')\nplt.imshow(dcm_data.pixel_array,cmap=plt.cm.gist_gray)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Lets us plot one Patient with pnemonia (Target = 1)\nprint(df.iloc[4])\npatientId = df['patientId'][4]\nimage_path_1='/kaggle/input/rsna-pneumonia-detection-challenge/stage_2_train_images/%s.dcm' %patientId\ndcm_data=pydicom.read_file(image_path_1)\nprint(dcm_data)\n#Plotting the image \nplt.figure(figsize=(12,10))\nplt.subplot(121)\nplt.title('Pateint- With pneumonia class')\nplt.imshow(dcm_data.pixel_array)\nplt.subplot(122)\nplt.title('Pateint- With pneumonia class')\nplt.imshow(dcm_data.pixel_array,cmap=plt.cm.gist_gray)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Function to show to a sample image with overlayed bounding box \ndef showImage(row):\n    \"\"\"\n    Method to draw single patient with bounding box(es) if present \n\n    \"\"\"\n    # --- Open DICOM file\n    imagePath = \"/kaggle/input/rsna-pneumonia-detection-challenge/stage_2_train_images/{0}.dcm\".format(row['patientId'])\n    d = pydicom.read_file(imagePath)\n    image = d.pixel_array\n    image = np.stack([image] * 3, axis=2)\n\n    if row['Target'] == 1:        \n        image = drawbox(image=image, row=row)\n\n    plt.imshow(image, cmap=plt.cm.gist_gray)\n    \n    \ndef drawbox(image, row):\n    color = np.floor(np.random.rand(3) * 256).astype('int')\n    stroke=6\n  \n    # --- Extract coordinates\n    x1 = int(row['x'])\n    y1 = int(row['y'])\n    y2 = y1 + int(row['height'])\n    x2 = x1 + int(row['width'])\n    \n    #print(x1)\n    #print(x2)\n    #print(y1)\n    #print(y2)\n    \n    image[y1:y1 + stroke, x1:x2] = color\n    image[y2:y2 + stroke, x1:x2] = color\n    image[y1:y2, x1:x1 + stroke] = color\n    image[y1:y2, x2:x2 + stroke] = color\n\n    return image","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#patient = labels_w_class.iloc[[10]]\npatient = list(df.T.to_dict().values())[4]\nprint(\"Path : stage_2_train_images/{0}.dcm\".format(patient['patientId']))\nprint(\"Target : {0}\".format(patient['Target']))\n\nplt.figure(figsize=(7,7))\nplt.title(\"Sample Patient - Lung Opacity\")\nshowImage(patient)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#----------------------------------------- Data generation for training, Model Building and training model-----","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# Function to collect three major information (Patient ID, box and corresponding image file path) into a dictonary called parsed\nextract_boxes=lambda row: [ row['y'], row['x'], row ['height'], row['width']]\nparsed={}\nfor n, row in df.iterrows():\n    pid=row['patientId']\n    if pid not in parsed:\n        parsed[pid]={\n            'dicom': '/kaggle/input/rsna-pneumonia-detection-challenge/stage_2_train_images/%s.dcm' % pid,\n            'label': row['Target'],\n            'boxes':[]\n            }\n                 \n    if parsed[pid]['label']==1:\n        parsed[pid]['boxes'].append(extract_boxes(row))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"len(parsed)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"parsed[df['patientId'][7]]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#............ function to get the images with bounbding box for any given Patient ID\ndef draw(data):\n#    \"\"\"\n#    Method to draw single patient with bounding box(es) if present \n\n#   \"\"\"\n    # --- Open DICOM file\n    d = pydicom.read_file(data['dicom'])\n    im = d.pixel_array\n\n    # --- Convert from single-channel grayscale to 3-channel RGB\n    im = np.stack([im] * 3, axis=2)\n\n    # --- Add boxes with random color if present\n    for box in data['boxes']:\n        rgb = np.floor(np.random.rand(3) * 256).astype('int')\n        im = overlay_box(im=im, box=box, rgb=rgb, stroke=6)\n\n    pylab.imshow(im, cmap=pylab.cm.gist_gray)\n    pylab.axis('off')\n\ndef overlay_box(im, box, rgb, stroke=1):\n    \"\"\"\n    Method to overlay single box on image\n\n    \"\"\"\n    # --- Convert coordinates to integers\n    box = [int(b) for b in box]\n    \n    # --- Extract coordinates\n    y1, x1, height, width = box\n    y2 = y1 + height\n    x2 = x1 + width\n\n    im[y1:y1 + stroke, x1:x2] = rgb\n    im[y2:y2 + stroke, x1:x2] = rgb\n    im[y1:y2, x1:x1 + stroke] = rgb\n    im[y1:y2, x2:x2 + stroke] = rgb\n\n    return im","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# overalaping bounding box with image for sample pnemonia case\n#Plotting the image \nprint(df.iloc[4])\npatientId = df['patientId'][4]\ndraw(parsed[patientId])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import csv\n# empty dictionary\npneumonia_locations = {}\n# load table\nwith open(os.path.join(labels_path), mode='r') as infile:\n    # open reader\n    reader = csv.reader(infile)\n    # skip header\n    next(reader, None)\n    # loop through rows\n    for rows in reader:\n        # retrieve information\n        filename = rows[0]\n        location = rows[1:5]\n        pneumonia = rows[5]\n        # if row contains pneumonia add label to dictionary\n        # which contains a list of pneumonia locations per filename\n        if pneumonia == '1':\n            # convert string to float to int\n            location = [int(float(i)) for i in location]\n            # save pneumonia location in dictionary\n            if filename in pneumonia_locations:\n                pneumonia_locations[filename].append(location)\n            else:\n                pneumonia_locations[filename] = [location]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"len(pneumonia_locations)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# load and shuffle filenames\nfolder = Image_train_path\nfilenames = os.listdir(folder)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_image='/kaggle/input/rsna-pneumonia-detection-challenge/stage_2_train_images/'\ntest_image='/kaggle/input/rsna-pneumonia-detection-challenge/stage_2_test_images/'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"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 ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class 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 = 1 \n    \n    BACKBONE = 'resnet50'\n    \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 = 0.9\n    DETECTION_NMS_THRESHOLD = 0.1\n\n    STEPS_PER_EPOCH = 10\n    \nconfig = DetectorConfig()\nconfig.display()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"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)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"image_fps, image_annotations = parse_dataset(train_image, anns=df_label)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ds = pydicom.read_file(image_fps[0]) # read dicom image from filepath \nimage = ds.pixel_array # get image array","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"######################################################################\n# Modify this line to use more or fewer images for training/validation. \n# To use all images, do: image_fps_list = list(image_fps)\nimage_fps_list = list(image_fps[:1000]) \n#####################################################################\n\n# split dataset into training vs. validation dataset \n# split ratio is set to 0.9 vs. 0.1 (train vs. validation, respectively)\nsorted(image_fps_list)\nrandom.seed(42)\nrandom.shuffle(image_fps_list)\n\nvalidation_split = 0.1\nsplit_index = int((1 - validation_split) * len(image_fps_list))\n\nimage_fps_train = image_fps_list[:split_index]\nimage_fps_val = image_fps_list[split_index:]\n\nprint(len(image_fps_train), len(image_fps_val))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# prepare the training dataset\ndataset_train = DetectorDataset(image_fps_train, image_annotations, ORIG_SIZE, ORIG_SIZE)\ndataset_train.prepare()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Show annotation(s) for a DICOM image \ntest_fp = random.choice(image_fps_train)\nimage_annotations[test_fp]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# prepare the validation dataset\ndataset_val = DetectorDataset(image_fps_val, image_annotations, ORIG_SIZE, ORIG_SIZE)\ndataset_val.prepare()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = modellib.MaskRCNN(mode='training', config=config, model_dir=ROOT_DIR)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Image augmentation \naugmentation = iaa.SomeOf((0, 3), [\n    iaa.Fliplr(0.5),\n    iaa.Flipud(0.5),\n    iaa.OneOf([iaa.Affine(rotate=90),\n               iaa.Affine(rotate=180),\n               iaa.Affine(rotate=270)],\n             ),\n    iaa.Affine(\n        scale={\"x\": (0.8, 1.2), \"y\": (0.8, 1.2)},\n        translate_percent={\"x\": (-0.2, 0.2), \"y\": (-0.2, 0.2)},\n        rotate=(-25, 25),\n        shear=(-8, 8)\n    ),\n    iaa.Multiply((0.9, 1.1))\n  \n])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"NUM_EPOCHS = 10\n\n# Train Mask-RCNN Model \nimport warnings \nwarnings.filterwarnings(\"ignore\")\nmodel.train(dataset_train, dataset_val, \n            learning_rate=config.LEARNING_RATE, \n            epochs=NUM_EPOCHS, \n            layers='all',\n            augmentation=augmentation)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}