{"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":"markdown","source":"Welcome to the world where fashion meets computer vision! This is a starter kernel that applies Mask R-CNN with COCO pretrained weights to the task of [iMaterialist (Fashion) 2019 at FGVC6](https://www.kaggle.com/c/imaterialist-fashion-2019-FGVC6).","metadata":{}},{"cell_type":"code","source":"import os\nimport gc\nimport sys\nimport json\nimport glob\nimport random\nfrom pathlib import Path\n\nimport cv2\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport itertools\nfrom tqdm import tqdm\n\nfrom imgaug import augmenters as iaa\nfrom sklearn.model_selection import StratifiedKFold, KFold","metadata":{"execution":{"iopub.status.busy":"2022-04-03T15:02:40.788731Z","iopub.execute_input":"2022-04-03T15:02:40.788996Z","iopub.status.idle":"2022-04-03T15:02:42.230449Z","shell.execute_reply.started":"2022-04-03T15:02:40.788949Z","shell.execute_reply":"2022-04-03T15:02:42.229467Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"DATA_DIR = Path('../../input/imaterialist-fashion-2019-FGVC6')\nROOT_DIR = Path('/kaggle/working')\n\n# For demonstration purpose, the classification ignores attributes (only categories),\n# and the image size is set to 512, which is the same as the size of submission masks\n\nim_width = 128\nim_height = 128\nborder = 5\npath_train = '../input/imaterialist-fashion-2019-FGVC6/train/'\npath_test = '../input/imaterialist-fashion-2019-FGVC6/test/'","metadata":{"execution":{"iopub.status.busy":"2022-04-03T15:03:47.050112Z","iopub.execute_input":"2022-04-03T15:03:47.050398Z","iopub.status.idle":"2022-04-03T15:03:47.054973Z","shell.execute_reply.started":"2022-04-03T15:03:47.050343Z","shell.execute_reply":"2022-04-03T15:03:47.054281Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Dowload Libraries and Pretrained Weights","metadata":{}},{"cell_type":"code","source":"def get_data(path, train=True):\n    ids = next(os.walk(path + \"images\"))[2]\n    X = np.zeros((len(ids), im_height, im_width, 1), dtype=np.float32)\n    if train:\n        y = np.zeros((len(ids), im_height, im_width, 1), dtype=np.float32)\n    print('Getting and resizing images ... ')\n    for n, id_ in tqdm_notebook(enumerate(ids), total=len(ids)):\n        # Load images\n        img = load_img(path + '/images/' + id_, grayscale=True)\n        x_img = img_to_array(img)\n        x_img = resize(x_img, (128, 128, 1), mode='constant', preserve_range=True)\n\n        # Load masks\n        if train:\n            mask = img_to_array(load_img(path + '/masks/' + id_, grayscale=True))\n            mask = resize(mask, (128, 128, 1), mode='constant', preserve_range=True)\n\n        # Save images\n        X[n, ..., 0] = x_img.squeeze() / 255\n        if train:\n            y[n] = mask / 255\n    print('Done!')\n    if train:\n        return X, y\n    else:\n        return X\n    \nX, y = get_data(path_train, train=True)","metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","execution":{"iopub.status.busy":"2022-04-03T15:03:50.789851Z","iopub.execute_input":"2022-04-03T15:03:50.790138Z","iopub.status.idle":"2022-04-03T15:03:50.823611Z","shell.execute_reply.started":"2022-04-03T15:03:50.790085Z","shell.execute_reply":"2022-04-03T15:03:50.822378Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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","metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","execution":{"iopub.status.busy":"2022-04-03T12:38:00.819364Z","iopub.execute_input":"2022-04-03T12:38:00.819644Z","iopub.status.idle":"2022-04-03T12:38:01.80008Z","shell.execute_reply.started":"2022-04-03T12:38:00.819589Z","shell.execute_reply":"2022-04-03T12:38:01.798409Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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'","metadata":{"execution":{"iopub.status.busy":"2022-04-03T12:38:01.801249Z","iopub.execute_input":"2022-04-03T12:38:01.801519Z","iopub.status.idle":"2022-04-03T12:38:19.924911Z","shell.execute_reply.started":"2022-04-03T12:38:01.801471Z","shell.execute_reply":"2022-04-03T12:38:19.923889Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Set Config","metadata":{}},{"cell_type":"markdown","source":"Mask R-CNN has a load of hyperparameters. I only adjust some of them.","metadata":{}},{"cell_type":"code","source":"class FashionConfig(Config):\n    NAME = \"fashion\"\n    NUM_CLASSES = NUM_CATS + 1 # +1 for the background class\n    \n    GPU_COUNT = 1\n    IMAGES_PER_GPU = 4 # a memory error occurs when IMAGES_PER_GPU is too high\n    \n    BACKBONE = 'resnet50'\n    \n    IMAGE_MIN_DIM = IMAGE_SIZE\n    IMAGE_MAX_DIM = IMAGE_SIZE    \n    IMAGE_RESIZE_MODE = 'none'\n    \n    RPN_ANCHOR_SCALES = (16, 32, 64, 128, 256)\n    #DETECTION_NMS_THRESHOLD = 0.0\n    \n    # STEPS_PER_EPOCH should be the number of instances \n    # divided by (GPU_COUNT*IMAGES_PER_GPU), and so should VALIDATION_STEPS;\n    # however, due to the time limit, I set them so that this kernel can be run in 9 hours\n    STEPS_PER_EPOCH = 1000\n    VALIDATION_STEPS = 200\n    \nconfig = FashionConfig()\nconfig.display()","metadata":{"execution":{"iopub.status.busy":"2022-04-03T12:38:19.929571Z","iopub.execute_input":"2022-04-03T12:38:19.931701Z","iopub.status.idle":"2022-04-03T12:38:19.952629Z","shell.execute_reply.started":"2022-04-03T12:38:19.931633Z","shell.execute_reply":"2022-04-03T12:38:19.951774Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Make Datasets","metadata":{"execution":{"iopub.status.busy":"2022-04-03T12:38:19.956498Z","iopub.execute_input":"2022-04-03T12:38:19.958661Z","iopub.status.idle":"2022-04-03T12:38:19.963565Z","shell.execute_reply.started":"2022-04-03T12:38:19.958586Z","shell.execute_reply":"2022-04-03T12:38:19.962778Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pwd","metadata":{"execution":{"iopub.status.busy":"2022-04-03T12:38:19.968026Z","iopub.execute_input":"2022-04-03T12:38:19.970049Z","iopub.status.idle":"2022-04-03T12:38:20.718241Z","shell.execute_reply.started":"2022-04-03T12:38:19.96997Z","shell.execute_reply":"2022-04-03T12:38:20.717326Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with open(\"../../input/imaterialist-fashion-2019-FGVC6/label_descriptions.json\") as f:\n    label_descriptions = json.load(f)\n\nlabel_names = [x['name'] for x in label_descriptions['categories']]","metadata":{"execution":{"iopub.status.busy":"2022-04-03T12:38:20.719713Z","iopub.execute_input":"2022-04-03T12:38:20.720002Z","iopub.status.idle":"2022-04-03T12:38:20.729982Z","shell.execute_reply.started":"2022-04-03T12:38:20.719953Z","shell.execute_reply":"2022-04-03T12:38:20.729093Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"len(label_names)","metadata":{"execution":{"iopub.status.busy":"2022-04-03T12:38:20.731339Z","iopub.execute_input":"2022-04-03T12:38:20.731774Z","iopub.status.idle":"2022-04-03T12:38:20.740329Z","shell.execute_reply.started":"2022-04-03T12:38:20.731724Z","shell.execute_reply":"2022-04-03T12:38:20.739491Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"segment_df = pd.read_csv(DATA_DIR/\"train.csv\")\nsegment_df.head()","metadata":{"execution":{"iopub.status.busy":"2022-04-03T12:38:20.742709Z","iopub.execute_input":"2022-04-03T12:38:20.743239Z","iopub.status.idle":"2022-04-03T12:38:47.102602Z","shell.execute_reply.started":"2022-04-03T12:38:20.743181Z","shell.execute_reply":"2022-04-03T12:38:47.101814Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"multilabel_percent = len(segment_df[segment_df['ClassId'].str.contains('_')])/len(segment_df)*100\nprint(f\"Segments that have attributes: {multilabel_percent:.2f}%\")","metadata":{"execution":{"iopub.status.busy":"2022-04-03T12:38:47.103896Z","iopub.execute_input":"2022-04-03T12:38:47.10417Z","iopub.status.idle":"2022-04-03T12:38:47.335212Z","shell.execute_reply.started":"2022-04-03T12:38:47.104121Z","shell.execute_reply":"2022-04-03T12:38:47.333692Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Segments that contain attributes are only 3.46% of data, and [according to the host](https://www.kaggle.com/c/imaterialist-fashion-2019-FGVC6/discussion/90643#523135), 80% of images have no attribute. So, in the first step, we can only deal with categories to reduce the complexity of the task.","metadata":{}},{"cell_type":"code","source":"segment_df['CategoryId'] = segment_df['ClassId'].str.split('_').str[0]\n\nprint(\"Total segments: \", len(segment_df))\nsegment_df.head()","metadata":{"execution":{"iopub.status.busy":"2022-04-03T12:38:47.336608Z","iopub.execute_input":"2022-04-03T12:38:47.337063Z","iopub.status.idle":"2022-04-03T12:38:48.11497Z","shell.execute_reply.started":"2022-04-03T12:38:47.336891Z","shell.execute_reply":"2022-04-03T12:38:48.114277Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Rows with the same image are grouped together because the subsequent operations perform in an image level.","metadata":{}},{"cell_type":"code","source":"image_df = segment_df.groupby('ImageId')['EncodedPixels', 'CategoryId'].agg(lambda x: list(x))\nsize_df = segment_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()","metadata":{"execution":{"iopub.status.busy":"2022-04-03T12:38:48.116104Z","iopub.execute_input":"2022-04-03T12:38:48.116367Z","iopub.status.idle":"2022-04-03T12:38:56.143752Z","shell.execute_reply.started":"2022-04-03T12:38:48.116322Z","shell.execute_reply":"2022-04-03T12:38:56.142935Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Here is the custom function that resizes an image.","metadata":{}},{"cell_type":"code","source":"def resize_image(image_path):\n    img = cv2.imread(image_path)\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    img = cv2.resize(img, (IMAGE_SIZE, IMAGE_SIZE), interpolation=cv2.INTER_AREA)  \n    return img","metadata":{"execution":{"iopub.status.busy":"2022-04-03T12:38:56.145261Z","iopub.execute_input":"2022-04-03T12:38:56.145889Z","iopub.status.idle":"2022-04-03T12:38:56.151125Z","shell.execute_reply.started":"2022-04-03T12:38:56.145831Z","shell.execute_reply":"2022-04-03T12:38:56.150285Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"The crucial part is to create a dataset for this task.","metadata":{}},{"cell_type":"code","source":"class FashionDataset(utils.Dataset):\n\n    def __init__(self, df):\n        super().__init__(self)\n        \n        # Add classes\n        for i, name in enumerate(label_names):\n            self.add_class(\"fashion\", i+1, 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), \n                           labels=row['CategoryId'],\n                           annotations=row['EncodedPixels'], \n                           height=row['Height'], width=row['Width'])\n\n    def image_reference(self, image_id):\n        info = self.image_info[image_id]\n        return info['path'], [label_names[int(x)] for x in info['labels']]\n    \n    def load_image(self, image_id):\n        return resize_image(self.image_info[image_id]['path'])\n\n    def load_mask(self, image_id):\n        info = self.image_info[image_id]\n                \n        mask = np.zeros((IMAGE_SIZE, 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, (IMAGE_SIZE, 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)","metadata":{"execution":{"iopub.status.busy":"2022-04-03T12:38:56.156358Z","iopub.execute_input":"2022-04-03T12:38:56.157312Z","iopub.status.idle":"2022-04-03T12:38:56.17273Z","shell.execute_reply.started":"2022-04-03T12:38:56.157258Z","shell.execute_reply":"2022-04-03T12:38:56.171785Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Let's visualize some random images and their masks.","metadata":{}},{"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    print(dataset.image_reference(image_id))\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)","metadata":{"execution":{"iopub.status.busy":"2022-04-03T12:38:56.174344Z","iopub.execute_input":"2022-04-03T12:38:56.174738Z","iopub.status.idle":"2022-04-03T12:39:08.870332Z","shell.execute_reply.started":"2022-04-03T12:38:56.174621Z","shell.execute_reply":"2022-04-03T12:39:08.869615Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Now, the data are partitioned into train and validation sets.","metadata":{}},{"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 = 5\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()","metadata":{"execution":{"iopub.status.busy":"2022-04-03T12:39:08.871538Z","iopub.execute_input":"2022-04-03T12:39:08.871835Z","iopub.status.idle":"2022-04-03T12:39:14.681968Z","shell.execute_reply.started":"2022-04-03T12:39:08.871787Z","shell.execute_reply":"2022-04-03T12:39:14.681208Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Let's visualize class distributions of the train and validation data.","metadata":{}},{"cell_type":"code","source":"train_segments = np.concatenate(train_df['CategoryId'].values).astype(int)\nprint(\"Total train images: \", len(train_df))\nprint(\"Total train segments: \", len(train_segments))\n\nplt.figure(figsize=(12, 3))\nvalues, counts = np.unique(train_segments, return_counts=True)\nplt.bar(values, counts)\nplt.xticks(values, label_names, rotation='vertical')\nplt.show()\n\nvalid_segments = np.concatenate(valid_df['CategoryId'].values).astype(int)\nprint(\"Total train images: \", len(valid_df))\nprint(\"Total validation segments: \", len(valid_segments))\n\nplt.figure(figsize=(12, 3))\nvalues, counts = np.unique(valid_segments, return_counts=True)\nplt.bar(values, counts)\nplt.xticks(values, label_names, rotation='vertical')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-04-03T12:39:14.683268Z","iopub.execute_input":"2022-04-03T12:39:14.683533Z","iopub.status.idle":"2022-04-03T12:39:16.450695Z","shell.execute_reply.started":"2022-04-03T12:39:14.683489Z","shell.execute_reply":"2022-04-03T12:39:16.449927Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Train","metadata":{}},{"cell_type":"code","source":"# Note that any hyperparameters here, such as LR, may still not be optimal\nLR = 1e-4\nEPOCHS = [2, 6, 8]\n\nimport warnings \nwarnings.filterwarnings(\"ignore\")","metadata":{"execution":{"iopub.status.busy":"2022-04-03T12:39:16.451823Z","iopub.execute_input":"2022-04-03T12:39:16.452254Z","iopub.status.idle":"2022-04-03T12:39:16.458712Z","shell.execute_reply.started":"2022-04-03T12:39:16.452203Z","shell.execute_reply":"2022-04-03T12:39:16.458065Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"This section creates a Mask R-CNN model and specifies augmentations to be used.","metadata":{}},{"cell_type":"code","source":"model = modellib.MaskRCNN(mode='training', config=config, model_dir=ROOT_DIR)\n\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-04-03T12:39:16.459787Z","iopub.execute_input":"2022-04-03T12:39:16.460013Z","iopub.status.idle":"2022-04-03T12:39:25.752568Z","shell.execute_reply.started":"2022-04-03T12:39:16.459961Z","shell.execute_reply":"2022-04-03T12:39:25.751764Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pwd","metadata":{"execution":{"iopub.status.busy":"2022-04-03T12:39:25.753962Z","iopub.execute_input":"2022-04-03T12:39:25.754227Z","iopub.status.idle":"2022-04-03T12:39:26.668639Z","shell.execute_reply.started":"2022-04-03T12:39:25.75418Z","shell.execute_reply":"2022-04-03T12:39:26.667765Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.load_weights(\"../../input/training-mask-r-cnn-to-be-a-fashionista-lb-0-07/fashion20190522T1516/mask_rcnn_fashion_0008.h5\")","metadata":{"execution":{"iopub.status.busy":"2022-04-03T12:39:26.670195Z","iopub.execute_input":"2022-04-03T12:39:26.670472Z","iopub.status.idle":"2022-04-03T12:39:29.598717Z","shell.execute_reply.started":"2022-04-03T12:39:26.670423Z","shell.execute_reply":"2022-04-03T12:39:29.598018Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"augmentation = iaa.Sequential([\n    iaa.Fliplr(0.5) # only horizontal flip here\n])","metadata":{"execution":{"iopub.status.busy":"2022-04-03T12:39:29.600741Z","iopub.execute_input":"2022-04-03T12:39:29.601204Z","iopub.status.idle":"2022-04-03T12:39:29.606754Z","shell.execute_reply.started":"2022-04-03T12:39:29.60115Z","shell.execute_reply":"2022-04-03T12:39:29.606175Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"First, we train only the heads.","metadata":{}},{"cell_type":"code","source":"model.get_trainable_layers()","metadata":{"execution":{"iopub.status.busy":"2022-04-03T12:39:29.608361Z","iopub.execute_input":"2022-04-03T12:39:29.60885Z","iopub.status.idle":"2022-04-03T12:39:39.172704Z","shell.execute_reply.started":"2022-04-03T12:39:29.608608Z","shell.execute_reply":"2022-04-03T12:39:39.171942Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.get_trainable_layers()[10]","metadata":{"execution":{"iopub.status.busy":"2022-04-03T12:39:39.174077Z","iopub.execute_input":"2022-04-03T12:39:39.174356Z","iopub.status.idle":"2022-04-03T12:39:39.294684Z","shell.execute_reply.started":"2022-04-03T12:39:39.174305Z","shell.execute_reply":"2022-04-03T12:39:39.293869Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# model.summary()","metadata":{"execution":{"iopub.status.busy":"2022-04-03T12:39:39.296014Z","iopub.execute_input":"2022-04-03T12:39:39.296288Z","iopub.status.idle":"2022-04-03T12:39:39.300211Z","shell.execute_reply.started":"2022-04-03T12:39:39.296241Z","shell.execute_reply":"2022-04-03T12:39:39.299281Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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[0],\n            layers='heads',\n            augmentation=None)\n\nhistory = model.keras_model.history.history","metadata":{"execution":{"iopub.status.busy":"2022-04-03T12:39:39.301881Z","iopub.execute_input":"2022-04-03T12:39:39.302636Z","iopub.status.idle":"2022-04-03T12:39:48.894593Z","shell.execute_reply.started":"2022-04-03T12:39:39.302578Z","shell.execute_reply":"2022-04-03T12:39:48.893615Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Then, all layers are trained.","metadata":{}},{"cell_type":"code","source":"%%time\nmodel.train(train_dataset, valid_dataset,\n            learning_rate=LR,\n            epochs=EPOCHS[1],\n            layers='all',\n            augmentation=augmentation)\n\nnew_history = model.keras_model.history.history\nfor k in new_history: history[k] = history[k] + new_history[k]","metadata":{"execution":{"iopub.status.busy":"2022-04-03T12:39:48.898641Z","iopub.execute_input":"2022-04-03T12:39:48.898948Z","iopub.status.idle":"2022-04-03T12:40:08.895236Z","shell.execute_reply.started":"2022-04-03T12:39:48.898886Z","shell.execute_reply":"2022-04-03T12:40:08.894104Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Afterwards, we reduce LR and train again.","metadata":{}},{"cell_type":"code","source":"%%time\nmodel.train(train_dataset, valid_dataset,\n            learning_rate=LR/5,\n            epochs=EPOCHS[2],\n            layers='all',\n            augmentation=augmentation)\n\nnew_history = model.keras_model.history.history\nfor k in new_history: history[k] = history[k] + new_history[k]","metadata":{"execution":{"iopub.status.busy":"2022-04-03T12:40:08.8986Z","iopub.execute_input":"2022-04-03T12:40:08.898961Z","iopub.status.idle":"2022-04-03T12:41:19.627508Z","shell.execute_reply.started":"2022-04-03T12:40:08.898901Z","shell.execute_reply":"2022-04-03T12:41:19.626058Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Let's visualize training history and choose the best epoch.","metadata":{}},{"cell_type":"markdown","source":"# Predict","metadata":{}},{"cell_type":"markdown","source":"The final step is to use our model to predict test data.","metadata":{}},{"cell_type":"code","source":"glob_list = glob.glob(f'../../input/training-mask-r-cnn-to-be-a-fashionista-lb-0-07/fashion20190522T1516/mask_rcnn_fashion_0008.h5')\nmodel_path = glob_list[0] if glob_list else ''","metadata":{"execution":{"iopub.status.busy":"2022-04-03T12:42:15.58496Z","iopub.execute_input":"2022-04-03T12:42:15.585631Z","iopub.status.idle":"2022-04-03T12:42:15.596594Z","shell.execute_reply.started":"2022-04-03T12:42:15.58528Z","shell.execute_reply":"2022-04-03T12:42:15.595078Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"This cell defines InferenceConfig and loads the best trained model.","metadata":{}},{"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)","metadata":{"execution":{"iopub.status.busy":"2022-04-03T12:42:16.894332Z","iopub.execute_input":"2022-04-03T12:42:16.89486Z","iopub.status.idle":"2022-04-03T12:43:10.524228Z","shell.execute_reply.started":"2022-04-03T12:42:16.894772Z","shell.execute_reply":"2022-04-03T12:43:10.523069Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Then, load the submission data.","metadata":{}},{"cell_type":"code","source":"sample_df = pd.read_csv(DATA_DIR/\"sample_submission.csv\")\nsample_df.head()","metadata":{"execution":{"iopub.status.busy":"2022-04-03T12:43:10.52873Z","iopub.execute_input":"2022-04-03T12:43:10.529505Z","iopub.status.idle":"2022-04-03T12:43:10.600441Z","shell.execute_reply.started":"2022-04-03T12:43:10.528989Z","shell.execute_reply":"2022-04-03T12:43:10.599214Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Here is the main prediction steps, along with some helper functions.","metadata":{}},{"cell_type":"code","source":"# Convert data to run-length encoding\ndef to_rle(bits):\n    rle = []\n    pos = 0\n    for bit, group in itertools.groupby(bits):\n        group_list = list(group)\n        if bit:\n            rle.extend([pos, sum(group_list)])\n        pos += len(group_list)\n    return rle","metadata":{"execution":{"iopub.status.busy":"2022-04-03T12:43:10.606324Z","iopub.execute_input":"2022-04-03T12:43:10.606967Z","iopub.status.idle":"2022-04-03T12:43:10.626741Z","shell.execute_reply.started":"2022-04-03T12:43:10.606581Z","shell.execute_reply":"2022-04-03T12:43:10.619301Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Since the submission system does not permit overlapped masks, we have to fix them\ndef refine_masks(masks, rois):\n    areas = np.sum(masks.reshape(-1, masks.shape[-1]), axis=0)\n    mask_index = np.argsort(areas)\n    union_mask = np.zeros(masks.shape[:-1], dtype=bool)\n    for m in mask_index:\n        masks[:, :, m] = np.logical_and(masks[:, :, m], np.logical_not(union_mask))\n        union_mask = np.logical_or(masks[:, :, m], union_mask)\n    for m in range(masks.shape[-1]):\n        mask_pos = np.where(masks[:, :, m]==True)\n        if np.any(mask_pos):\n            y1, x1 = np.min(mask_pos, axis=1)\n            y2, x2 = np.max(mask_pos, axis=1)\n            rois[m, :] = [y1, x1, y2, x2]\n    return masks, rois","metadata":{"execution":{"iopub.status.busy":"2022-04-03T12:43:10.631034Z","iopub.execute_input":"2022-04-03T12:43:10.633786Z","iopub.status.idle":"2022-04-03T12:43:10.659753Z","shell.execute_reply.started":"2022-04-03T12:43:10.63127Z","shell.execute_reply":"2022-04-03T12:43:10.657572Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"1* (640*480)","metadata":{"execution":{"iopub.status.busy":"2022-04-03T12:43:10.665212Z","iopub.execute_input":"2022-04-03T12:43:10.676705Z","iopub.status.idle":"2022-04-03T12:43:10.687783Z","shell.execute_reply.started":"2022-04-03T12:43:10.66554Z","shell.execute_reply":"2022-04-03T12:43:10.686861Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\nsub_list = []\nmissing_count = 0\nfor i, row in tqdm(sample_df.iterrows(), total=len(sample_df)):\n    try:\n        image = resize_image(str(DATA_DIR/'test'/row['ImageId']))\n        result = model.detect([image])[0]\n        if result['masks'].size > 0:\n            masks, _ = refine_masks(result['masks'], result['rois'])\n            for m in range(masks.shape[-1]):\n                mask = masks[:, :, m].ravel(order='F')\n                rle = to_rle(mask)\n                label = result['class_ids'][m] - 1\n                sub_list.append([row['ImageId'], ' '.join(list(map(str, rle))), label])\n        else:\n            # The system does not allow missing ids, this is an easy way to fill them \n            sub_list.append([row['ImageId'], '1 1', 23])\n            missing_count += 1\n    except:\n        print(\"skipped, \", row['ImageId'])\n        ","metadata":{"execution":{"iopub.status.busy":"2022-04-03T12:43:10.690528Z","iopub.execute_input":"2022-04-03T12:43:10.699836Z","iopub.status.idle":"2022-04-03T13:08:40.574154Z","shell.execute_reply.started":"2022-04-03T12:43:10.699753Z","shell.execute_reply":"2022-04-03T13:08:40.57322Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"The submission file is created, when all predictions are ready.","metadata":{}},{"cell_type":"code","source":"submission_df = pd.DataFrame(sub_list, columns=sample_df.columns.values)\nprint(\"Total image results: \", submission_df['ImageId'].nunique())\nprint(\"Missing Images: \", missing_count)\nsubmission_df.head()","metadata":{"execution":{"iopub.status.busy":"2022-04-03T13:08:40.575373Z","iopub.execute_input":"2022-04-03T13:08:40.575632Z","iopub.status.idle":"2022-04-03T13:08:40.666532Z","shell.execute_reply.started":"2022-04-03T13:08:40.575587Z","shell.execute_reply":"2022-04-03T13:08:40.665819Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission_df.to_csv(\"submission.csv\", index=False)","metadata":{"execution":{"iopub.status.busy":"2022-04-03T13:08:40.667695Z","iopub.execute_input":"2022-04-03T13:08:40.668117Z","iopub.status.idle":"2022-04-03T13:08:41.3759Z","shell.execute_reply.started":"2022-04-03T13:08:40.668068Z","shell.execute_reply":"2022-04-03T13:08:41.3752Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Finally, it's pleasing to visualize the results! Sample images contain both fashion models and predictions from the Mask R-CNN model.","metadata":{}},{"cell_type":"code","source":"for i in range(9):\n    image_id = sample_df.sample()['ImageId'].values[0]\n    image_path = str(DATA_DIR/'test'/image_id)\n    \n    img = cv2.imread(image_path)\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    \n    result = model.detect([resize_image(image_path)])\n    r = result[0]\n    \n    if r['masks'].size > 0:\n        masks = np.zeros((img.shape[0], img.shape[1], r['masks'].shape[-1]), dtype=np.uint8)\n        for m in range(r['masks'].shape[-1]):\n            masks[:, :, m] = cv2.resize(r['masks'][:, :, m].astype('uint8'), \n                                        (img.shape[1], img.shape[0]), interpolation=cv2.INTER_NEAREST)\n        \n        y_scale = img.shape[0]/IMAGE_SIZE\n        x_scale = img.shape[1]/IMAGE_SIZE\n        rois = (r['rois'] * [y_scale, x_scale, y_scale, x_scale]).astype(int)\n        \n        masks, rois = refine_masks(masks, rois)\n    else:\n        masks, rois = r['masks'], r['rois']\n        \n    visualize.display_instances(img, rois, masks, r['class_ids'], \n                                ['bg']+label_names, r['scores'],\n                                title=image_id, figsize=(12, 12))","metadata":{"execution":{"iopub.status.busy":"2022-04-03T13:08:41.377133Z","iopub.execute_input":"2022-04-03T13:08:41.377415Z","iopub.status.idle":"2022-04-03T13:09:14.922512Z","shell.execute_reply.started":"2022-04-03T13:08:41.377369Z","shell.execute_reply":"2022-04-03T13:09:14.92177Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"My code is largely based on [this Mask-RCNN kernel](https://www.kaggle.com/hmendonca/mask-rcnn-and-coco-transfer-learning-lb-0-155) and borrowed some ideas from [the U-Net Baseline kernel](https://www.kaggle.com/go1dfish/u-net-baseline-by-pytorch-in-fgvc6-resize). So, I would like to thank the kernel authors for sharing insights and programming techniques. Importantly, an image segmentation task can be accomplished with short code and good accuracy thanks to [Matterport's implementation](https://github.com/matterport/Mask_RCNN) and a deep learning line of researches culminating in [Mask R-CNN](https://arxiv.org/abs/1703.06870).\n\nI am sorry that I published this kernel quite late, beyond the halfway of a timeline. I just started working for this competition about a week ago, and to my surprise, the score fell in the range of silver medals at that time. I have no dedicated GPU and no time to further tune the model, so I decided to make this kernel public as a starter guide for anyone who is interested to join this delightful competition.\n\n<img src='https://i.imgur.com/j6LPLQc.png'>","metadata":{}},{"cell_type":"markdown","source":"Hope you guys like this kernel. If there are any bugs, please let me know.\n\nP.S. When clicking 'Submit to Competition' button, I always run into 404 erros, so I have to save a submission file and upload it to the submission page for submitting. The public LB score of this kernel is around **0.07**.","metadata":{}},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}