{"cells":[{"metadata":{},"cell_type":"markdown","source":"# MLiPioneers BengaliAI Model (no augmentation)\n\n## Submission Notebook"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load \n\nimport warnings\nwarnings.filterwarnings(action='ignore')\n\nimport cv2 # image processing\nimport time, gc\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nfrom glob import glob\nfrom tqdm.auto import tqdm\nimport albumentations as A\n\n# deep learning frameworks\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom keras.models import Model\nfrom keras.optimizers import Adam\nfrom keras.models import clone_model\nfrom keras.utils.vis_utils import plot_model\nfrom keras.callbacks import ReduceLROnPlateau\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.layers import Dense,Conv2D,Flatten,MaxPool2D,Dropout,BatchNormalization, Input,Reshape,Concatenate, concatenate,GaussianDropout \n\n\n# data visualization/serialization packages\nimport pickle\nimport seaborn as sns\nimport matplotlib.image as mpimg\nfrom matplotlib import pyplot as plt\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.model_selection import train_test_split\nimport PIL.Image as Image, PIL.ImageDraw as ImageDraw, PIL.ImageFont as ImageFont\n\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\ntrain_df_ = pd.read_csv('/kaggle/input/bengaliai-cv19/train.csv')\ntest_df_ = pd.read_csv('/kaggle/input/bengaliai-cv19/test.csv')\nclass_map_df = pd.read_csv('/kaggle/input/bengaliai-cv19/class_map.csv')\nsample_sub_df = pd.read_csv('/kaggle/input/bengaliai-cv19/sample_submission.csv')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Prepare Data"},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"IMG_SIZE=64\nN_CHANNELS=1\nHEIGHT = 137\nWIDTH = 236\nSIZE = 64\nCROP_SIZE = 64","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def resize(df, size=64, need_progress_bar=True):\n    resized = {}\n    resize_size=64\n    angle=0\n    if need_progress_bar:\n        for i in tqdm(range(df.shape[0])):\n            #Reshape\n            image=df.loc[df.index[i]].values.reshape(137,236)\n            \n            #Centering\n            image_center = tuple(np.array(image.shape[1::-1]) / 2)\n            matrix = cv2.getRotationMatrix2D(image_center, angle, 1.0)\n            image = cv2.warpAffine(image, matrix, image.shape[1::-1], flags=cv2.INTER_LINEAR,\n                            borderMode=cv2.BORDER_CONSTANT, borderValue=(0, 0, 0))\n            \n            #Scaling\n            matrix = cv2.getRotationMatrix2D(image_center, 0, 1.0)\n            image = cv2.warpAffine(image, matrix, image.shape[1::-1], flags=cv2.INTER_LINEAR,\n                            borderMode=cv2.BORDER_CONSTANT, borderValue=(0, 0, 0))\n            \n            #Threshold and Contours\n            _, thresh = cv2.threshold(image, 30, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)\n            contours, _ = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)[-2:]\n\n            idx = 0 \n            ls_xmin = []\n            ls_ymin = []\n            ls_xmax = []\n            ls_ymax = []\n            for cnt in contours:\n                idx += 1\n                x,y,w,h = cv2.boundingRect(cnt)\n                ls_xmin.append(x)\n                ls_ymin.append(y)\n                ls_xmax.append(x + w)\n                ls_ymax.append(y + h)\n            xmin = min(ls_xmin)\n            ymin = min(ls_ymin)\n            xmax = max(ls_xmax)\n            ymax = max(ls_ymax)\n\n            roi = image[ymin:ymax,xmin:xmax]\n            resized_roi = cv2.resize(roi, (resize_size, resize_size),interpolation=cv2.INTER_AREA)\n\n            resized[df.index[i]] = resized_roi.reshape(-1)\n        \n    else:\n        for i in range(df.shape[0]):\n            #Reshape\n            image=df.loc[df.index[i]].values.reshape(137,236)\n            \n            #Centering\n            image_center = tuple(np.array(image.shape[1::-1]) / 2)\n            matrix = cv2.getRotationMatrix2D(image_center, angle, 1.0)\n            image = cv2.warpAffine(image, matrix, image.shape[1::-1], flags=cv2.INTER_LINEAR,\n                            borderMode=cv2.BORDER_CONSTANT, borderValue=(0, 0, 0))\n            \n            #Scaling\n            matrix = cv2.getRotationMatrix2D(image_center, 0, 1.0)\n            image = cv2.warpAffine(image, matrix, image.shape[1::-1], flags=cv2.INTER_LINEAR,\n                            borderMode=cv2.BORDER_CONSTANT, borderValue=(0, 0, 0))\n            \n            #Threshold and Contours\n            _, thresh = cv2.threshold(image, 30, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)\n            contours, _ = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)[-2:]\n\n            idx = 0 \n            ls_xmin = []\n            ls_ymin = []\n            ls_xmax = []\n            ls_ymax = []\n            for cnt in contours:\n                idx += 1\n                x,y,w,h = cv2.boundingRect(cnt)\n                ls_xmin.append(x)\n                ls_ymin.append(y)\n                ls_xmax.append(x + w)\n                ls_ymax.append(y + h)\n            xmin = min(ls_xmin)\n            ymin = min(ls_ymin)\n            xmax = max(ls_xmax)\n            ymax = max(ls_ymax)\n\n            roi = image[ymin:ymax,xmin:xmax]\n            resized_roi = cv2.resize(roi, (resize_size, resize_size),interpolation=cv2.INTER_AREA)\n\n            resized[df.index[i]] = resized_roi.reshape(-1)\n            \n    resized = pd.DataFrame(resized).T\n    return resized","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Model Architecture"},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.applications import Xception\n\n# load the model\ninputs = Input(shape = (IMG_SIZE, IMG_SIZE, 1))\nmodel = Conv2D(filters=3, kernel_size=(3, 3), padding='SAME', activation='relu', input_shape=(IMG_SIZE, IMG_SIZE, 1))(inputs)\nmodel = BatchNormalization(momentum=0.15)(model)\nmodel = GaussianDropout(rate=0.3)(model)\nfmodel = Conv2D(filters=3, kernel_size=(3, 3), padding='SAME', activation='relu')(model)\nfmodel = BatchNormalization(momentum=0.15)(fmodel)\n\n# Pretrained model\nbase_model = Xception(weights=None, include_top=False)(fmodel)\n\nmodel = BatchNormalization(momentum=0.15)(base_model)\nmodel = GaussianDropout(rate=0.3)(model)\nmodel = Flatten()(base_model)\n\nmodel = Dense(1024, activation = \"relu\")(model)\nmodel = BatchNormalization(momentum=0.15)(model)\nmodel = GaussianDropout(rate=0.3)(model)\ndense = Dense(512, activation = \"relu\")(model)\ndense = BatchNormalization(momentum=0.15)(dense)\nhead_root = Dense(168, activation = 'softmax')(dense)\n\nhead_root = Dense(168, activation = 'softmax')(dense)\nhead_vowel = Dense(11, activation = 'softmax')(dense)\nhead_consonant = Dense(7, activation = 'softmax')(dense)\n\nmodel = Model(inputs=inputs, outputs=[head_root, head_vowel, head_consonant])\n    \nplot_model(model, to_file='model_plot.png', show_shapes=True, show_layer_names=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class MultiOutputDataGenerator(keras.preprocessing.image.ImageDataGenerator):\n\n    def flow(self,\n             x,\n             y=None,\n             batch_size=32,\n             shuffle=True,\n             sample_weight=None,\n             seed=None,\n             save_to_dir=None,\n             save_prefix='',\n             save_format='png',\n             subset=None):\n\n        targets = None\n        target_lengths = {}\n        ordered_outputs = []\n        for output, target in y.items():\n            if targets is None:\n                targets = target\n            else:\n                targets = np.concatenate((targets, target), axis=1)\n            target_lengths[output] = target.shape[1]\n            ordered_outputs.append(output)\n\n\n        for flowx, flowy in super().flow(x, targets, batch_size=batch_size,\n                                         shuffle=shuffle):\n            target_dict = {}\n            i = 0\n            for output in ordered_outputs:\n                target_length = target_lengths[output]\n                target_dict[output] = flowy[:, i: i + target_length]\n                i += target_length\n\n            yield flowx, target_dict","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Model Evaluation"},{"metadata":{"trusted":true},"cell_type":"code","source":"model.load_weights(\"/kaggle/input/bengaliainoaugxceptionnet/model_noaug_v1.h5\")\n\npreds_dict = {\n    'grapheme_root': [],\n    'vowel_diacritic': [],\n    'consonant_diacritic': []\n}\n\ncomponents = ['consonant_diacritic', 'grapheme_root', 'vowel_diacritic']\ntarget=[] # model predictions placeholder\nrow_id=[] # row_id place holder\nfor i in range(4):\n    df_test_img = pd.read_parquet('/kaggle/input/bengaliai-cv19/test_image_data_{}.parquet'.format(i)) \n    df_test_img.set_index('image_id', inplace=True)\n\n    X_test = resize(df_test_img, need_progress_bar=False)/255\n    X_test = X_test.values.reshape(-1, IMG_SIZE, IMG_SIZE, N_CHANNELS)\n    \n    preds = model.predict(X_test)\n\n    for i, p in enumerate(preds_dict):\n        preds_dict[p] = np.argmax(preds[i], axis=1)\n\n    for k,id in enumerate(df_test_img.index.values):  \n        for i,comp in enumerate(components):\n            id_sample=id+'_'+comp\n            row_id.append(id_sample)\n            target.append(preds_dict[comp][k])\n    del df_test_img\n    del X_test\n    gc.collect()\n\ndf_sample = pd.DataFrame(\n    {\n        'row_id': row_id,\n        'target':target\n    },\n    columns = ['row_id','target'] \n)\ndf_sample.to_csv('submission.csv',index=False)\ndf_sample.head()","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}