{"cells":[{"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 in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nfrom tqdm.auto import tqdm\nfrom glob import glob\nimport time, gc\nimport cv2\n\nfrom tensorflow import keras\nimport matplotlib.image as mpimg\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Model\nfrom keras.models import clone_model\nfrom keras.layers import Dense,Conv2D,Flatten,MaxPool2D,Dropout,BatchNormalization, Input\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ReduceLROnPlateau\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\nimport PIL.Image as Image, PIL.ImageDraw as ImageDraw, PIL.ImageFont as ImageFont\nfrom matplotlib import pyplot as plt\nimport seaborn as sns\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":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"train_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":"Image processing"},{"metadata":{"trusted":true},"cell_type":"code","source":"def bbox(img):\n    rows = np.any(img, axis=1)\n    cols = np.any(img, axis=0)\n    rmin, rmax = np.where(rows)[0][[0, -1]]\n    cmin, cmax = np.where(cols)[0][[0, -1]]\n    return rmin, rmax, cmin, cmax\n\ndef crop_resize(df, size=64, pad=16):\n    resized = {}\n    #crop a box around pixels large than the threshold \n    #some images contain line at the sides\n    for i in tqdm(range(df.shape[0])):\n        #somehow the original input is inverted\n        img0 = 255 - df.loc[df.index[i]].values.reshape(137, 236).astype(np.uint8)\n        #normalize each image by its max val\n        img0 = (img0*(255.0/img0.max())).astype(np.uint8)\n        \n        _, thresh = cv2.threshold(img0,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)\n        ymin,ymax,xmin,xmax = bbox(thresh[5:-5,5:-5] > 80)\n        #cropping may cut too much, so we need to add it back\n        xmin = xmin - 13 if (xmin > 13) else 0\n        ymin = ymin - 10 if (ymin > 10) else 0\n        xmax = xmax + 13 if (xmax < WIDTH - 13) else WIDTH\n        ymax = ymax + 10 if (ymax < HEIGHT - 10) else HEIGHT\n        img = img0[ymin:ymax,xmin:xmax]\n        #remove lo intensity pixels as noise\n        img[img < 28] = 0\n        lx, ly = xmax-xmin,ymax-ymin\n        l = max(lx,ly) + pad\n        #make sure that the aspect ratio is kept in rescaling\n        img = np.pad(img, [((l-ly)//2,), ((l-lx)//2,)], mode='constant')\n        resized_roi = cv2.resize(img, (size, size),interpolation=cv2.INTER_AREA)\n        resized[df.index[i]] = resized_roi.reshape(-1)\n    resized = pd.DataFrame(resized).T\n    return resized\n\n\ndef get_dummies(df):\n    cols = []\n    for col in df:\n        cols.append(pd.get_dummies(df[col].astype(str)))\n    return pd.concat(cols, axis=1)\n\nclass 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\n            \n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Build Model"},{"metadata":{"trusted":true},"cell_type":"code","source":"def Basic_Model():\n    inputs = Input(shape = (IMG_SIZE, IMG_SIZE, 1))\n\n    model = Conv2D(filters=64, kernel_size=(3, 3), padding='SAME', activation='relu', input_shape=(IMG_SIZE, IMG_SIZE, 1), kernel_initializer='glorot_normal')(inputs)\n    model = Conv2D(filters=64, kernel_size=(3, 3), padding='SAME', activation='relu',  kernel_initializer='glorot_normal',)(model)\n#    model = Conv2D(filters=64, kernel_size=(3, 3), padding='SAME', activation='relu',  kernel_initializer='glorot_normal',)(model)\n    model = BatchNormalization(momentum=0.15)(model)\n    model = MaxPool2D(pool_size=(2, 2))(model)\n    model = Conv2D(filters=64, kernel_size=(5, 5), padding='SAME', activation='relu',  kernel_initializer='glorot_normal',)(model)\n    model = Dropout(rate=0.3)(model)\n    \n    model = Conv2D(filters=128, kernel_size=(3, 3), padding='SAME', activation='relu',  kernel_initializer='glorot_normal',)(model)\n    model = Conv2D(filters=128, kernel_size=(3, 3), padding='SAME', activation='relu',  kernel_initializer='glorot_normal',)(model)\n    model = BatchNormalization(momentum=0.15)(model)\n    model = MaxPool2D(pool_size=(2, 2))(model)\n    model = Conv2D(filters=128, kernel_size=(5, 5), padding='SAME', activation='relu',  kernel_initializer='glorot_normal',)(model)\n    model = BatchNormalization(momentum=0.15)(model)\n    model = Dropout(rate=0.3)(model)\n    \n#    model = Conv2D(filters=128, kernel_size=(3, 3), padding='SAME', activation='relu', kernel_initializer='glorot_normal',)(model)\n#    model = Conv2D(filters=128, kernel_size=(3, 3), padding='SAME', activation='relu', kernel_initializer='glorot_normal',)(model)\n#    model = Conv2D(filters=128, kernel_size=(3, 3), padding='SAME', activation='relu', kernel_initializer='glorot_normal',)(model)\n#    model = Conv2D(filters=128, kernel_size=(3, 3), padding='SAME', activation='relu', kernel_initializer='glorot_normal',)(model)\n#    model = BatchNormalization(momentum=0.15)(model)\n#    model = MaxPool2D(pool_size=(2, 2))(model)\n#    model = Conv2D(filters=128, kernel_size=(5, 5), padding='SAME', activation='relu', kernel_initializer='glorot_normal',)(model)\n#    model = BatchNormalization(momentum=0.15)(model)\n#    model = Dropout(rate=0.3)(model)\n    \n    model = Conv2D(filters=256, kernel_size=(3, 3), padding='SAME', activation='relu',  kernel_initializer='glorot_normal',)(model)\n    model = Conv2D(filters=256, kernel_size=(3, 3), padding='SAME', activation='relu', kernel_initializer='glorot_normal', )(model)\n    model = BatchNormalization(momentum=0.15)(model)\n    model = MaxPool2D(pool_size=(2, 2))(model)\n    model = Conv2D(filters=256, kernel_size=(5, 5), padding='SAME', activation='relu', kernel_initializer='glorot_normal',)(model)\n    model = BatchNormalization(momentum=0.15)(model)\n    model = Dropout(rate=0.3)(model)\n    \n    #root model\n    root_model = Conv2D(filters=256, kernel_size=(3, 3), padding='SAME', activation='elu',  kernel_initializer='glorot_normal',)(model)\n    root_model = MaxPool2D(pool_size=(2, 2))(root_model)\n    root_model = Dropout(rate=0.2)(root_model)\n\n    root_model = Flatten()(root_model) \n    root_model = Dense(1024, activation = \"elu\")(root_model)\n    root_model = BatchNormalization(momentum=0.15)(root_model)\n    root_model = Dropout(rate=0.2)(root_model)\n    root_model = Dense(512, activation = \"elu\")(root_model)\n    root_model = BatchNormalization(momentum=0.15)(root_model)\n    root_model = Dropout(rate=0.1)(root_model)\n    root_dense = Dense(256, activation = \"elu\")(root_model)\n        \n    #others \n    model = Flatten()(model)\n    model = Dense(1024, activation = \"elu\")(model)\n    model = Dropout(rate=0.3)(model)\n    dense = Dense(512, activation = \"elu\")(model)\n    \n    \n    head_root = Dense(168, activation = 'softmax',name='dense_23')(root_dense)\n    head_vowel = Dense(11, activation = 'softmax',name='dense_24')(dense)\n    head_consonant = Dense(7, activation = 'softmax',name='dense_25')(dense)\n    \n    model = Model(inputs=inputs, outputs=[head_root, head_vowel, head_consonant])\n    model.compile(optimizer='Adam', loss='categorical_crossentropy', metrics=['accuracy'])\n    \n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Set a learning rate annealer. Learning rate will be half after 3 epochs if accuracy is not increased\nlearning_rate_reduction_root = ReduceLROnPlateau(monitor='dense_23_accuracy', \n                                            patience=3, \n                                            verbose=1,\n                                            factor=0.5, \n                                            min_lr=0.00001)\nlearning_rate_reduction_vowel = ReduceLROnPlateau(monitor='dense_24_accuracy', \n                                            patience=3, \n                                            verbose=1,\n                                            factor=0.5, \n                                            min_lr=0.00001)\nlearning_rate_reduction_consonant = ReduceLROnPlateau(monitor='dense_25_accuracy', \n                                            patience=3, \n                                            verbose=1,\n                                            factor=0.5, \n                                            min_lr=0.00001)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Training loop"},{"metadata":{"trusted":true},"cell_type":"code","source":"import datetime\nIMG_SIZE=64\nN_CHANNELS=1\nHEIGHT = 137\nWIDTH = 236\nbatch_size = 256\nepochs = 28\n\nhistories = []\nmodel = Basic_Model()\nfor i in range(4):\n    start = datetime.datetime.now()\n    train_df = pd.merge(pd.read_parquet(f'/kaggle/input/bengaliai-cv19/train_image_data_{i}.parquet'), train_df_, on='image_id').drop(['image_id'], axis=1)\n    X_train = train_df.drop(['grapheme_root', 'vowel_diacritic', 'consonant_diacritic','grapheme'], axis=1)\n    X_train = crop_resize(X_train)/255\n    \n    X_train = X_train.values.reshape(-1, IMG_SIZE, IMG_SIZE, N_CHANNELS)\n    \n    Y_train_root = pd.get_dummies(train_df['grapheme_root']).values\n    Y_train_vowel = pd.get_dummies(train_df['vowel_diacritic']).values\n    Y_train_consonant = pd.get_dummies(train_df['consonant_diacritic']).values\n\n    print(f'Training images: {X_train.shape}')\n    print(f'Training labels root: {Y_train_root.shape}')\n    print(f'Training labels vowel: {Y_train_vowel.shape}')\n    print(f'Training labels consonants: {Y_train_consonant.shape}')\n\n    # Divide the data into training and validation set\n    x_train, x_test, y_train_root, y_test_root, y_train_vowel, y_test_vowel, y_train_consonant, y_test_consonant = train_test_split(X_train, Y_train_root, Y_train_vowel, Y_train_consonant, test_size=0.08, random_state=666)\n    del train_df\n    del X_train\n    del Y_train_root, Y_train_vowel, Y_train_consonant\n\n    # Data augmentation for creating more training data\n    datagen = MultiOutputDataGenerator(\n        featurewise_center=False,  # set input mean to 0 over the dataset\n        samplewise_center=False,  # set each sample mean to 0\n        featurewise_std_normalization=False,  # divide inputs by std of the dataset\n        samplewise_std_normalization=False,  # divide each input by its std\n        zca_whitening=False,  # apply ZCA whitening\n        rotation_range=8,  # randomly rotate images in the range (degrees, 0 to 180)\n        zoom_range = 0.15, # Randomly zoom image \n        width_shift_range=0.15,  # randomly shift images horizontally (fraction of total width)\n        height_shift_range=0.15,  # randomly shift images vertically (fraction of total height)\n        horizontal_flip=False,  # randomly flip images\n        vertical_flip=False)  # randomly flip images\n\n\n    # This will just calculate parameters required to augment the given data. This won't perform any augmentations\n    datagen.fit(x_train)\n    \n    # Fit the model\n    history = model.fit_generator(datagen.flow(x_train, {'dense_23': y_train_root, 'dense_24': y_train_vowel, 'dense_25': y_train_consonant}, batch_size=batch_size),\n                              epochs = epochs, validation_data = (x_test, [y_test_root, y_test_vowel, y_test_consonant]), \n                              steps_per_epoch=x_train.shape[0] // batch_size, \n                              callbacks=[learning_rate_reduction_root, learning_rate_reduction_vowel, learning_rate_reduction_consonant])\n\n    histories.append(history)\n    end = datetime.datetime.now()\n    print ('use time'+str(end-start))\n    # Delete to reduce memory usage\n    del x_train\n    del x_test\n    del y_train_root\n    del y_test_root\n    del y_train_vowel\n    del y_test_vowel\n    del y_train_consonant\n    del y_test_consonant\n    gc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"preds_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 = crop_resize(df_test_img)/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)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.4","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}