{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import pandas as pd\nimport keras\nfrom keras.layers import Dense,Conv2D,Flatten,MaxPool2D,Dropout,BatchNormalization, Input\nfrom keras.callbacks import ReduceLROnPlateau\nfrom keras.models import Model\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom sklearn.model_selection import train_test_split\nimport cv2\nimport albumentations as A\nimport numpy as np\nimport math\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"","_uuid":"","trusted":true},"cell_type":"code","source":"# FOr parquet data \n\nBASE_URL = '/kaggle/input/bengaliaicv19feather/'\nTRAIN = ['train_image_data_0.parquet',\n         'train_image_data_1.parquet',\n         'train_image_data_2.parquet',\n         'train_image_data_3.parquet']\n\nd1 = BASE_URL+'train_image_data_1.feather'\nimageSize=64","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# FOr parquet data \n# # # this take lots of server space so commented till testing\n# dataList = []\n# for i in TRAIN:\n#     df = pd.read_parquet(BASE_URL+i)\n#     dataList.append(df) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# trainData = pd.concat(dataList)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# trainData = pd.read_parquet(BASE_URL+TRAIN[0])\ntrainData = pd.read_feather(d1)\ntrain = pd.read_csv('/kaggle/input/bengaliai-cv19/train.csv')\n# del dataList","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    if need_progress_bar:\n         for i in range(df.shape[0]):\n            image=df.loc[df.index[i]].values.reshape(137,236)\n            augBright=A.RandomBrightnessContrast(p=1.0)\n            image = augBright(image=image)['image']\n            _, thresh = cv2.threshold(image, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)\n            contours, _ = cv2.findContours(image,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            resized[df.index[i]] = resized_roi.reshape(-1)\n    else:\n        for i in range(df.shape[0]):\n            image=df.loc[df.index[i]].values.reshape(137,236)\n            augBright=A.RandomBrightnessContrast(p=1.0)\n            image = augBright(image=image)['image']\n            _, thresh = cv2.threshold(image, 0, 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            resized[df.index[i]] = resized_roi.reshape(-1)\n    resized = pd.DataFrame(resized).T\n    return resized","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"inputs = Input(shape = (imageSize, imageSize, 1))\n\nmodel = Conv2D(filters=32, kernel_size=(3, 3), padding='SAME', activation='relu', input_shape=(imageSize, imageSize, 1))(inputs)\nmodel = Conv2D(filters=32, kernel_size=(3, 3), padding='SAME', activation='relu')(model)\nmodel = Conv2D(filters=32, kernel_size=(3, 3), padding='SAME', activation='relu')(model)\nmodel = Conv2D(filters=32, kernel_size=(3, 3), padding='SAME', activation='relu')(model)\nmodel = Conv2D(filters=32, kernel_size=(3, 3), padding='SAME', activation='relu')(model)\nmodel = Conv2D(filters=32, kernel_size=(3, 3), padding='SAME', activation='relu')(model)\nmodel = BatchNormalization(momentum=0.9)(model)\nmodel = MaxPool2D(pool_size=(2, 2))(model)\nmodel = Conv2D(filters=32, kernel_size=(5, 5), padding='SAME', activation='relu')(model)\nmodel = Dropout(rate=0.3)(model)\n\nmodel = Conv2D(filters=64, kernel_size=(3, 3), padding='SAME', activation='relu')(model)\nmodel = Conv2D(filters=64, kernel_size=(3, 3), padding='SAME', activation='relu')(model)\nmodel = Conv2D(filters=64, kernel_size=(3, 3), padding='SAME', activation='relu')(model)\nmodel = Conv2D(filters=64, kernel_size=(3, 3), padding='SAME', activation='relu')(model)\nmodel = Conv2D(filters=64, kernel_size=(3, 3), padding='SAME', activation='relu')(model)\nmodel = Conv2D(filters=64, kernel_size=(3, 3), padding='SAME', activation='relu')(model)\nmodel = BatchNormalization(momentum=0.9)(model)\nmodel = MaxPool2D(pool_size=(2, 2))(model)\nmodel = Conv2D(filters=64, kernel_size=(5, 5), padding='SAME', activation='relu')(model)\nmodel = BatchNormalization(momentum=0.9)(model)\nmodel = Dropout(rate=0.3)(model)\n\nmodel = Conv2D(filters=128, kernel_size=(3, 3), padding='SAME', activation='relu')(model)\nmodel = Conv2D(filters=128, kernel_size=(3, 3), padding='SAME', activation='relu')(model)\nmodel = Conv2D(filters=128, kernel_size=(3, 3), padding='SAME', activation='relu')(model)\nmodel = Conv2D(filters=128, kernel_size=(3, 3), padding='SAME', activation='relu')(model)\nmodel = Conv2D(filters=128, kernel_size=(3, 3), padding='SAME', activation='relu')(model)\nmodel = Conv2D(filters=128, kernel_size=(3, 3), padding='SAME', activation='relu')(model)\nmodel = BatchNormalization(momentum=0.9)(model)\nmodel = MaxPool2D(pool_size=(2, 2))(model)\nmodel = Conv2D(filters=128, kernel_size=(5, 5), padding='SAME', activation='relu')(model)\nmodel = BatchNormalization(momentum=0.9)(model)\nmodel = Dropout(rate=0.3)(model)\n\nmodel = Conv2D(filters=256, kernel_size=(3, 3), padding='SAME', activation='relu')(model)\nmodel = Conv2D(filters=256, kernel_size=(3, 3), padding='SAME', activation='relu')(model)\nmodel = Conv2D(filters=256, kernel_size=(3, 3), padding='SAME', activation='relu')(model)\nmodel = Conv2D(filters=256, kernel_size=(3, 3), padding='SAME', activation='relu')(model)\nmodel = Conv2D(filters=256, kernel_size=(3, 3), padding='SAME', activation='relu')(model)\nmodel = Conv2D(filters=256, kernel_size=(3, 3), padding='SAME', activation='relu')(model)\nmodel = BatchNormalization(momentum=0.9)(model)\nmodel = MaxPool2D(pool_size=(2, 2))(model)\nmodel = Conv2D(filters=256, kernel_size=(5, 5), padding='SAME', activation='relu')(model)\nmodel = BatchNormalization(momentum=0.9)(model)\nmodel = Dropout(rate=0.3)(model)\n\nmodel = Flatten()(model)\nmodel = Dense(1024, activation = \"relu\")(model)\nmodel = Dropout(rate=0.3)(model)\ndense = Dense(512, activation = \"relu\")(model)\n\nhead_root = Dense(168, activation = 'softmax')(dense)\nhead_vowel = Dense(11, activation = 'softmax')(dense)\nhead_consonant = Dense(7, activation = 'softmax')(dense)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Model(inputs=inputs, outputs=[head_root, head_vowel, head_consonant])\nmodel.summary()","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":"lrReductionRoot = ReduceLROnPlateau(monitor='dense_3_accuracy', \n                                            patience=3, \n                                            verbose=1,\n                                            factor=0.5, \n                                            min_lr=0.00001)\nlrReductionVowel = ReduceLROnPlateau(monitor='dense_4_accuracy', \n                                            patience=3, \n                                            verbose=1,\n                                            factor=0.5, \n                                            min_lr=0.00001)\nlrReductionConsonant = ReduceLROnPlateau(monitor='dense_5_accuracy', \n                                            patience=3, \n                                            verbose=1,\n                                            factor=0.5, \n                                            min_lr=0.00001)\nlearningRate = [lrReductionRoot,lrReductionVowel,lrReductionConsonant]\n","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":{"trusted":true},"cell_type":"code","source":"trainData = pd.merge(trainData, train, on='image_id').drop(['image_id'], axis=1).drop(['grapheme'], axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"yCols = ['consonant_diacritic', 'grapheme_root', 'vowel_diacritic']\n\nxTrain = trainData.drop(yCols, axis=1)\nxTrain = 255 - resize(xTrain) / 255\nxTrain = xTrain.values.reshape(-1, imageSize, imageSize, 1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"yTrainRoot = pd.get_dummies(trainData['grapheme_root']).values\nyTrainVowel = pd.get_dummies(trainData['vowel_diacritic']).values\nyTrainConsonant = pd.get_dummies(trainData['consonant_diacritic']).values\nyTrain = [yTrainRoot,yTrainVowel,yTrainConsonant]\ndel trainData","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"imgGen = 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\nimgGen.fit(xTrain)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true},"cell_type":"code","source":"# history = model.fit_generator(imgGen.flow(xTrain, {'dense_3': yTrainRoot, 'dense_4':yTrainVowel, 'dense_5': yTrainConsonant}),epochs=30,steps_per_epoch=xTrain.shape[0],callbacks=learningRate)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit(xTrain,yTrain,epochs=50, batch_size=36,validation_split = 0.1,callbacks=learningRate)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predsDict = {\n    'grapheme_root': [],\n    'vowel_diacritic': [],\n    'consonant_diacritic': []\n}","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"components = ['consonant_diacritic', 'grapheme_root', 'vowel_diacritic']\ntarget=[]\nrowId=[]\n\nfor i in range(4):\n    testData = pd.read_parquet('/kaggle/input/bengaliai-cv19/test_image_data_{}.parquet'.format(i)) \n    testData.set_index('image_id', inplace=True)\n\n    xTest = resize(testData, need_progress_bar=False)/255\n    xTest = xTest.values.reshape(-1, imageSize, imageSize, 1)\n    \n    preds = model.predict(xTest)\n\n    for i, p in enumerate(predsDict):\n        predsDict[p] = np.argmax(preds[i], axis=1)\n\n    for k,id in enumerate(testData.index.values):  \n        for i,comp in enumerate(components):\n            idSample=id+'_'+comp\n            rowId.append(idSample)\n            target.append(predsDict[comp][k])\n\n\n    del testData\n    del xTest\n\nsampleData = pd.DataFrame(\n    {\n        'row_id': rowId,\n        'target':target\n    },\n    columns = ['row_id','target'] \n)\nsampleData.to_csv('submission.csv',index=False)\n","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"","_uuid":"","trusted":true},"cell_type":"code","source":"sampleData.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}