{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install -U tensorflow","execution_count":null,"outputs":[]},{"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\nimport tensorflow as tf\nimport matplotlib.image as mpimg\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":{"trusted":true},"cell_type":"code","source":"print(tf.__version__)","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":{"trusted":true},"cell_type":"code","source":"train_df_.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df_.head()","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":"class_map_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(f'Size of training data: {train_df_.shape}')\nprint(f'Size of test data: {test_df_.shape}')\nprint(f'Size of class map: {class_map_df.shape}')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Exploratory Data Analysis\nExploratory data analysis (EDA) is an approach to analyzing data sets to summarize their main characteristics, often with visual methods."},{"metadata":{"trusted":true},"cell_type":"code","source":"HEIGHT = 236\nWIDTH = 236\n\ndef get_n(df, field, n, top=True):\n    top_graphemes = df.groupby([field]).size().reset_index(name='counts')['counts'].sort_values(ascending=not top)[:n]\n    top_grapheme_roots = top_graphemes.index\n    top_grapheme_counts = top_graphemes.values\n    top_graphemes = class_map_df[class_map_df['component_type'] == field].reset_index().iloc[top_grapheme_roots]\n    top_graphemes.drop(['component_type', 'label'], axis=1, inplace=True)\n    top_graphemes.loc[:, 'count'] = top_grapheme_counts\n    return top_graphemes\n\ndef image_from_char(char):\n    image = Image.new('RGB', (WIDTH, HEIGHT))\n    draw = ImageDraw.Draw(image)\n    myfont = ImageFont.truetype('/kaggle/input/kalpurush-fonts/kalpurush-2.ttf', 120)\n    w, h = draw.textsize(char, font=myfont)\n    draw.text(((WIDTH - w) / 2,(HEIGHT - h) / 3), char, font=myfont)\n\n    return image","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Number of unique values"},{"metadata":{"trusted":true},"cell_type":"code","source":"print(f'Number of unique grapheme roots: {train_df_[\"grapheme_root\"].nunique()}')\nprint(f'Number of unique vowel diacritic: {train_df_[\"vowel_diacritic\"].nunique()}')\nprint(f'Number of unique consonant diacritic: {train_df_[\"consonant_diacritic\"].nunique()}')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Most used top 10 Grapheme Roots in training set"},{"metadata":{"trusted":true},"cell_type":"code","source":"top_10_roots = get_n(train_df_, 'grapheme_root', 10)\ntop_10_roots","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"f, ax = plt.subplots(2, 5, figsize=(16, 8))\nax = ax.flatten()\n\nfor i in range(10):\n    ax[i].imshow(image_from_char(top_10_roots['component'].iloc[i]), cmap='Greys')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Least used 10 Grapheme Roots in training set"},{"metadata":{"trusted":true},"cell_type":"code","source":"bottom_10_roots = get_n(train_df_, 'grapheme_root', 10, False)\nbottom_10_roots","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"f, ax = plt.subplots(2, 5, figsize=(16, 8))\nax = ax.flatten()\n\nfor i in range(10):\n    ax[i].imshow(image_from_char(bottom_10_roots['component'].iloc[i]), cmap='Greys')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Top 5 Vowel Diacritic in taining data"},{"metadata":{"trusted":true},"cell_type":"code","source":"top_5_vowels = get_n(train_df_, 'vowel_diacritic', 5)\ntop_5_vowels","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"f, ax = plt.subplots(1, 5, figsize=(16, 8))\nax = ax.flatten()\n\nfor i in range(5):\n    ax[i].imshow(image_from_char(top_5_vowels['component'].iloc[i]), cmap='Greys')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Top 5 Consonant Diacritic in training data"},{"metadata":{"trusted":true},"cell_type":"code","source":"top_5_consonants = get_n(train_df_, 'consonant_diacritic', 5)\ntop_5_consonants","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"f, ax = plt.subplots(1, 5, figsize=(16, 8))\nax = ax.flatten()\n\nfor i in range(5):\n    ax[i].imshow(image_from_char(top_5_consonants['component'].iloc[i]), cmap='Greys')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df_ = train_df_.drop(['grapheme'], axis=1, inplace=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df_[['grapheme_root', 'vowel_diacritic', 'consonant_diacritic']] = train_df_[['grapheme_root', 'vowel_diacritic', 'consonant_diacritic']].astype('uint8')","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":"def resize(df, size=IMG_SIZE, need_progress_bar=True):\n    resized = {}\n    if need_progress_bar:\n        for i in tqdm(range(df.shape[0])):\n            image = cv2.resize(df.loc[df.index[i]].values.reshape(137,236),(size, size))\n            resized[df.index[i]] = image.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))\n            resized[df.index[i]] = image.reshape(-1)\n    resized = pd.DataFrame(resized).T\n    return resized","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def 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)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Basic Model"},{"metadata":{"trusted":true},"cell_type":"code","source":"class BengaliNet:\n    @staticmethod\n    def build_grapheme_branch(inputs, numGraphemes,finalAct=\"softmax\", chanDim=-1):\n \n        x = tf.keras.layers.Conv2D(32, (3, 3), padding=\"same\")(inputs)\n        x = tf.keras.layers.Activation(\"relu\")(x)\n        x = tf.keras.layers.BatchNormalization(axis=chanDim)(x)\n        x = tf.keras.layers.MaxPooling2D(pool_size=(3, 3))(x)\n        x = tf.keras.layers.Dropout(0.25)(x)\n        \n        x = tf.keras.layers.Conv2D(64, (3, 3), padding=\"same\")(x)\n        x = tf.keras.layers.Activation(\"relu\")(x)\n        x = tf.keras.layers.BatchNormalization(axis=chanDim)(x)\n        x = tf.keras.layers.Conv2D(64, (3, 3), padding=\"same\")(x)\n        x = tf.keras.layers.Activation(\"relu\")(x)\n        x = tf.keras.layers.BatchNormalization(axis=chanDim)(x)\n        x = tf.keras.layers.MaxPooling2D(pool_size=(2, 2))(x)\n        x = tf.keras.layers.Dropout(0.25)(x)\n\n        x = tf.keras.layers.Conv2D(128, (3, 3), padding=\"same\")(x)\n        x = tf.keras.layers.Activation(\"relu\")(x)\n        x = tf.keras.layers.BatchNormalization(axis=chanDim)(x)\n        x = tf.keras.layers.Conv2D(128, (3, 3), padding=\"same\")(x)\n        x = tf.keras.layers.Activation(\"relu\")(x)\n        x = tf.keras.layers.BatchNormalization(axis=chanDim)(x)\n        x = tf.keras.layers.MaxPooling2D(pool_size=(2, 2))(x)\n        x = tf.keras.layers.Dropout(0.25)(x)\n\n        x = tf.keras.layers.Flatten()(x)\n        x = tf.keras.layers.Dense(256)(x)\n        x = tf.keras.layers.Activation(\"relu\")(x)\n        x = tf.keras.layers.BatchNormalization()(x)\n        x = tf.keras.layers.Dropout(0.5)(x)\n        x = tf.keras.layers.Dense(numGraphemes)(x)\n        x = tf.keras.layers.Activation(finalAct, name=\"grapheme_output\")(x)\n \n        # return the Grapheme prediction sub-network\n        return x\n    \n    @staticmethod\n    def build_vowel_branch(inputs, numVowels, finalAct=\"softmax\",chanDim=-1):\n\n        x = tf.keras.layers.Conv2D(32, (3, 3), padding=\"same\")(inputs)\n        x = tf.keras.layers.Activation(\"relu\")(x)\n        x = tf.keras.layers.BatchNormalization(axis=chanDim)(x)\n        x = tf.keras.layers.MaxPooling2D(pool_size=(3, 3))(x)\n        x = tf.keras.layers.Dropout(0.25)(x)\n        \n        x = tf.keras.layers.Conv2D(64, (3, 3), padding=\"same\")(x)\n        x = tf.keras.layers.Activation(\"relu\")(x)\n        x = tf.keras.layers.BatchNormalization(axis=chanDim)(x)\n        x = tf.keras.layers.Conv2D(64, (3, 3), padding=\"same\")(x)\n        x = tf.keras.layers.Activation(\"relu\")(x)\n        x = tf.keras.layers.BatchNormalization(axis=chanDim)(x)\n        x = tf.keras.layers.MaxPooling2D(pool_size=(2, 2))(x)\n        x = tf.keras.layers.Dropout(0.25)(x)\n\n        x = tf.keras.layers.Conv2D(128, (3, 3), padding=\"same\")(x)\n        x = tf.keras.layers.Activation(\"relu\")(x)\n        x = tf.keras.layers.BatchNormalization(axis=chanDim)(x)\n        x = tf.keras.layers.Conv2D(128, (3, 3), padding=\"same\")(x)\n        x = tf.keras.layers.Activation(\"relu\")(x)\n        x = tf.keras.layers.BatchNormalization(axis=chanDim)(x)\n        x = tf.keras.layers.MaxPooling2D(pool_size=(2, 2))(x)\n        x = tf.keras.layers.Dropout(0.25)(x)\n\n        x = tf.keras.layers.Flatten()(x)\n        x = tf.keras.layers.Dense(128)(x)\n        x = tf.keras.layers.Activation(\"relu\")(x)\n        x = tf.keras.layers.BatchNormalization()(x)\n        x = tf.keras.layers.Dropout(0.5)(x)\n        x = tf.keras.layers.Dense(numVowels)(x)\n        x = tf.keras.layers.Activation(finalAct, name=\"vowel_output\")(x)\n\n        # return the vowel prediction sub-network\n        return x\n    \n    @staticmethod\n    def build_consonant_branch(inputs, numConsonants, finalAct=\"softmax\",chanDim=-1):\n\n        x = tf.keras.layers.Conv2D(32, (3, 3), padding=\"same\")(inputs)\n        x = tf.keras.layers.Activation(\"relu\")(x)\n        x = tf.keras.layers.BatchNormalization(axis=chanDim)(x)\n        x = tf.keras.layers.MaxPooling2D(pool_size=(3, 3))(x)\n        x = tf.keras.layers.Dropout(0.25)(x)\n        \n        x = tf.keras.layers.Conv2D(64, (3, 3), padding=\"same\")(x)\n        x = tf.keras.layers.Activation(\"relu\")(x)\n        x = tf.keras.layers.BatchNormalization(axis=chanDim)(x)\n        x = tf.keras.layers.Conv2D(64, (3, 3), padding=\"same\")(x)\n        x = tf.keras.layers.Activation(\"relu\")(x)\n        x = tf.keras.layers.BatchNormalization(axis=chanDim)(x)\n        x = tf.keras.layers.MaxPooling2D(pool_size=(2, 2))(x)\n        x = tf.keras.layers.Dropout(0.25)(x)\n\n        x = tf.keras.layers.Conv2D(128, (3, 3), padding=\"same\")(x)\n        x = tf.keras.layers.Activation(\"relu\")(x)\n        x = tf.keras.layers.BatchNormalization(axis=chanDim)(x)\n        x = tf.keras.layers.Conv2D(128, (3, 3), padding=\"same\")(x)\n        x = tf.keras.layers.Activation(\"relu\")(x)\n        x = tf.keras.layers.BatchNormalization(axis=chanDim)(x)\n        x = tf.keras.layers.MaxPooling2D(pool_size=(2, 2))(x)\n        x = tf.keras.layers.Dropout(0.25)(x)\n\n        x = tf.keras.layers.Flatten()(x)\n        x = tf.keras.layers.Dense(128)(x)\n        x = tf.keras.layers.Activation(\"relu\")(x)\n        x = tf.keras.layers.BatchNormalization()(x)\n        x = tf.keras.layers.Dropout(0.5)(x)\n        x = tf.keras.layers.Dense(numConsonants)(x)\n        x = tf.keras.layers.Activation(finalAct, name=\"consonant_output\")(x)\n\n        # return the consonant prediction sub-network\n        return x\n    \n    @staticmethod\n    def build(width, height, numGraphemes, numVowels, numConsonants, finalAct=\"softmax\"):\n        # initialize the input shape and channel dimension (this code\n        # assumes you are using TensorFlow which utilizes channels\n        # last ordering)\n        inputShape = (height, width,1)\n        chanDim = -1\n\n        # construct both the \"grapheme\" , \"vowel\", and \"consonant\" sub-networks\n        inputs = tf.keras.layers.Input(shape=inputShape)\n        graphemeBranch = BengaliNet.build_grapheme_branch(inputs,\n            numGraphemes, finalAct=finalAct, chanDim=chanDim)\n        vowelBranch = BengaliNet.build_vowel_branch(inputs,\n            numVowels, finalAct=finalAct, chanDim=chanDim)\n        consonantBranch = BengaliNet.build_consonant_branch(inputs,\n            numConsonants, finalAct=finalAct, chanDim=chanDim)\n\n        # create the model using our input (the batch of images) and\n        # three separate outputs -- one for the grapheme\n        # branch, the vowel branch, and consonant branch respectively\n        model = tf.keras.models.Model(\n            inputs=inputs,\n            outputs=[graphemeBranch, vowelBranch, consonantBranch],\n            name=\"Bengalinet\")\n\n        # return the constructed network architecture\n        return model\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"EPOCHS = 25\nINIT_LR = 1e-3\nBS = 32","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = BengaliNet.build(64, 64,numGraphemes=168,numVowels=11,numConsonants=7,finalAct=\"softmax\")\n\n# define two dictionaries: one that specifies the loss method for\n# each output of the network along with a second dictionary that\n# specifies the weight per loss\nlosses = {\n    \"grapheme_output\": \"categorical_crossentropy\",\n    \"vowel_output\": \"categorical_crossentropy\",\n    \"consonant_output\": \"categorical_crossentropy\"\n}\nlossWeights = {\"grapheme_output\": 1.0, \"vowel_output\": 1.0, \"consonant_output\":1.0}\n\n# initialize the optimizer and compile the model\nprint(\"[INFO] compiling model...\")\nopt = tf.keras.optimizers.Adam(lr=INIT_LR, decay=INIT_LR / EPOCHS)\nmodel.compile(optimizer=opt, loss=losses, loss_weights=lossWeights,metrics=[\"accuracy\"])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Let's visualize the 3-tailed (3 output) CNN by plotting it."},{"metadata":{"trusted":true},"cell_type":"code","source":"HEIGHT = 137\nWIDTH = 236","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Training loop"},{"metadata":{"trusted":true},"cell_type":"code","source":"histories = []\nfor i in range(4):\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    \n    # Visualize few samples of current training dataset\n    fig, ax = plt.subplots(nrows=3, ncols=4, figsize=(16, 8))\n    count=0\n    for row in ax:\n        for col in row:\n            col.imshow(resize(train_df.drop(['grapheme_root', 'vowel_diacritic', 'consonant_diacritic'], axis=1).iloc[[count]], need_progress_bar=False).values.reshape(-1).reshape(IMG_SIZE, IMG_SIZE).astype(np.float64))\n            count += 1\n    plt.show()\n    \n    X_train = train_df.drop(['grapheme_root', 'vowel_diacritic', 'consonant_diacritic'], axis=1)\n    X_train = resize(X_train)\n    \n    # CNN takes images in shape `(batch_size, h, w, channels)`, so reshape the images\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    # This will just calculate parameters required to augment the given data. This won't perform any augmentations\n    print(\"train_size:\"+str(x_train.shape[0]))\n\n    # Fit the model\n    history = model.fit((x_train, {\"grapheme_output\": y_train_root, \"vowel_output\": y_train_vowel, \"consonant_output\": y_train_consonant}),batch_size=BS,\n                              epochs = EPOCHS, validation_data = (x_test, [y_test_root, y_test_vowel, y_test_consonant]), \n                              steps_per_epoch=x_train.shape[0] // BS, verbose=1 )\n    histories.append(history)\n    \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":"%matplotlib inline\ndef plot_loss(his, epoch, title):\n    plt.style.use('ggplot')\n    plt.figure()\n    plt.plot(np.arange(0, epoch), his.history['loss'], label='train_loss')\n    plt.plot(np.arange(0, epoch), his.history['grapheme_output_loss'], label='train_root_loss')\n    plt.plot(np.arange(0, epoch), his.history['vowel_output_loss'], label='train_vowel_loss')\n    plt.plot(np.arange(0, epoch), his.history['consonant_output_loss'], label='train_consonant_loss')\n    \n    plt.plot(np.arange(0, epoch), his.history['val_grapheme_output_loss'], label='val_train_root_loss')\n    plt.plot(np.arange(0, epoch), his.history['val_vowel_output_loss'], label='val_train_vowel_loss')\n    plt.plot(np.arange(0, epoch), his.history['val_consonant_output_loss'], label='val_train_consonant_loss')\n    \n    plt.title(title)\n    plt.xlabel('Epoch #')\n    plt.ylabel('Loss')\n    plt.legend(loc='upper right')\n    plt.show()\n\ndef plot_acc(his, epoch, title):\n    plt.style.use('ggplot')\n    plt.figure()\n    plt.plot(np.arange(0, epoch), his.history['grapheme_output_accuracy'], label='train_root_acc')\n    plt.plot(np.arange(0, epoch), his.history['vowel_output_accuracy'], label='train_vowel_accuracy')\n    plt.plot(np.arange(0, epoch), his.history['consonant_output_accuracy'], label='train_consonant_accuracy')\n    \n    plt.plot(np.arange(0, epoch), his.history['val_grapheme_output_accuracy'], label='val_root_acc')\n    plt.plot(np.arange(0, epoch), his.history['val_vowel_output_accuracy'], label='val_vowel_accuracy')\n    plt.plot(np.arange(0, epoch), his.history['val_consonant_output_accuracy'], label='val_consonant_accuracy')\n    plt.title(title)\n    plt.xlabel('Epoch #')\n    plt.ylabel('Accuracy')\n    plt.legend(loc='upper right')\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for dataset in range(4):\n    plot_loss(histories[dataset], epochs, f'Training Dataset: {dataset}')\n    plot_acc(histories[dataset], epochs, f'Training Dataset: {dataset}')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"del histories\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"preds_dict = {\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=[] # 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)\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":{"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":1}