{"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 in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\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":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"# General\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 # progress bar\nimport gc # garbage collector\nimport random\nimport cv2\nimport albumentations as A\n\n# CNN\nfrom tensorflow import keras\nfrom keras.models import Model\nfrom keras.layers import Dense,Conv2D,Flatten,MaxPool2D,Dropout,BatchNormalization,Input,UpSampling2D,concatenate, GlobalAveragePooling2D\nfrom keras.optimizers import Adam\nfrom keras.applications import DenseNet121\n\n# Training\nfrom keras.callbacks import ReduceLROnPlateau,ModelCheckpoint,EarlyStopping\nfrom keras.preprocessing.image import ImageDataGenerator # super useful because we don't need to create our own generator\nfrom sklearn.model_selection import train_test_split # train and test data split\n\n# Visualization\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg","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":"# https://www.kaggle.com/shawon10/bangla-graphemes-image-processing-deep-cnn\n    # Images can lose much important information due to resizing. Inter-area interpolation \n    # is preferred method for image decimation. Interpolation works by using known data to \n    # estimate values at unknown points. We use inter-area interpolation after resizing images. \n    # We have also cropped the images and extract the region of interest of the images.\n    # Cropped images are performing better.\n\ndef resize(df, size=IMG_SIZE, need_progress_bar=True):\n    resized = {}\n    resize_size=IMG_SIZE\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","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# kaggle.com/xhlulu/bengali-ai-simple-densenet-in-keras\ndef build_model(densenet):\n    x_in = Input(shape=(IMG_SIZE, IMG_SIZE, 1))\n    x = Conv2D(3, (3, 3), padding='same')(x_in)\n    x = densenet(x)\n    \n    x = GlobalAveragePooling2D()(x)\n    x = BatchNormalization()(x)\n    x = Dropout(0.5)(x)\n    x = Dense(256, activation='relu',name='dense_5')(x)\n    x = BatchNormalization()(x)\n    x = Dropout(0.5)(x)\n    \n    head_root = Dense(168, activation='softmax',name='dense_1')(x)\n    head_vowel = Dense(11, activation='softmax',name='dense_2')(x)\n    head_consonant = Dense(7, activation='softmax',name='dense_3')(x)\n    \n    model = Model(inputs=x_in, outputs=[head_root, head_vowel, head_consonant])\n    \n    model.compile(\n        Adam(lr=0.0001), \n        metrics=['accuracy'], \n        loss='categorical_crossentropy'\n    )\n    \n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"weights_path = '/kaggle/input/densenet-keras/DenseNet-BC-121-32-no-top.h5'\ndensenet = DenseNet121(include_top=False, weights=weights_path, input_shape=(IMG_SIZE, IMG_SIZE, 3))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = build_model(densenet)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Reduce learning rate when a metric has stopped improving\n# if validation loss of dense_x is not decreasing for 3 consecutive epochs, decrease the learning rate by 0.5 \n# given if learning rate is above 0.00001 and give us little insight on what has happened verbose=1\nReduceLearningOnPlateau_root = ReduceLROnPlateau(monitor='val_dense_1_loss',patience=3,verbose=1,factor=0.5,min_lr=0.00001)\nReduceLearningOnPlateau_vowel = ReduceLROnPlateau(monitor='val_dense_2_loss',patience=3,verbose=1,factor=0.5,min_lr=0.00001)\nReduceLearningOnPlateau_consonant = ReduceLROnPlateau(monitor='val_dense_3_loss',patience=3,verbose=1,factor=0.5,min_lr=0.00001)\n\n\n# Stop training when a monitored quantity has stopped improving\nEarlyStopping = EarlyStopping(monitor='val_loss',patience=4, min_delta=0.0025,restore_best_weights=True)\n# stop the model from fitting data if validation loss has not decreased by 0.0025 in the last 5 epochs and \n# restore best weights for the next time\n# loss vs val_loss: \n    # if loss is significantly lower than val_loss the data is probably overfitted\n    # EarlyStopping prevents this from happening (from overfitting)\n\n\n# Save the model after every epoch\nModelCheckpoint = ModelCheckpoint('best_model_weight.h5', monitor='val_loss', verbose=1, \n                      save_best_only=True, save_weights_only=True)\n# save the weights in a file name specified only if the validation loss of out_1 layer has improved from \n# last save. out_1 because it's recall matters twice \n\n# save all into one array\ncallbacks = [ReduceLearningOnPlateau_root, ReduceLearningOnPlateau_vowel, ReduceLearningOnPlateau_consonant, EarlyStopping, ModelCheckpoint]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"batch_size = 128\nepochs = 30","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"num_dataset = 4","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Function takes data and label arrays and then generates batches of augmented data\n# Many notebooks are using exactly this kind of generator\n# the only different thing is usually different batch size\nclass TweakedDataGenerator(ImageDataGenerator):\n\n    def flow(self, x, y=None, batch_size=batch_size, shuffle=True, sample_weight=None, seed=None, \n             save_to_dir=None, save_prefix='', save_format='png', subset=None):\n\n        labels_array = None # concatenate all labels arrays into a single array\n        target_lengths = {} # dictionary mapping the 'key' (y1,y2,...) to lengths of corresponding label_array     \n        ordered_labels = [] # store ordering in which the labels were passed to this class\n        \n        for output, label_value in y.items():\n            if labels_array is None:\n                labels_array = label_value # for the first time loop, it's empty, so insert first element\n            else:\n                labels_array = np.concatenate((labels_array, label_value), axis=1)\n            target_lengths[output] = label_value.shape[1]\n            ordered_labels.append(output)\n\n\n        for flowx, flowy in super().flow(x, labels_array, batch_size=batch_size,\n                                         shuffle=shuffle):\n            target_dict = {}\n            i = 0\n            for output in ordered_labels:\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":"history_list = []\ntrain_data = pd.read_csv('/kaggle/input/bengaliai-cv19/train.csv')\n\nfor i in range(num_dataset):\n\n    # Merge data frames, then drop useless columns\n    b_train_data =  pd.merge(pd.read_parquet(f'../input/bengaliai-cv19/train_image_data_{i}.parquet'), train_data, on='image_id').drop(['image_id'], axis=1)\n    X_train = b_train_data.drop(['grapheme_root', 'vowel_diacritic', 'consonant_diacritic', 'grapheme'], axis=1)\n    \n    # Normalize\n    X_train = resize(X_train)/255\n\n    \n    # Reshape, -1 means we let numpy figure out the dimensions\n    X_train = X_train.values.reshape(-1, IMG_SIZE, IMG_SIZE, N_CHANNELS)\n  \n\n    # Training set for the three consitutuents\n    Y_train_root = b_train_data['grapheme_root']\n    Y_train_vowel = b_train_data['vowel_diacritic']\n    Y_train_consonant = b_train_data['consonant_diacritic']\n\n    \n    # Extract labels\n    # Convert numerical values of classes into dummy variables\n    Y_train_root = pd.get_dummies(Y_train_root).values\n    Y_train_vowel = pd.get_dummies(Y_train_vowel).values\n    Y_train_consonant = pd.get_dummies(Y_train_consonant).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    \n    # Split the data in training and test to cross-validate our model's performance\n    # random_state produces the same data every time for reproducibility so it is kind of pseudo randomness\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=2020)\n\n    # Data augmentation for creating more training data\n    datagen = TweakedDataGenerator(\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    datagen.fit(x_train)   \n    print(y_train_root.shape)\n    # Start training\n    history = model.fit_generator(datagen.flow(x_train, {'dense_1': y_train_root, 'dense_2': y_train_vowel, 'dense_3': 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, callbacks = callbacks)\n    \n    stopped_at = EarlyStopping.stopped_epoch # gives you >=1 at which epoch model stopped due to early stopping\n    \n    history_list.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    del b_train_data\n    del X_train\n    del Y_train_root, Y_train_vowel, Y_train_consonant\n    \n    # Use this method to force the system to try to reclaim the maximum amount of available memory\n    gc.collect()\n    \ndel train_data\ngc.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    epoch = len(his.history['loss'])\n    plt.plot(np.arange(0, epoch), his.history['loss'], label='train_loss')\n    plt.plot(np.arange(0, epoch), his.history['dense_1_loss'], label='train_root_loss')\n    plt.plot(np.arange(0, epoch), his.history['dense_2_loss'], label='train_vowel_loss')\n    plt.plot(np.arange(0, epoch), his.history['dense_3_loss'], label='train_consonant_loss')\n    \n    plt.plot(np.arange(0, epoch), his.history['val_dense_1_loss'], label='val_train_root_loss')\n    plt.plot(np.arange(0, epoch), his.history['val_dense_2_loss'], label='val_train_vowel_loss')\n    plt.plot(np.arange(0, epoch), his.history['val_dense_3_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    epoch = len(his.history['dense_1_accuracy'])\n    plt.plot(np.arange(0, epoch), his.history['dense_1_accuracy'], label='train_root_acc')\n    plt.plot(np.arange(0, epoch), his.history['dense_2_accuracy'], label='train_vowel_accuracy')\n    plt.plot(np.arange(0, epoch), his.history['dense_3_accuracy'], label='train_consonant_accuracy')\n    \n    plt.plot(np.arange(0, epoch), his.history['val_dense_1_accuracy'], label='val_root_acc')\n    plt.plot(np.arange(0, epoch), his.history['val_dense_2_accuracy'], label='val_vowel_accuracy')\n    plt.plot(np.arange(0, epoch), his.history['val_dense_3_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(num_dataset):\n    plot_loss(history_list[dataset], epochs, f'Training Dataset: {dataset}')\n    plot_acc(history_list[dataset], epochs, f'Training Dataset: {dataset}')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Load the best weights so far so that we don't have over fitting by the time the mode lhad stopped \nmodel.load_weights('best_model_weight.h5') ","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=[]\nrow_id=[]\n\nfor i in range(num_dataset):\n    df_test_img = pd.read_parquet('../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    \nsubmission = pd.DataFrame({'row_id': row_id, 'target':target}, columns = ['row_id','target'])\nsubmission.to_csv('submission.csv',index=False)\nsubmission.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_data = pd.read_csv('../input/bengaliai-cv19/train.csv')\n\nb_train_data =  pd.merge(pd.read_parquet(f'/kaggle/input/bengaliai-cv19/train_image_data_0.parquet'), train_data, on='image_id').drop(['image_id'], axis=1)\nX_train = b_train_data.drop(['grapheme_root', 'vowel_diacritic', 'consonant_diacritic','grapheme'], axis=1)\nX_train = resize(X_train)/255\n\nX_train = X_train.values.reshape(-1, IMG_SIZE, IMG_SIZE, N_CHANNELS)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"![](http://)"},{"metadata":{},"cell_type":"markdown","source":"vanaf hier origineel\n"}],"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}