{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import os\nimport pandas as pd\nimport tensorflow as tf\nimport numpy as np\nimport cv2\nfrom pathlib import Path\nfrom tqdm.auto import tqdm\nimport matplotlib.pyplot as plt\nimport time, gc\nfrom math import ceil","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Data Params"},{"metadata":{"trusted":true},"cell_type":"code","source":"DATA_DIR = Path(\"../input/bengaliai-cv19/\")\nORIGINAL_HEIGHT = 137\nORIGINAL_WIDTH = 236","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Hyperparameters"},{"metadata":{"trusted":true},"cell_type":"code","source":"WIDTH, HEIGHT = 250, 150\nBATCH_SIZE = 64\nEPOCHS = 5","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"root_cls_num = 168\nvowel_cls_num = 11\nconsonant_cls_num = 7","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class TestDataGenerator(tf.keras.utils.Sequence):\n    def __init__(self, df, batch_size = 16):\n        self.df = df\n        self.batch_size = batch_size\n        self.image_ids = df[\"image_id\"].values\n        self.df = df.drop([\"image_id\"], axis=1)\n                    \n    def __len__(self):\n        return int(ceil(len(self.df) / self.batch_size))\n\n    def __getitem__(self, index):\n        start_idx = index*self.batch_size\n        batch_size = min(self.batch_size, len(self.df) - start_idx)\n        X = np.empty((batch_size, *(HEIGHT, WIDTH, 3)))\n        for idx in range(batch_size):\n            idx = idx + start_idx\n            flat_img = self.df.loc[df.index[idx]].values\n            flat_img = 255 - flat_img\n            flat_img = (flat_img * (255.0 / flat_img.max())).astype(np.uint8)\n            img = flat_img.reshape((ORIGINAL_HEIGHT, ORIGINAL_WIDTH))\n            img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)\n            img = cv2.resize(img, (WIDTH, HEIGHT))\n            X[idx,] = img\n        return X","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def create_model():\n    inputs = tf.keras.Input(shape=(HEIGHT, WIDTH, 3), name='img')\n    enet = tf.keras.applications.MobileNetV2(\n        input_shape=(HEIGHT, WIDTH, 3),\n        weights=None,\n        include_top=False\n    )\n    x = enet(inputs)\n    x = tf.keras.layers.GlobalAveragePooling2D()(x)\n    grapheme_root = tf.keras.layers.Dense(root_cls_num, activation='softmax', name='root')(x)\n    vowel = tf.keras.layers.Dense(vowel_cls_num, activation='softmax', name='vowel')(x)\n    consonant = tf.keras.layers.Dense(consonant_cls_num, activation='softmax', name='consonant')(x)\n    \n    model = tf.keras.Model(inputs=inputs, outputs=[grapheme_root, vowel, consonant])\n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"device = '/device:GPU:0'\nnum_test_parquetes = 4\nrow_ids = []\ntargets = [] \nwith tf.device(device):\n    model = create_model()\n    model.load_weights(\"../input/bengaligraphememodels/cp.ckpt\")\n    for i in tqdm(range(num_test_parquetes)):\n        df = pd.read_parquet(DATA_DIR/(\"test_image_data_\" + str(i) + \".parquet\"))\n        test_data_generator = TestDataGenerator(df, batch_size=BATCH_SIZE)\n        preds = model.predict(test_data_generator)\n        for idx in range(preds[0].shape[0]):\n            image_id = test_data_generator.image_ids[idx]\n            row_ids.append(image_id + \"_grapheme_root\")\n            row_ids.append(image_id + \"_vowel_diacritic\")\n            row_ids.append(image_id + \"_consonant_diacritic\")\n            root, vowel, consonant = np.argmax(preds[0][idx]), np.argmax(preds[1][idx]), np.argmax(preds[2][idx])\n            targets.append(root)\n            targets.append(vowel)\n            targets.append(consonant)\n        del df\n        gc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submit_df = pd.DataFrame({'row_id':row_ids,'target':targets}, columns = ['row_id','target'])\nsubmit_df.to_csv('submission.csv', index = False)\nprint(submit_df.head(40))","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}