{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# Import required libraries\nimport os\nimport gc\nimport sys\nimport json\nimport random\nfrom pathlib import Path\n\nimport cv2 # CV2 for image manipulation\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\nfrom tqdm import tqdm\n\nfrom imgaug import augmenters as iaa\n\nimport seaborn as sns\nimport matplotlib.image as mpimg\nfrom matplotlib import pyplot as plt\n\nfrom sklearn.model_selection import StratifiedKFold, KFold","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install tensorflow==1.13.1\n!pip install keras==2.1.5\n\nimport tensorflow\nprint(tensorflow.__version__)\nimport keras\nprint(keras.__version__)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\nwith open('/kaggle/input/imaterialist-fashion-2020-fgvc7/label_descriptions.json', 'r') as file:\n    label_desc = json.load(file)\nsample_sub_df = pd.read_csv('/kaggle/input/imaterialist-fashion-2020-fgvc7/sample_submission.csv')\ntrain_df = pd.read_csv('/kaggle/input/imaterialist-fashion-2020-fgvc7/train.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_sub_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(f'Shape of training dataset: {train_df.shape}')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(f'# of images in training set: {train_df[\"ImageId\"].nunique()}')\nprint(f'# of images in test set: {sample_sub_df[\"ImageId\"].nunique()}')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Image size analysis in training dataset","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"pd.DataFrame([train_df['Height'].describe(), train_df['Width'].describe()]).T.loc[['max', 'min', 'mean']]","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Height and Width destribution of training images","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"image_shape_df = train_df.groupby(\"ImageId\")[\"Height\", \"Width\"].first()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 5))\nax1.hist(image_shape_df['Height'], bins=100)\nax1.set_title(\"Height distribution\")\nax2.hist(image_shape_df['Width'], bins=100)\nax2.set_title(\"Width distribution\")\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"num_classes = len(label_desc['categories'])\nnum_attributes = len(label_desc['attributes'])\nprint(f'Total # of classes: {num_classes}')\nprint(f'Total # of attributes: {num_attributes}')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"categories_df = pd.DataFrame(label_desc['categories'])\nattributes_df = pd.DataFrame(label_desc['attributes'])\ncategories_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pd.set_option('display.max_rows', 300)\nattributes_df","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Plotting a few training images without any masks","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def plot_images(size=12, figsize=(12, 12)):\n    # First get some images to be plotted\n    image_ids = train_df['ImageId'].unique()[:12]\n    images=[]\n    \n    for image in image_ids:\n        images.append(mpimg.imread(f'/kaggle/input/imaterialist-fashion-2020-fgvc7/train/{image}.jpg'))\n    \n    # Plot images in groups of 4 images\n    n_groups = 4\n    \n    count = 0\n    for index in range(size // 4):\n        fig, ax = plt.subplots(nrows=2, ncols=2, figsize=figsize)\n        for row in ax:\n            for col in row:\n                col.imshow(images[count])\n                col.axis('off')\n                count += 1\n        plt.show()\n    gc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plot_images()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Plotting a few images with given segments","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def create_mask(size):\n    image_ids = train_df['ImageId'].unique()[:size]\n    images_meta=[]\n\n    for image_id in image_ids:\n        img = mpimg.imread(f'/kaggle/input/imaterialist-fashion-2020-fgvc7/train/{image_id}.jpg')\n        images_meta.append({\n            'image': img,\n            'shape': img.shape,\n            'encoded_pixels': train_df[train_df['ImageId'] == image_id]['EncodedPixels'],\n            'class_ids':  train_df[train_df['ImageId'] == image_id]['ClassId']\n        })\n\n    masks = []\n    for image in images_meta:\n        shape = image.get('shape')\n        encoded_pixels = list(image.get('encoded_pixels'))\n        class_ids = list(image.get('class_ids'))\n        \n        # Initialize numpy array with shape same as image size\n        height, width = shape[:2]\n        mask = np.zeros((height, width)).reshape(-1)\n        \n        # Iterate over encoded pixels and create mask\n        for segment, (pixel_str, class_id) in enumerate(zip(encoded_pixels, class_ids)):\n           # print(\"length of encoded pixel==\",len(encoded_pixels))\n            splitted_pixels = list(map(int, pixel_str.split()))\n            pixel_starts = splitted_pixels[::2]\n            run_lengths = splitted_pixels[1::2]\n            #if segment == 1:\n               # print(\"segment==\",segment,\"type of pixes start\",type(pixel_starts))\n               # print(\"type of run length\",type(run_lengths))\n            assert max(pixel_starts) < mask.shape[0]\n            for pixel_start, run_length in zip(pixel_starts, run_lengths):\n                pixel_start = int(pixel_start) - 1\n                run_length = int(run_length)\n                mask[pixel_start:pixel_start+run_length] = 255 - class_id * 4\n        masks.append(mask.reshape((height, width), order='F'))  # https://stackoverflow.com/questions/45973722/how-does-numpy-reshape-with-order-f-work\n    return masks, images_meta","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def plot_segmented_images(size=12, figsize=(14, 14)):\n    # First create masks from given segments\n    masks, images_meta = create_mask(size)\n    \n    # Plot images in groups of 4 images\n    n_groups = 4\n    \n    count = 0\n     \n    for index in range(size // 4):\n        fig, ax = plt.subplots(nrows=2, ncols=2, figsize=figsize)\n        for row in ax:\n            for col in row:\n               \n                #mask = np.zeros((512,512,3))\n               # col.imshow(mask)\n                #col.imshow(images_meta[count]['image'])\n                col.imshow(masks[count], alpha=0.75)\n                col.axis('off')\n                count += 1\n        plt.show()\n    gc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plot_segmented_images()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Analysing Categories and Attributes","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"categories_df = pd.DataFrame(label_desc.get('categories'))\nattributes_df = pd.DataFrame(label_desc.get('attributes'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(f'# of categories: {len(categories_df)}')\nprint(f'# of attributes: {len(attributes_df)}')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"categories_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"attributes_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"category_map, attribute_map = {}, {}\nfor cat in label_desc.get('categories'):\n    category_map[cat.get('id')] = cat.get('name')\nfor attr in label_desc.get('attributes'):\n    attribute_map[attr.get('id')] = attr.get('name')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df['ClassId'] = train_df['ClassId'].map(category_map)\ntrain_df['ClassId'] = train_df['ClassId'].astype('category')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sns.set(style='darkgrid')\nfig, ax = plt.subplots(figsize = (10,10))\nsns.countplot(y='ClassId',data=train_df , ax=ax, order = train_df['ClassId'].value_counts().index)\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"IMAGE_ID = '000b3ec2c6eaffb491a5abb72c2e3e26'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Get the an image id given in the training set for visualization\nvis_df = train_df[train_df['ImageId'] == IMAGE_ID]\nvis_df['ClassId'] = vis_df['ClassId'].cat.codes\nvis_df = vis_df.reset_index(drop=True)\nvis_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize = (110,11))\nimage = mpimg.imread(f'/kaggle/input/imaterialist-fashion-2020-fgvc7/train/{IMAGE_ID}.jpg')\nplt.grid(False)\nplt.imshow(image)\nplt.plot()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df[train_df['ImageId'] == IMAGE_ID]","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Now let's plot each segment in a separate image","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"segments = list(vis_df['EncodedPixels'])\nclass_ids = list(vis_df['ClassId'])\nmasks = []\nfor segment, class_id in zip(segments, class_ids):\n    \n    height = vis_df['Height'][0]\n    width = vis_df['Width'][0]\n    # Initialize empty mask\n    mask = np.zeros((height, width)).reshape(-1)\n    \n    # Iterate over encoded pixels and create mask\n    splitted_pixels = list(map(int, segment.split()))\n    pixel_starts = splitted_pixels[::2]\n    run_lengths = splitted_pixels[1::2]\n    assert max(pixel_starts) < mask.shape[0]\n    for pixel_start, run_length in zip(pixel_starts, run_lengths):\n        pixel_start = int(pixel_start) - 1\n        run_length = int(run_length)\n        mask[pixel_start:pixel_start+run_length] = 255 - class_id * 4\n\n    mask = mask.reshape((height, width), order='F')\n    masks.append(mask)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def plot_individual_segment(*masks, image, figsize=(110, 11)):\n    plt.figure(figsize = figsize)\n    plt.imshow(image)\n    for mask in masks:\n        plt.imshow(mask, alpha=0.6)\n    plt.axis('off')\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Plotting 1st Segment: ClassId: \"Shoe\" and no attributes ","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"plot_individual_segment(masks[0], image=image)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Plotting 2nd Segment: ClassId: \"shoe\"","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"plot_individual_segment(masks[1], image=image)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Plotting 3rd Segment with ClassId: \"pants\"","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"plot_individual_segment(masks[2], image=image)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Plotting 4th Segment with ClassId: \"top, t-shirt, sweatshirt\"","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"plot_individual_segment(masks[3], image=image)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Plotting 5th Segment with ClassId: \"pocket\"","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"plot_individual_segment(masks[4], image=image)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Plotting 6th Segment with ClassId: \"sleeve\"","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"plot_individual_segment(masks[5], image=image)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Plotting 7th Segment with ClassId: \"sleeve\"","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"plot_individual_segment(masks[6], image=image)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Plotting 8th segment with Class \"neckline\"","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"plot_individual_segment(masks[7], image=image)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(f'Segments that do not have attributes: {train_df[\"AttributesIds\"].isna().sum()/len(train_df) * 100} %')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df[['ImageId', 'EncodedPixels', 'Height', 'Width', 'ClassId']].isna().sum()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df['ClassId'] = train_df['ClassId'].cat.codes","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df = train_df.drop('AttributesIds', axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"image_df = train_df.groupby('ImageId')['EncodedPixels', 'ClassId'].agg(lambda x: list(x))\nsize_df = train_df.groupby('ImageId')['Height', 'Width'].mean()\nimage_df = image_df.join(size_df, on='ImageId')\n\nprint(\"Total images: \", len(image_df))\nimage_df.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Reference: https://github.com/matterport/Mask_RCNN/blob/master/samples/shapes/train_shapes.ipynb","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"import os\nfrom pathlib import Path\n!git clone https://www.github.com/matterport/Mask_RCNN.git\nos.chdir('Mask_RCNN')\n\n!rm -rf .git # to prevent an error when the kernel is committed\n!rm -rf images assets # to prevent displaying images at the bottom of a kernel","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!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 = 'mask_rcnn_coco.h5'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"DATA_DIR = Path('/kaggle/input/imaterialist-fashion-2020-fgvc7')\nROOT_DIR = Path('/kaggle/working')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import sys","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# sys.path.append(ROOT_DIR/'Mask_RCNN')\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":"class FashionConfig(Config):\n    \"\"\"Configuration for training on the toy shapes dataset.\n    Derives from the base Config class and overrides values specific\n    to the toy shapes dataset.\n    \"\"\"\n    # Give the configuration a recognizable name\n    NAME = \"class\"\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    # Number of classes (including background)\n    NUM_CLASSES = 1 + len(categories_df)  # background + 46 classes\n\n    # Use small images for faster training. Set the limits of the small side\n    # the large side, and that determines the image shape.\n    IMAGE_MIN_DIM = 256\n    IMAGE_MAX_DIM = 256\n\n    # Use smaller anchors because our image and objects are small\n    RPN_ANCHOR_SCALES = (8, 16, 32, 64, 128)  # anchor side in pixels\n\n    # Reduce training ROIs per image because the images are small and have\n    # few objects. Aim to allow ROI sampling to pick 33% positive ROIs.\n    TRAIN_ROIS_PER_IMAGE = 32\n\n    # Use a small epoch since the data is simple\n    STEPS_PER_EPOCH = 100\n\n    # use small validation steps since the epoch is small\n    VALIDATION_STEPS = 5\n    \nconfig = FashionConfig()\nconfig.display()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class FashionDataset(utils.Dataset):\n    def __init__(self, df):\n        super().__init__(self)\n        \n        self.IMAGE_SIZE = 256\n        \n        # Add classes\n        for cat in label_desc['categories']:\n            self.add_class('fashion', cat.get('id'), cat.get('name'))\n        \n        # Add images\n        for i, row in df.iterrows():\n            self.add_image(\"fashion\", \n                           image_id=row.name, \n                           path=str(DATA_DIR/'train'/row.name) + '.jpg', \n                           labels=row['ClassId'],\n                           annotations=row['EncodedPixels'], \n                           height=row['Height'], width=row['Width'])\n            \n    def _resize_image(self, image_path):\n        img = cv2.imread(image_path)\n        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n        img = cv2.resize(img, (self.IMAGE_SIZE, self.IMAGE_SIZE), interpolation=cv2.INTER_AREA)  \n        return img\n        \n    def load_image(self, image_id):\n        return self._resize_image(self.image_info[image_id]['path'])\n    \n    def image_reference(self, image_id):\n        info = self.image_info[image_id]\n        return info['path'], [x for x in info['labels']]\n    \n    def load_mask(self, image_id):\n        info = self.image_info[image_id]\n                \n        mask = np.zeros((self.IMAGE_SIZE, self.IMAGE_SIZE, len(info['annotations'])), dtype=np.uint8)\n        labels = []\n        \n        for m, (annotation, label) in enumerate(zip(info['annotations'], info['labels'])):\n            sub_mask = np.full(info['height']*info['width'], 0, dtype=np.uint8)\n            annotation = [int(x) for x in annotation.split(' ')]\n            \n            for i, start_pixel in enumerate(annotation[::2]):\n                sub_mask[start_pixel: start_pixel+annotation[2*i+1]] = 1\n\n            sub_mask = sub_mask.reshape((info['height'], info['width']), order='F')\n            sub_mask = cv2.resize(sub_mask, (self.IMAGE_SIZE, self.IMAGE_SIZE), interpolation=cv2.INTER_NEAREST)\n            \n            mask[:, :, m] = sub_mask\n            labels.append(int(label)+1)\n            \n        return mask, np.array(labels)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"dataset = FashionDataset(image_df)\ndataset.prepare()\n\nfor i in range(6):\n    image_id = random.choice(dataset.image_ids)\n\n    image = dataset.load_image(image_id)\n    mask, class_ids = dataset.load_mask(image_id)\n    visualize.display_top_masks(image, mask, class_ids, dataset.class_names, limit=4)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# This code partially supports k-fold training, \n# you can specify the fold to train and the total number of folds here\nFOLD = 0\nN_FOLDS = 2\n\nkf = KFold(n_splits=N_FOLDS, random_state=42, shuffle=True)\nsplits = kf.split(image_df) # ideally, this should be multilabel stratification\n\ndef get_fold():    \n    for i, (train_index, valid_index) in enumerate(splits):\n        if i == FOLD:\n            return image_df.iloc[train_index], image_df.iloc[valid_index]\n        \ntrain_df, valid_df = get_fold()\n\ntrain_dataset = FashionDataset(train_df)\ntrain_dataset.prepare()\n\nvalid_dataset = FashionDataset(valid_df)\nvalid_dataset.prepare()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(train_df.shape)\nprint(valid_df.shape)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Training","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# Note that any hyperparameters here, such as LR, may still not be optimal\nLR = 1e-4\nEPOCHS = 1\n\nimport warnings \nwarnings.filterwarnings(\"ignore\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Let's load the COCO dataset weights to our Model.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"model = modellib.MaskRCNN(mode='training', config=config, model_dir=ROOT_DIR)\n\n# Load weights trained on MS COCO, but skip layers that\n# are different due to the different number of classes\n# See README for instructions to download the COCO weights\nmodel.load_weights(COCO_WEIGHTS_PATH, by_name=True,\n                   exclude=[\"mrcnn_class_logits\", \"mrcnn_bbox_fc\", \n                            \"mrcnn_bbox\", \"mrcnn_mask\"])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"augmentation = iaa.Sequential([\n    iaa.Fliplr(0.5) # only horizontal flip here\n])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\nmodel.train(train_dataset, valid_dataset,\n            learning_rate=LR*2, # train heads with higher lr to speedup learning\n            epochs=EPOCHS,\n            layers='heads',\n            augmentation=None)\n\nhistory = model.keras_model.history.history","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# %%time\n# model.train(train_dataset, valid_dataset,\n#             learning_rate=LR,\n#             epochs=EPOCHS[1],\n#             layers='all',\n#             augmentation=augmentation)\n\n# new_history = model.keras_model.history.history\n# for k in new_history: history[k] = history[k] + new_history[k]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#%%time\n#model.train(train_dataset, valid_dataset,learning_rate=LR/5,epochs=EPOCHS[2],layers='all',augmentation=augmentation)\n#new_history = model.keras_model.history.history\n#for k in new_history: history[k] = history[k] + new_history[k]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"epochs = range(EPOCHS[0])\n\nplt.figure(figsize=(18, 6))\n\nplt.subplot(131)\nplt.plot(epochs, history['loss'], label=\"train loss\")\nplt.plot(epochs, history['val_loss'], label=\"valid loss\")\nplt.legend()\nplt.subplot(132)\nplt.plot(epochs, history['mrcnn_class_loss'], label=\"train class loss\")\nplt.plot(epochs, history['val_mrcnn_class_loss'], label=\"valid class loss\")\nplt.legend()\nplt.subplot(133)\nplt.plot(epochs, history['mrcnn_mask_loss'], label=\"train mask loss\")\nplt.plot(epochs, history['val_mrcnn_mask_loss'], label=\"valid mask loss\")\nplt.legend()\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"best_epoch = np.argmin(history[\"val_loss\"]) + 1\nprint(\"Best epoch: \", best_epoch)\nprint(\"Valid loss: \", history[\"val_loss\"][best_epoch-1])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import glob","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"glob_list = glob.glob(f'/kaggle/working/class*/mask_rcnn_class_{best_epoch:04d}.h5')\nmodel_path = glob_list[0] if glob_list else ''","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_df = sample_sub_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class InferenceConfig(FashionConfig):\n    GPU_COUNT = 1\n    IMAGES_PER_GPU = 1\n\ninference_config = InferenceConfig()\n\nmodel = modellib.MaskRCNN(mode='inference', \n                          config=inference_config,\n                          model_dir=ROOT_DIR)\n\nassert model_path != '', \"Provide path to trained weights\"\nprint(\"Loading weights from \", model_path)\nmodel.load_weights(model_path, by_name=True)","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}