{"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.5\n!pip install keras==2.1.5\n\nimport tensorflow\nprint(tensorflow.__version__)\nimport keras\nprint(keras.__version__)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"!ls /kaggle/input/imaterialist-fashion-2020-fgvc7/","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"},{"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"},{"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":{},"cell_type":"markdown","source":"### Image with minimum height"},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize = (70,7))\nmin_height = list(set(train_df[train_df['Height'] == train_df['Height'].min()]['ImageId']))[0]\nplt.imshow(mpimg.imread(f'/kaggle/input/imaterialist-fashion-2020-fgvc7/train/{min_height}.jpg'))\nplt.grid(False)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Image with maximum height"},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize = (70,7))\nmax_height = list(set(train_df[train_df['Height'] == train_df['Height'].max()]['ImageId']))[0]\nplt.imshow(mpimg.imread(f'/kaggle/input/imaterialist-fashion-2020-fgvc7/train/{max_height}.jpg'))\nplt.grid(False)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Image with minimum width"},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize = (70,7))\nmin_width = list(set(train_df[train_df['Width'] == train_df['Width'].min()]['ImageId']))[0]\nplt.imshow(mpimg.imread(f'/kaggle/input/imaterialist-fashion-2020-fgvc7/train/{min_width}.jpg'))\nplt.grid(False)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Image with maximum width"},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize = (70,7))\nmax_width = list(set(train_df[train_df['Width'] == train_df['Width'].max()]['ImageId']))[0]\nplt.imshow(mpimg.imread(f'/kaggle/input/imaterialist-fashion-2020-fgvc7/train/{max_width}.jpg'))\nplt.grid(False)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"area_df = pd.DataFrame()\narea_df['ImageId'] = train_df['ImageId']\narea_df['area'] = train_df['Height'] * train_df['Width']\nmin_area = list(set(area_df[area_df['area'] == area_df['area'].min()]['ImageId']))[0]\nmax_area = list(set(area_df[area_df['area'] == area_df['area'].max()]['ImageId']))[0]","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Image with minimum area"},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize = (70,7))\nplt.imshow(mpimg.imread(f'/kaggle/input/imaterialist-fashion-2020-fgvc7/train/{min_area}.jpg'))\nplt.grid(False)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Image with maximum area"},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize = (70,7))\nplt.imshow(mpimg.imread(f'/kaggle/input/imaterialist-fashion-2020-fgvc7/train/{max_area}.jpg'))\nplt.grid(False)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Details about Classes and Attributes"},{"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"},{"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"},{"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            splitted_pixels = list(map(int, pixel_str.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        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    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_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"},{"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":{},"cell_type":"markdown","source":"So there are 46 categories (classes) and 294 attributes. Let's see some of the categories and attributes"},{"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":{},"cell_type":"markdown","source":"### Let's see the class wise distribution of segments in training dataset"},{"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":{},"cell_type":"markdown","source":"### Now let's visualize an image with all its classes and attributes"},{"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":{},"cell_type":"markdown","source":"From above table, this image has 8 segmentes and a few attributes. Let's visualize all of them!"},{"metadata":{},"cell_type":"markdown","source":"## Let's first the plot the plain image"},{"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"},{"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 "},{"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\""},{"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\""},{"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\""},{"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\""},{"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\""},{"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\""},{"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\""},{"metadata":{"trusted":true},"cell_type":"code","source":"plot_individual_segment(masks[6], image=image)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Some of the segments have no attributes. Let's check how many such segment exists in training dataset."},{"metadata":{},"cell_type":"markdown","source":"Let's check of missing values in training dataset for columns other than \"AttributeIds\""},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df[['ImageId', 'EncodedPixels', 'Height', 'Width', 'ClassId']].isna().sum()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Data Preparation and modeling"},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.head()","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":{"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}