{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Bengali.AI albumentations data augmentation tutorial\n\nFor CNN training, data augmentation is important to improve test accuracy (generalization performance). I will show some image preprocessing to increase the data variety.<br>\n**albumentations** library, *fast image augmentation library and easy to use wrapper around other libraries*, can be used for many kinds of data augmentation.\n\nI will introduce several methods, especially useful for this competition.\n\nReference\n - https://github.com/albumentations-team/albumentations\n - https://arxiv.org/abs/1809.06839"},{"metadata":{},"cell_type":"markdown","source":"# Table of Contents:\n**[Fast data loading with feather](#load)**<br>\n**[Dataset](#dataset)**<br>\n**[How to apply albumentations augmentations](#apply)**<br>\n**[Blur Related Methods](#blur)**<br>\n**[Noise Related Methods](#noise)**<br>\n**[Cutout Related Methods](#cutout)**<br>\n**[Distortion Related Methods](#distortion)**<br>\n**[Brightness, contrast Related Methods](#brightness)**<br>\n**[Affine Related Methods](#affine)**<br>\n**[Reference and further reading](#ref)**<br>"},{"metadata":{"_kg_hide-input":true,"trusted":true,"_kg_hide-output":true},"cell_type":"code","source":"import gc\nimport os\nfrom pathlib import Path\nimport random\nimport sys\n\nfrom tqdm.notebook import tqdm\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom IPython.core.display import display, HTML\n\n# --- plotly ---\nfrom plotly import tools, subplots\nimport plotly.offline as py\npy.init_notebook_mode(connected=True)\nimport plotly.graph_objs as go\nimport plotly.express as px\nimport plotly.figure_factory as ff\n\n# --- models ---\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import KFold\nimport lightgbm as lgb\nimport xgboost as xgb\nimport catboost as cb\n\n# --- setup ---\npd.set_option('max_columns', 50)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"_kg_hide-input":true,"_kg_hide-output":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 in \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 \"../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# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"debug=True\nsubmission=False\nbatch_size=32\ndevice='cuda:0'\nout='.'\nimage_size=64\nncol=6","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true,"_kg_hide-input":false,"_kg_hide-output":true},"cell_type":"code","source":"datadir = Path('/kaggle/input/bengaliai-cv19')\nfeatherdir = Path('/kaggle/input/bengaliaicv19feather')\noutdir = Path('.')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<a id=\"load\"></a>\n# Fast data loading with feather\n\nRefer [Bengali.AI super fast data loading with feather](https://www.kaggle.com/corochann/bengali-ai-super-fast-data-loading-with-feather) and [dataset](https://www.kaggle.com/corochann/bengaliaicv19feather) for detail.<br/>\nOriginal `parquet` format takes about 60 sec to load 1 data, while `feather` format takes about **2 sec to load 1 data!!!**\n\n### How to add dataset\n\nWhen you write kernel, click \"+ Add Data\" botton on right top.<br/>\nThen inside window pop-up, you can see \"Search Datasets\" text box on right top.<br/>\nYou can type \"bengaliai-cv19-feather\" to find this dataset and press \"Add\" botton to add the data."},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport gc\n\ndef prepare_image(datadir, featherdir, data_type='train',\n                  submission=False, indices=[0, 1, 2, 3]):\n    assert data_type in ['train', 'test']\n    if submission:\n        image_df_list = [pd.read_parquet(datadir / f'{data_type}_image_data_{i}.parquet')\n                         for i in indices]\n    else:\n        image_df_list = [pd.read_feather(featherdir / f'{data_type}_image_data_{i}.feather')\n                         for i in indices]\n\n    print('image_df_list', len(image_df_list))\n    HEIGHT = 137\n    WIDTH = 236\n    images = [df.iloc[:, 1:].values.reshape(-1, HEIGHT, WIDTH) for df in image_df_list]\n    del image_df_list\n    gc.collect()\n    images = np.concatenate(images, axis=0)\n    return images","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n\ntrain = pd.read_csv(datadir/'train.csv')\ntrain_labels = train[['grapheme_root', 'vowel_diacritic', 'consonant_diacritic']].values\nindices = [0] if debug else [0, 1, 2, 3]\ntrain_images = prepare_image(\n    datadir, featherdir, data_type='train', submission=False, indices=indices)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<a id=\"dataset\"></a>\n# Dataset"},{"metadata":{},"cell_type":"markdown","source":"This `DatasetMixin` class can be used to define any custom dataset class in pytorch. We can implement `get_example(self, i)` method to return `i`-th data.\n\nHere I return `i`-th image `x` and `label`, with scaling image to be value ranges between 0~1."},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"\"\"\"\nReferenced `chainer.dataset.DatasetMixin` to work with pytorch Dataset.\n\"\"\"\nimport numpy\nimport six\nimport torch\nfrom torch.utils.data.dataset import Dataset\n\n\nclass DatasetMixin(Dataset):\n\n    def __init__(self, transform=None):\n        self.transform = transform\n\n    def __getitem__(self, index):\n        \"\"\"Returns an example or a sequence of examples.\"\"\"\n        if torch.is_tensor(index):\n            index = index.tolist()\n        if isinstance(index, slice):\n            current, stop, step = index.indices(len(self))\n            return [self.get_example_wrapper(i) for i in\n                    six.moves.range(current, stop, step)]\n        elif isinstance(index, list) or isinstance(index, numpy.ndarray):\n            return [self.get_example_wrapper(i) for i in index]\n        else:\n            return self.get_example_wrapper(index)\n\n    def __len__(self):\n        \"\"\"Returns the number of data points.\"\"\"\n        raise NotImplementedError\n\n    def get_example_wrapper(self, i):\n        \"\"\"Wrapper of `get_example`, to apply `transform` if necessary\"\"\"\n        example = self.get_example(i)\n        if self.transform:\n            example = self.transform(example)\n        return example\n\n    def get_example(self, i):\n        \"\"\"Returns the i-th example.\n\n        Implementations should override it. It should raise :class:`IndexError`\n        if the index is invalid.\n\n        Args:\n            i (int): The index of the example.\n\n        Returns:\n            The i-th example.\n\n        \"\"\"\n        raise NotImplementedError","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"import numpy as np\n\n\nclass BengaliAIDataset(DatasetMixin):\n    def __init__(self, images, labels=None, transform=None, indices=None):\n        super(BengaliAIDataset, self).__init__(transform=transform)\n        self.images = images\n        self.labels = labels\n        if indices is None:\n            indices = np.arange(len(images))\n        self.indices = indices\n        self.train = labels is not None\n\n    def __len__(self):\n        \"\"\"return length of this dataset\"\"\"\n        return len(self.indices)\n\n    def get_example(self, i):\n        \"\"\"Return i-th data\"\"\"\n        i = self.indices[i]\n        x = self.images[i]\n        # Opposite white and black: background will be white and\n        # for future Affine transformation\n        x = (255 - x).astype(np.float32) / 255.\n        if self.train:\n            y = self.labels[i]\n            return x, y\n        else:\n            return x","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_dataset = BengaliAIDataset(train_images, train_labels)                                 ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Original data\n\nLet's see original data at first"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"nrow, ncol = 1, 6\n\nfig, axes = plt.subplots(nrow, ncol, figsize=(20, 2))\naxes = axes.flatten()\nfor i, ax in enumerate(axes):\n    image, label = train_dataset[i]\n    ax.imshow(image, cmap='Greys')\n    ax.set_title(f'label: {label}')\nplt.tight_layout()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<a id=\"apply\"></a>\n## How to apply albumentations augmentations\n\nWhen we have `image` array, we can apply albumentations augmentation by calling **`aug(image=image)['image']`**, where `aug` is various methods implemented in `albumentations`.\n\nLet's see example, I will apply `aug = A.Blur(p=1.0)`. You can see that the image is blurred from original image."},{"metadata":{"trusted":true},"cell_type":"code","source":"import albumentations as A\n\naug = A.Blur(p=1.0)\n\nnrow, ncol = 1, 6\n\nfig, axes = plt.subplots(nrow, ncol, figsize=(20, 2))\naxes = axes.flatten()\nfor i, ax in enumerate(axes):\n    image, label = train_dataset[i]\n    # I added only this 1 line!\n    image = aug(image=image)['image']\n    ax.imshow(image, cmap='Greys')\n    ax.set_title(f'label: {label}')\nplt.tight_layout()","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"def show_images(aug_dict, ncol=6):\n    nrow = len(aug_dict)\n\n    fig, axes = plt.subplots(nrow, ncol, figsize=(20, 2 * nrow), squeeze=False)\n    for i, (key, aug) in enumerate(aug_dict.items()):\n        for j in range(ncol):\n            ax = axes[i, j]\n            if j == 0:\n                ax.text(0.5, 0.5, key, horizontalalignment='center', verticalalignment='center', fontsize=15)\n                ax.get_xaxis().set_visible(False)\n                ax.get_yaxis().set_visible(False)\n                ax.axis('off')\n            else:\n                image, label = train_dataset[j-1]\n                if aug is not None:\n                    image = aug(image=image)['image']\n                ax.imshow(image, cmap='Greys')\n                ax.set_title(f'label: {label}')\n    plt.tight_layout()\n    plt.show()\n    plt.close()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Many methods are supported in albumentations, let's see each methods.<br>\nI categorized methods by section so that you can refer easily :)"},{"metadata":{},"cell_type":"markdown","source":"<a id=\"blur\"></a>\n# Blur related methods\n\n - A.Blur\n - A.MedianBlur\n - A.GaussianBlur\n - A.MotionBlur"},{"metadata":{"_kg_hide-input":false,"trusted":true},"cell_type":"code","source":"show_images({'Original': None,\n             'Blur': A.Blur(p=1.0),\n             'MedianBlur': A.MedianBlur(blur_limit=5, p=1.0),\n             'GaussianBlur': A.GaussianBlur(p=1.0),\n             'MotionBlur': A.MotionBlur(p=1.0)},\n            ncol=ncol)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<a id=\"noise\"></a>\n# Noise related methods\n\n - A.GaussNoise\n - A.MultiplicativeNoise"},{"metadata":{"trusted":true},"cell_type":"code","source":"show_images({'Original': None,\n             'GaussNoise': A.GaussNoise(var_limit=5. / 255., p=1.0),\n             'MultiplicativeNoise': A.MultiplicativeNoise(p=1.0)},\n            ncol=ncol)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<a id=\"cutout\"></a>\n# Cutout related methods\n\nIt adds square sized mask to images for data augmentation. CNN need to learn target label by \"watching\" part of the images.<br>\nRefer: https://arxiv.org/abs/1708.04552\n\n - A.Cutout <-- It is deprecated.\n - A.CoarseDropout"},{"metadata":{"trusted":true},"cell_type":"code","source":"show_images({'Original': None,\n             'Cutout':A.Cutout(num_holes=8,  max_h_size=20, max_w_size=20, p=1.0),\n             'CoarseDropout': A.CoarseDropout(max_holes=8, max_height=20, max_width=20, p=1.0)},\n            ncol=ncol)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<a id=\"distortion\"></a>\n# Distortion related methods\n\n - A.GridDistortion\n - A.ElasticTransform: Refer http://cognitivemedium.com/assets/rmnist/Simard.pdf"},{"metadata":{"trusted":true},"cell_type":"code","source":"show_images({'Original': None,\n             'GridDistortion':A.GridDistortion(p=1.0),\n             'ElasticTransform': A.ElasticTransform(sigma=50, alpha=1, alpha_affine=10, p=1.0)},\n            ncol=ncol)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<a id=\"brightness\"></a>\n# Brightness, contrast related methods\n\n - A.RandomBrightness <-- Deprecated\n - A.RandomContrast <-- Deprecated\n - A.RandomBrightnessContrast"},{"metadata":{"trusted":true},"cell_type":"code","source":"show_images({'Original': None,\n             'RandomBrightness': A.RandomBrightness(p=1.0),\n             'RandomContrast': A.RandomContrast(p=1.0),\n             'RandomBrightnessContrast': A.RandomBrightnessContrast(p=1.0)},\n            ncol=ncol)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<a id=\"affine\"></a>\n# Affine related methods\n\n - A.RandomBrightness <-- Deprecated\n - A.RandomContrast <-- Deprecated\n - A.RandomBrightnessContrast"},{"metadata":{"trusted":true},"cell_type":"code","source":"show_images({'Original': None,\n             'IAAPiecewiseAffine': A.IAAPiecewiseAffine(p=1.0),\n             'ShiftScaleRotate': A.ShiftScaleRotate(\n                shift_limit=0.0625,\n                scale_limit=0.1,\n                rotate_limit=30,\n                p=1.0)},\n            ncol=ncol)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<a id=\"ref\"></a>\n# Reference and further reading\n\nThat's all for the tutorial of this kernel. Below are the next reading contents.<br>\nEspecially, I will write training code based on this data augmentation in this kernel: **[Bengali: SEResNeXt prediction with pytorch](https://www.kaggle.com/corochann/bengali-seresnext-prediction-with-pytorch)**.\n\n#### Kernel\n\n**[Bangali.AI super fast data loading with feather](https://www.kaggle.com/corochann/bangali-ai-super-fast-data-loading-with-feather)**<br>\nSimple example of how use feather format data to load data faster.\n\n**[Bengali: SEResNeXt prediction with pytorch](https://www.kaggle.com/corochann/bengali-seresnext-prediction-with-pytorch)**<br>\n**Training code using this kernel's data augmentation, please check this too!**\n\n**[Bengali: SEResNeXt prediction with pytorch](https://www.kaggle.com/corochann/bengali-seresnext-prediction-with-pytorch)**<br>\nPrediction code of above trained model.\n\n**[Deep learning - CNN with Chainer: LB 0.99700](https://www.kaggle.com/corochann/deep-learning-cnn-with-chainer-lb-0-99700)**<br>\nData augmentation idea is based on this kernel, which achieves quite high accuracy on MNIST task.\n\n#### Dataset\n**[bengaliai-cv19-feather](https://www.kaggle.com/corochann/bengaliaicv19feather)**<br>\nFeather format dataset\n\n**[bengaliaicv19_seresnext101_32x4d](https://www.kaggle.com/corochann/bengaliaicv19-seresnext101-32x4d)**<br>\nTrained model weight\n\n**[bengaliaicv19_trainedmodels](https://www.kaggle.com/corochann/bengaliaicv19-trainedmodels)**<br>\nTrained model weight\n\n#### Library\n**https://github.com/albumentations-team/albumentations**\n\nfast image augmentation library and easy to use wrapper around other libraries https://arxiv.org/abs/1809.06839<br>\nI could not show all the methods, you can find more methods in the library, check yourself!"},{"metadata":{},"cell_type":"markdown","source":"<h3 style=\"color:red\">If this kernel helps you, please upvote to keep me motivated :)<br>Thanks!</h3>"}],"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":1}