{"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\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport keras\nfrom keras.layers import Conv2D, MaxPool2D,  \\\n    Dropout, Dense, Input, concatenate,      \\\n    GlobalAveragePooling2D, AveragePooling2D,\\\n    Flatten\nfrom keras.optimizers import Adam\nfrom keras.models import Model\n\n# Input data files are available in the read-only \"../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# You can write up to 5GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","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')\ntrain_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.head()\n","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":"import math\nimport numpy as np\nimport h5py\nimport matplotlib.pyplot as plt\nimport scipy\nfrom PIL import Image\nfrom scipy import ndimage\nimport tensorflow as tf\nfrom tensorflow.python.framework import ops\nfrom tqdm.auto import tqdm\nfrom glob import glob\nimport time, gc\nimport cv2\n\n\n%matplotlib inline\nnp.random.seed(1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_grapheme_root=train_df[\"grapheme_root\"]\ny_vowel_diacritic=train_df[\"vowel_diacritic\"]\ny_cons_diacritic=train_df[\"consonant_diacritic\"]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def convert_to_one_hot(Y, C):\n    Y = np.eye(C)[np.reshape(Y,-1)]\n    return Y","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Y_root = convert_to_one_hot(y_grapheme_root, y_grapheme_root.max()+1).T\nY_cons = convert_to_one_hot(y_cons_diacritic,y_cons_diacritic.max()+1).T\nY_vowel = convert_to_one_hot(y_vowel_diacritic, y_vowel_diacritic.max()+1).T","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"IMG_SIZE=64\nN_CHANNELS=1","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"kernel_init = keras.initializers.glorot_uniform()\nbias_init = keras.initializers.Constant(value=0.2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def inception_module(X,filters,stage,block):\n    conv_name_base = 'inception' + str(stage) + block + '_branch'\n    #bn_name_base = 'bn' + str(stage) + block + '_branch'\n    \n    # Retrieve Filters\n    F1x1, F3x3_reduce, F3x3, F5x5_reduce, F5x5, F_pool_project  = filters\n    \n    conv_1x1=Conv2D( F1x1, (1, 1), padding='same', activation='relu', name = conv_name_base + '2a')(X)\n    \n    conv_3x3_reduce= Conv2D( F3x3_reduce, (1, 1), padding='same', activation='relu')(X)\n    conv_3x3= Conv2D( F3x3, (3, 3), padding='same', activation='relu', name = conv_name_base + '2b')(conv_3x3_reduce)\n    \n    conv_5x5_reduce= Conv2D( F5x5_reduce, (1, 1), padding='same', activation='relu')(X)\n    conv_5x5= Conv2D( F5x5, (5, 5), padding='same', activation='relu', name = conv_name_base + '2c')(conv_5x5_reduce)\n    \n    pool_proj = MaxPool2D((3, 3), strides=(1, 1), padding='same')(X)\n    pool_proj = Conv2D(F_pool_project, (1, 1), padding='same', activation='relu', name = conv_name_base + '2d')(pool_proj)\n    \n    output=concatenate([conv_1x1,conv_3x3, conv_5x5, pool_proj ],  axis=3)\n    print(output.shape)\n    \n    return output\n    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def GoogleNet(input_shape = (IMG_SIZE, IMG_SIZE, 1), classes = 6):\n    \"\"\"\n    Implementation of the popular ResNet50 the following architecture:\n    CONV2D -> BATCHNORM -> RELU -> MAXPOOL -> CONVBLOCK -> IDBLOCK*2 -> CONVBLOCK -> IDBLOCK*3\n    -> CONVBLOCK -> IDBLOCK*5 -> CONVBLOCK -> IDBLOCK*2 -> AVGPOOL -> TOPLAYER\n\n    Arguments:\n    input_shape -- shape of the images of the dataset\n    classes -- integer, number of classes\n\n    Returns:\n    model -- a Model() instance in Keras\n    \"\"\"\n    \n    # Define the input as a tensor with shape input_shape\n    X_input = Input(input_shape)\n    \n    x = Conv2D(64, (7, 7), padding='same', strides=(2, 2), activation='relu', name='conv_1_7x7/2')(X_input)\n    x = MaxPool2D((3, 3), padding='same', strides=(2, 2), name='max_pool_1_3x3/2')(x)\n    x = Conv2D(64, (1, 1), padding='same', strides=(1, 1), activation='relu', name='conv_2a_3x3/1')(x)\n    x = Conv2D(192, (3, 3), padding='same', strides=(1, 1), activation='relu', name='conv_2b_3x3/1')(x)\n    x = MaxPool2D((3, 3), padding='same', strides=(2, 2), name='max_pool_2_3x3/2')(x)\n\n    \n    x = inception_module(x,[64,96,128,16,32,32],stage=1,block='a')\n    \n    x = inception_module(x,[128,128,192,32,96,64],stage=1,block='b')\n    \n    x = MaxPool2D((3, 3), padding='same', strides=(2, 2), name='max_pool_3_3x3/2')(x)\n    \n    x = inception_module(x,[192,96,208,16,58,64],stage=1,block='c')\n    \n    '''\n    \n    x1 = AveragePooling2D((5, 5), strides=3)(x)\n    x1 = Conv2D(128, (1, 1), padding='same', activation='relu')(x1)\n    x1 = Flatten()(x1)\n    x1 = Dense(1024, activation='relu')(x1)\n    x1 = Dropout(0.7)(x1)\n    x1_head_root = Dense(classes[0], activation='softmax', name='auxilliary_output_1' + str(classes[0]))(x1)\n    x1_head_cons = Dense(classes[1], activation='softmax', name='auxilliary_output_1' + str(classes[1]))(x1)\n    x1_head_vowel = Dense(classes[2], activation='softmax', name='auxilliary_output_1' + str(classes[2]))(x1)\n    '''\n    \n    \n    x = inception_module(x,[160,112,224,24,64,64],stage=2,block='a')\n    x = inception_module(x,[128,128,256,24,64,64],stage=2,block='b')\n    x = inception_module(x,[112,144,288,32,64,64],stage=2,block='c')\n    \n    '''\n    x2 = AveragePooling2D((5, 5), strides=3)(x)\n    x2 = Conv2D(128, (1, 1), padding='same', activation='relu')(x2)\n    x2 = Flatten()(x2)\n    x2 = Dense(1024, activation='relu')(x2)\n    x2 = Dropout(0.7)(x2)\n    x2_head_root = Dense(classes[0], activation='softmax', name='auxilliary_output_2' + str(classes[0]))(x2)\n    x2_head_cons = Dense(classes[1], activation='softmax', name='auxilliary_output_2' + str(classes[1]))(x2)\n    x2_head_vowel = Dense(classes[2], activation='softmax', name='auxilliary_output_2' + str(classes[2]))(x2)\n    \n    '''\n    \n    x = inception_module(x,[256,160,320,32,128,128],stage=3,block='a')\n    x = MaxPool2D((3, 3), padding='same', strides=(2, 2), name='max_pool_4_3x3/2')(x)\n    x = inception_module(x,[256,160,320,32,128,128],stage=3,block='b')\n    x = inception_module(x,[384,192,384,48,128,128],stage=3,block='c')\n    \n    x = GlobalAveragePooling2D(name='avg_pool_5_3x3/1')(x)\n\n    x = Dropout(0.4)(x)\n\n    head_root = Dense(classes[0], activation='softmax', name='fc' + str(classes[0]))(x)\n    head_cons = Dense(classes[1], activation='softmax', name='fc' + str(classes[1]))(x)\n    head_vowel = Dense(classes[2], activation='softmax', name='fc' + str(classes[2]))(x)\n                     \n    \n    # Create model\n    model = Model(inputs = X_input, outputs = [head_root, head_vowel, head_cons], name='ResNet50')\n\n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = GoogleNet(input_shape = (IMG_SIZE, IMG_SIZE, 1), classes = [168,11,7])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import math \nfrom keras.optimizers import SGD \n\ninitial_lrate = 0.01\nsgd = SGD(lr=initial_lrate, momentum=0.9, nesterov=False)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(optimizer=sgd, loss='categorical_crossentropy', metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"batch_size = 256\nepochs = 25","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"HEIGHT = 137\nWIDTH = 236\nSIZE = 128","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Y_root=Y_root.T\nY_cons =Y_cons.T\nY_vowel=Y_vowel.T\ndef resize(df, size=64, need_progress_bar=True):\n    resized = {}\n    resize_size=64\n    if need_progress_bar:\n        for i in tqdm(range(df.shape[0])):\n            image=df.loc[df.index[i]].values.reshape(137,236)\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            resized[df.index[i]] = resized_roi.reshape(-1)\n    else:\n        for i in range(df.shape[0]):\n            #image = cv2.resize(df.loc[df.index[i]].values.reshape(137,236),(size,size),None,fx=0.5,fy=0.5,interpolation=cv2.INTER_AREA)\n            image=df.loc[df.index[i]].values.reshape(137,236)\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            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":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for i in range(4):\n    train_df_=pd.DataFrame()\n    train_df_= pd.merge(pd.read_parquet(f'/kaggle/input/bengaliai-cv19/train_image_data_{i}.parquet'), train_df, on='image_id')\n    print(train_df_.shape)\n    X_train = train_df_.drop(['image_id','grapheme_root', 'vowel_diacritic', 'consonant_diacritic','grapheme'], axis=1)\n    X_train=resize(X_train)/255\n    print(X_train.shape)\n    X_train = X_train.values.reshape(-1, IMG_SIZE, IMG_SIZE, N_CHANNELS)\n    print(X_train.shape)\n    model.fit(X_train,{'fc168': Y_root[i*50210:(i+1)*50210,:], 'fc11': Y_vowel[i*50210:(i+1)*50210,:], 'fc7': Y_cons[i*50210:(i+1)*50210,:]},batch_size=batch_size,epochs = epochs)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"del train_df,Y_root,Y_cons ,Y_vowel\nprint(train_df_.shape)\ndel train_df_","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"preds_dict = {  \n    'grapheme_root': [],\n    'vowel_diacritic': [],\n    'consonant_diacritic': []\n}\ncomponents = ['consonant_diacritic', 'grapheme_root', 'vowel_diacritic']\ntarget=[] # model predictions placeholder\nrow_id=[] # row_id place holder","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for i in range(4):\n    test_df_= pd.read_parquet('/kaggle/input/bengaliai-cv19/test_image_data_{}.parquet'.format(i)) \n    test_df_.set_index('image_id', inplace=True)\n    X_test=resize(test_df_)/255\n    print(X_test.shape)\n    X_test = X_test.values.reshape(-1, IMG_SIZE, IMG_SIZE, N_CHANNELS)\n    print(X_test.shape)\n    preds=model.predict(X_test)\n    #print(preds)\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(test_df_.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])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_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":{"trusted":true},"cell_type":"code","source":"","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}