{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":14897,"databundleVersionId":1020216,"sourceType":"competition"},{"sourceId":867719,"sourceType":"datasetVersion","datasetId":461102}],"dockerImageVersionId":30699,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"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\nimport albumentations as A\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.","metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","execution":{"iopub.status.busy":"2024-05-29T15:28:07.572689Z","iopub.execute_input":"2024-05-29T15:28:07.572989Z","iopub.status.idle":"2024-05-29T15:28:21.992838Z","shell.execute_reply.started":"2024-05-29T15:28:07.572964Z","shell.execute_reply":"2024-05-29T15:28:21.988841Z"},"trusted":true},"execution_count":1,"outputs":[{"name":"stderr","text":"2024-05-29 15:28:11.516266: E external/local_xla/xla/stream_executor/cuda/cuda_dnn.cc:9261] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered\n2024-05-29 15:28:11.516388: E external/local_xla/xla/stream_executor/cuda/cuda_fft.cc:607] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered\n2024-05-29 15:28:11.628749: E external/local_xla/xla/stream_executor/cuda/cuda_blas.cc:1515] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered\n","output_type":"stream"},{"traceback":["\u001b[0;31m---------------------------------------------------------------------------\u001b[0m","\u001b[0;31mImportError\u001b[0m                               Traceback (most recent call last)","Cell \u001b[0;32mIn[1], line 15\u001b[0m\n\u001b[1;32m     13\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mtensorflow\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m keras\n\u001b[1;32m     14\u001b[0m \u001b[38;5;28;01mimport\u001b[39;00m \u001b[38;5;21;01mmatplotlib\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01mimage\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m \u001b[38;5;21;01mmpimg\u001b[39;00m\n\u001b[0;32m---> 15\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mkeras\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01mpreprocessing\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01mimage\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m ImageDataGenerator\n\u001b[1;32m     16\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mkeras\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01mmodels\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m Model\n\u001b[1;32m     17\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mkeras\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01mmodels\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m clone_model\n","\u001b[0;31mImportError\u001b[0m: cannot import name 'ImageDataGenerator' from 'keras.preprocessing.image' (/opt/conda/lib/python3.10/site-packages/keras/preprocessing/image/__init__.py)"],"ename":"ImportError","evalue":"cannot import name 'ImageDataGenerator' from 'keras.preprocessing.image' (/opt/conda/lib/python3.10/site-packages/keras/preprocessing/image/__init__.py)","output_type":"error"}]},{"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')","metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","execution":{"iopub.status.busy":"2024-05-29T15:28:21.993556Z","iopub.status.idle":"2024-05-29T15:28:21.993906Z","shell.execute_reply.started":"2024-05-29T15:28:21.99373Z","shell.execute_reply":"2024-05-29T15:28:21.993744Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df_[train_df_['grapheme_root']==14]","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:28:21.998435Z","iopub.status.idle":"2024-05-29T15:28:21.998767Z","shell.execute_reply.started":"2024-05-29T15:28:21.998608Z","shell.execute_reply":"2024-05-29T15:28:21.998623Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# pd.set_option('display.max_rows',None)\ntrain_df_","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:28:22.000158Z","iopub.status.idle":"2024-05-29T15:28:22.000489Z","shell.execute_reply.started":"2024-05-29T15:28:22.000329Z","shell.execute_reply":"2024-05-29T15:28:22.000343Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\ntest_df_.head()","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:28:22.002271Z","iopub.status.idle":"2024-05-29T15:28:22.003023Z","shell.execute_reply.started":"2024-05-29T15:28:22.002802Z","shell.execute_reply":"2024-05-29T15:28:22.002824Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"sample_sub_df.head()","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:28:22.004344Z","iopub.status.idle":"2024-05-29T15:28:22.004679Z","shell.execute_reply.started":"2024-05-29T15:28:22.004518Z","shell.execute_reply":"2024-05-29T15:28:22.004533Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class_map_df.head()","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:28:22.006343Z","iopub.status.idle":"2024-05-29T15:28:22.007155Z","shell.execute_reply.started":"2024-05-29T15:28:22.006943Z","shell.execute_reply":"2024-05-29T15:28:22.006967Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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}')","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:28:22.008397Z","iopub.status.idle":"2024-05-29T15:28:22.009153Z","shell.execute_reply.started":"2024-05-29T15:28:22.008917Z","shell.execute_reply":"2024-05-29T15:28:22.008937Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{}},{"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.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/banglafonts/SolaimanLipi.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","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:28:22.010864Z","iopub.status.idle":"2024-05-29T15:28:22.01124Z","shell.execute_reply.started":"2024-05-29T15:28:22.011073Z","shell.execute_reply":"2024-05-29T15:28:22.011087Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Number of unique values","metadata":{}},{"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()}')","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:28:22.012185Z","iopub.status.idle":"2024-05-29T15:28:22.012518Z","shell.execute_reply.started":"2024-05-29T15:28:22.012349Z","shell.execute_reply":"2024-05-29T15:28:22.012363Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Most used top 10 Grapheme Roots in training set","metadata":{}},{"cell_type":"code","source":"top_10_roots = get_n(train_df_, 'grapheme_root', 10)\ntop_10_roots","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:28:22.014317Z","iopub.status.idle":"2024-05-29T15:28:22.014648Z","shell.execute_reply.started":"2024-05-29T15:28:22.014486Z","shell.execute_reply":"2024-05-29T15:28:22.0145Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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')","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:28:22.016032Z","iopub.status.idle":"2024-05-29T15:28:22.016356Z","shell.execute_reply.started":"2024-05-29T15:28:22.016198Z","shell.execute_reply":"2024-05-29T15:28:22.016212Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Least used 10 Grapheme Roots in training set","metadata":{}},{"cell_type":"code","source":"bottom_10_roots = get_n(train_df_, 'grapheme_root', 10, False)\nbottom_10_roots","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:28:22.017476Z","iopub.status.idle":"2024-05-29T15:28:22.017828Z","shell.execute_reply.started":"2024-05-29T15:28:22.017669Z","shell.execute_reply":"2024-05-29T15:28:22.017683Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nf, 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')","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:28:22.019642Z","iopub.status.idle":"2024-05-29T15:28:22.020002Z","shell.execute_reply.started":"2024-05-29T15:28:22.01981Z","shell.execute_reply":"2024-05-29T15:28:22.019824Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Top 5 Vowel Diacritic in taining data","metadata":{}},{"cell_type":"code","source":"\ntop_5_vowels = get_n(train_df_, 'vowel_diacritic', 5)\ntop_5_vowels","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:28:22.021208Z","iopub.status.idle":"2024-05-29T15:28:22.021532Z","shell.execute_reply.started":"2024-05-29T15:28:22.021371Z","shell.execute_reply":"2024-05-29T15:28:22.021384Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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')","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:28:22.023064Z","iopub.status.idle":"2024-05-29T15:28:22.02341Z","shell.execute_reply.started":"2024-05-29T15:28:22.023235Z","shell.execute_reply":"2024-05-29T15:28:22.02325Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Top 5 Consonant Diacritic in training data","metadata":{}},{"cell_type":"code","source":"top_5_consonants = get_n(train_df_, 'consonant_diacritic', 5)\ntop_5_consonants","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:28:22.026548Z","iopub.status.idle":"2024-05-29T15:28:22.02688Z","shell.execute_reply.started":"2024-05-29T15:28:22.026721Z","shell.execute_reply":"2024-05-29T15:28:22.026735Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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')","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:28:22.02838Z","iopub.status.idle":"2024-05-29T15:28:22.028714Z","shell.execute_reply.started":"2024-05-29T15:28:22.028551Z","shell.execute_reply":"2024-05-29T15:28:22.028566Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df_ = train_df_.drop(['grapheme'], axis=1, inplace=False)","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:28:22.029649Z","iopub.status.idle":"2024-05-29T15:28:22.030009Z","shell.execute_reply.started":"2024-05-29T15:28:22.02981Z","shell.execute_reply":"2024-05-29T15:28:22.029824Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df_[['grapheme_root', 'vowel_diacritic', 'consonant_diacritic']] = train_df_[['grapheme_root', 'vowel_diacritic', 'consonant_diacritic']].astype('uint8')","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:28:22.031978Z","iopub.status.idle":"2024-05-29T15:28:22.032315Z","shell.execute_reply.started":"2024-05-29T15:28:22.032151Z","shell.execute_reply":"2024-05-29T15:28:22.032168Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMG_SIZE=64\nN_CHANNELS=1","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:28:22.03342Z","iopub.status.idle":"2024-05-29T15:28:22.033743Z","shell.execute_reply.started":"2024-05-29T15:28:22.033584Z","shell.execute_reply":"2024-05-29T15:28:22.033598Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"HEIGHT = 137\nWIDTH = 236\nSIZE = 64\nCROP_SIZE = 64","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:28:22.035303Z","iopub.status.idle":"2024-05-29T15:28:22.035843Z","shell.execute_reply.started":"2024-05-29T15:28:22.03562Z","shell.execute_reply":"2024-05-29T15:28:22.03564Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def resize(df, size=64, need_progress_bar=True):\n    resized = {}\n    resize_size=64\n    angle=0\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),None,fx=0.5,fy=0.5,interpolation=cv2.INTER_AREA)\n            image=df.loc[df.index[i]].values.reshape(137,236)\n            #Centering\n            image_center = tuple(np.array(image.shape[1::-1]) / 2)\n            matrix = cv2.getRotationMatrix2D(image_center, angle, 1.0)\n            image = cv2.warpAffine(image, matrix, image.shape[1::-1], flags=cv2.INTER_LINEAR,\n                            borderMode=cv2.BORDER_CONSTANT, borderValue=(0, 0, 0))\n            #Scaling\n            matrix = cv2.getRotationMatrix2D(image_center, 0, 1.0)\n            image = cv2.warpAffine(image, matrix, image.shape[1::-1], flags=cv2.INTER_LINEAR,\n                            borderMode=cv2.BORDER_CONSTANT, borderValue=(0, 0, 0))\n            #Removing Blur\n            #aug = A.GaussianBlur(p=1.0)\n            #image = aug(image=image)['image']\n            #Noise Removing\n            #augNoise=A.MultiplicativeNoise(p=1.0)\n            #image = augNoise(image=image)['image']\n            #Removing Distortion\n            #augDist=A.ElasticTransform(sigma=50, alpha=1, alpha_affine=10, p=1.0)\n            #image = augDist(image=image)['image']\n            #Brightness\n            augBright=A.RandomBrightnessContrast(p=1.0)\n            image = augBright(image=image)['image']\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            #image=affine_image(image)\n            #image= crop_resize(image)\n            #image = cv2.resize(image,(size,size),interpolation=cv2.INTER_AREA)\n            #image=resize_image(image,(64,64))\n            #image = cv2.resize(image,(size,size),interpolation=cv2.INTER_AREA)\n            #gaussian_3 = cv2.GaussianBlur(image, (5,5), cv2.BORDER_DEFAULT) #unblur\n            #image = cv2.addWeighted(image, 1.5, gaussian_3, -0.5, 0, image)\n            #kernel = np.array([[-1,-1,-1], [-1,9,-1], [-1,-1,-1]]) #filter\n            #image = cv2.filter2D(image, -1, kernel)\n            #ret,image = cv2.threshold(image, 128, 255, cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)\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            image_center = tuple(np.array(image.shape[1::-1]) / 2)\n            matrix = cv2.getRotationMatrix2D(image_center, angle, 1.0)\n            image = cv2.warpAffine(image, matrix, image.shape[1::-1], flags=cv2.INTER_LINEAR,\n                            borderMode=cv2.BORDER_CONSTANT, borderValue=(0, 0, 0))\n            matrix = cv2.getRotationMatrix2D(image_center, 0, 1.0)\n            image = cv2.warpAffine(image, matrix, image.shape[1::-1], flags=cv2.INTER_LINEAR,\n                            borderMode=cv2.BORDER_CONSTANT, borderValue=(0, 0, 0))\n            #Removing Blur\n            #aug = A.GaussianBlur(p=1.0)\n            #image = aug(image=image)['image']\n            #Noise Removing\n            #augNoise=A.MultiplicativeNoise(p=1.0)\n            #image = augNoise(image=image)['image']\n            #Removing Distortion\n            #augDist=A.ElasticTransform(sigma=50, alpha=1, alpha_affine=10, p=1.0)\n            #image = augDist(image=image)['image']\n            #Brightness\n            augBright=A.RandomBrightnessContrast(p=1.0)\n            image = augBright(image=image)['image']\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            #image=affine_image(image)\n            #image= crop_resize(image)\n            #image = cv2.resize(image,(size,size),interpolation=cv2.INTER_AREA)\n            #image=resize_image(image,(64,64))\n            #image = cv2.resize(image,(size,size),interpolation=cv2.INTER_AREA)\n            #gaussian_3 = cv2.GaussianBlur(image, (5,5), cv2.BORDER_DEFAULT) #unblur\n            #image = cv2.addWeighted(image, 1.5, gaussian_3, -0.5, 0, image)\n            #kernel = np.array([[-1,-1,-1], [-1,9,-1], [-1,-1,-1]]) #filter\n            #image = cv2.filter2D(image, -1, kernel)\n            #ret,image = cv2.threshold(image, 128, 255, cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)\n            resized[df.index[i]] = resized_roi.reshape(-1)\n    resized = pd.DataFrame(resized).T\n    return resized","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:28:22.037253Z","iopub.status.idle":"2024-05-29T15:28:22.037684Z","shell.execute_reply.started":"2024-05-29T15:28:22.037467Z","shell.execute_reply":"2024-05-29T15:28:22.037485Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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)","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:28:22.038777Z","iopub.status.idle":"2024-05-29T15:28:22.03913Z","shell.execute_reply.started":"2024-05-29T15:28:22.038961Z","shell.execute_reply":"2024-05-29T15:28:22.038975Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Basic Model","metadata":{}},{"cell_type":"code","source":"inputs = Input(shape = (IMG_SIZE, IMG_SIZE, 1))\n\nmodel = Conv2D(filters=32, kernel_size=(3, 3), padding='SAME', activation='relu', input_shape=(IMG_SIZE, IMG_SIZE, 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 = BatchNormalization(momentum=0.15)(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 = BatchNormalization(momentum=0.15)(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.15)(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 = BatchNormalization(momentum=0.15)(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.15)(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 = BatchNormalization(momentum=0.15)(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.15)(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)\n\nmodel = Model(inputs=inputs, outputs=[head_root, head_vowel, head_consonant])","metadata":{"_kg_hide-input":false,"execution":{"iopub.status.busy":"2024-05-29T15:28:22.040384Z","iopub.status.idle":"2024-05-29T15:28:22.040719Z","shell.execute_reply.started":"2024-05-29T15:28:22.040558Z","shell.execute_reply":"2024-05-29T15:28:22.040573Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:28:22.041764Z","iopub.status.idle":"2024-05-29T15:28:22.042105Z","shell.execute_reply.started":"2024-05-29T15:28:22.041945Z","shell.execute_reply":"2024-05-29T15:28:22.041959Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:28:22.042958Z","iopub.status.idle":"2024-05-29T15:28:22.043285Z","shell.execute_reply.started":"2024-05-29T15:28:22.043127Z","shell.execute_reply":"2024-05-29T15:28:22.043141Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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_3_accuracy', \n                                            patience=3, \n                                            verbose=1,\n                                            factor=0.5, \n                                            min_lr=0.00001)\nlearning_rate_reduction_vowel = ReduceLROnPlateau(monitor='dense_4_accuracy', \n                                            patience=3, \n                                            verbose=1,\n                                            factor=0.5, \n                                            min_lr=0.00001)\nlearning_rate_reduction_consonant = ReduceLROnPlateau(monitor='dense_5_accuracy', \n                                            patience=3, \n                                            verbose=1,\n                                            factor=0.5, \n                                            min_lr=0.00001)","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:28:22.044758Z","iopub.status.idle":"2024-05-29T15:28:22.045109Z","shell.execute_reply.started":"2024-05-29T15:28:22.044945Z","shell.execute_reply":"2024-05-29T15:28:22.04496Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#decreased batch size\nbatch_size = 256\nepochs = 30","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:28:22.04631Z","iopub.status.idle":"2024-05-29T15:28:22.046678Z","shell.execute_reply.started":"2024-05-29T15:28:22.046492Z","shell.execute_reply":"2024-05-29T15:28:22.046506Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:28:22.047617Z","iopub.status.idle":"2024-05-29T15:28:22.048329Z","shell.execute_reply.started":"2024-05-29T15:28:22.048144Z","shell.execute_reply":"2024-05-29T15:28:22.048163Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Training loop","metadata":{}},{"cell_type":"code","source":"histories = []\nfor i in range(1):\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    # 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(IMG_SIZE, IMG_SIZE))\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)/255\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    # 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_3': y_train_root, 'dense_4': y_train_vowel, 'dense_5': 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    \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()","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:28:22.049913Z","iopub.status.idle":"2024-05-29T15:28:22.05029Z","shell.execute_reply.started":"2024-05-29T15:28:22.05012Z","shell.execute_reply":"2024-05-29T15:28:22.050139Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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['dense_3_loss'], label='train_root_loss')\n    plt.plot(np.arange(0, epoch), his.history['dense_4_loss'], label='train_vowel_loss')\n    plt.plot(np.arange(0, epoch), his.history['dense_5_loss'], label='train_consonant_loss')\n    \n    plt.plot(np.arange(0, epoch), his.history['val_dense_3_loss'], label='val_train_root_loss')\n    plt.plot(np.arange(0, epoch), his.history['val_dense_4_loss'], label='val_train_vowel_loss')\n    plt.plot(np.arange(0, epoch), his.history['val_dense_5_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['dense_3_accuracy'], label='train_root_acc')\n    plt.plot(np.arange(0, epoch), his.history['dense_4_accuracy'], label='train_vowel_accuracy')\n    plt.plot(np.arange(0, epoch), his.history['dense_5_accuracy'], label='train_consonant_accuracy')\n    \n    plt.plot(np.arange(0, epoch), his.history['val_dense_3_accuracy'], label='val_root_acc')\n    plt.plot(np.arange(0, epoch), his.history['val_dense_4_accuracy'], label='val_vowel_accuracy')\n    plt.plot(np.arange(0, epoch), his.history['val_dense_5_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()","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:28:22.051454Z","iopub.status.idle":"2024-05-29T15:28:22.051783Z","shell.execute_reply.started":"2024-05-29T15:28:22.051623Z","shell.execute_reply":"2024-05-29T15:28:22.051638Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history.history","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:28:22.053162Z","iopub.status.idle":"2024-05-29T15:28:22.053512Z","shell.execute_reply.started":"2024-05-29T15:28:22.053339Z","shell.execute_reply":"2024-05-29T15:28:22.053354Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for dataset in range(1):\n    plot_loss(histories[dataset], epochs, f'Training Dataset: {dataset}')\n    plot_acc(histories[dataset], epochs, f'Training Dataset: {dataset}')","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:28:22.055996Z","iopub.status.idle":"2024-05-29T15:28:22.056324Z","shell.execute_reply.started":"2024-05-29T15:28:22.056165Z","shell.execute_reply":"2024-05-29T15:28:22.056179Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"del histories\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:28:22.05732Z","iopub.status.idle":"2024-05-29T15:28:22.057642Z","shell.execute_reply.started":"2024-05-29T15:28:22.057483Z","shell.execute_reply":"2024-05-29T15:28:22.057497Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"preds_dict = {\n    'grapheme_root': [],\n    'vowel_diacritic': [],\n    'consonant_diacritic': []\n}","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:28:22.059392Z","iopub.status.idle":"2024-05-29T15:28:22.059738Z","shell.execute_reply.started":"2024-05-29T15:28:22.059569Z","shell.execute_reply":"2024-05-29T15:28:22.059584Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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)/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)\ndf_sample.head()","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:28:22.061585Z","iopub.status.idle":"2024-05-29T15:28:22.061937Z","shell.execute_reply.started":"2024-05-29T15:28:22.061752Z","shell.execute_reply":"2024-05-29T15:28:22.061766Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"  preds","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:28:22.062712Z","iopub.status.idle":"2024-05-29T15:28:22.063074Z","shell.execute_reply.started":"2024-05-29T15:28:22.06288Z","shell.execute_reply":"2024-05-29T15:28:22.062915Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df_","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:28:22.065183Z","iopub.status.idle":"2024-05-29T15:28:22.065523Z","shell.execute_reply.started":"2024-05-29T15:28:22.065353Z","shell.execute_reply":"2024-05-29T15:28:22.065368Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}