{"cells":[{"metadata":{},"cell_type":"markdown","source":"This is my best private score kernel (0.99280),\nso I would like to share what I did.\nThe point is the method described in [Keras Learning Rate Finder](https://www.pyimagesearch.com/2019/08/05/keras-learning-rate-finder/)\nto find effective leraning rate range for the model.\nI used the values in the found range to train the model.\n\n## Contents\n1. [Preparation](#Preparation)\n1. [Making Model](#MakingModel)\n1. [Data Augmentation](#DataAugmentation)\n1. [Finding Effective Learning Rate](#FindingEffectiveLearningRate)\n1. [Training](#Training)\n1. [Submit Prediction](#SubmitPrediction)\n1. [Reference](#Reference)"},{"metadata":{},"cell_type":"markdown","source":"<div id='Preparation'>\n## 1. Preparation"},{"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":{"trusted":true},"cell_type":"code","source":"# https://keras.io/getting-started/faq/#how-can-i-obtain-reproducible-results-using-keras-during-development\n# How can I obtain reproducible results using Keras during development?\nimport random as rn\nimport tensorflow as tf\n\nrand_seed = 53\n# maybe no effect, since this should be set before the program starts.\n%env PYTHONHASHSEED=0\nnp.random.seed(rand_seed)\nrn.seed(rand_seed)\n\ntf.config.threading.set_inter_op_parallelism_threads(1)\ntf.config.threading.set_intra_op_parallelism_threads(1)\ntf.random.set_seed(rand_seed)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def read_data(file_name):\n    file_path = '../input/Kannada-MNIST/' + file_name\n    data_df = pd.read_csv(file_path)\n    pixels_df = data_df.drop(columns='label')\n    pixels_array = pixels_df.to_numpy(dtype=np.uint8)\n    reshaped_pixels_array = pixels_array.reshape(-1, 28, 28, 1)\n    labels_array = data_df.label.values\n    return (reshaped_pixels_array, labels_array)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"For [train_test_split](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html),\nI specified the stratify option.\nThis ensures that the distribution of each splitted data becomes\nthe same as the one in the specified data.\nIn this case, train_test_split tries to split the whole data\ninto training and test with the same distribution of labels in the whole data."},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n\nX, y = read_data('train.csv')\nX_train, X_test, y_train, y_test = \\\n    train_test_split(X, y, test_size=0.1, random_state=rand_seed, stratify=y)\n\nprint(X_train.shape)\nprint(y_train.shape)\nprint(X_test.shape)\nprint(y_test.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from PIL import Image\nimport matplotlib.pyplot as plt\n\ndef draw_image(im_array, subplot=(1, 1, 1)):\n    im = Image.fromarray(im_array.reshape(28, 28))\n    plt.subplot(*subplot)\n    plt.imshow(im, cmap='gray')\n    plt.axis(\"off\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"draw_image(X_train[0])\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"unique_y = np.unique(y_train)\nprint(unique_y)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"label_count = len(unique_y)\nprint(label_count)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# TODO: Fix, xticks and bar positions are not aligned.\ndef draw_hist(x, title):\n    global label_count\n    plt.hist(x, bins=label_count, rwidth=0.8)\n    plt.title(title)\n    plt.xlabel('labels')\n    plt.ylabel('counts')\n    plt.xticks(np.arange(10))\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"draw_hist(y_train, \"Distributions of all train labels\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"draw_hist(y_test, \"Distributions of all test labels\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<div id='MakingModel'>\n## 2. Making Model\n\nFor a convolution block, I used \"Conv2D --> ReLU --> BatchNormalization\".\nI specified he_normal as the [kernel_initializer](https://keras.io/initializers/).\nWithout this, sometimes loss of the model became larger and larger and did not converged."},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.layers import Conv2D, BatchNormalization\nfrom keras.initializers import he_normal\n\ndef make_conv_layer(filter_size, suffix, inputs):\n    x = Conv2D(\n        filter_size, kernel_size=(3, 3), padding='same', activation='relu',\n        kernel_initializer=he_normal(seed=rand_seed), name='conv_' + suffix)(inputs)\n    outputs = BatchNormalization(name='bn_' + suffix)(x)\n    return outputs","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"The model consists of the following blocks:\n1. Scaling by dividing 255.0.\n1. 3 Convolutions with filter size 64, then MaxPooling and SpatialDropout(0.25)\n1. 3 Convolutions with filter size 128, then MaxPooling and SpatialDropout(0.25)\n1. 3 Convolutions with filter size 256, then GlobalAveragePooling\n1. Dense with 256 units, then Dropout(0.25) and outputs with Dense(label_count).\n\nSome points are:\n* Scaling is done here, because:\n    * To do just once.\n    * To save memory.  Data type for image is unsigned integer (0..255) and its size is 1 byte. Dividing by floting point number 255.0 makes floating point result of 4 or 8 bytes. So dividing whole data comsumes a lot of memory.\n* [GlobalAveragePooling2D](https://keras.io/layers/pooling/) is used\nto connect the last convolution block to the Dence.\nThis saves the number of parameters for the Dence and seems the performance is much the same.\n* sparse_categorical_crossentropy is used for the [loss function](https://keras.io/losses/).\nThis function accepts the label value directly, so one hot encoding is not necessary."},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.layers import Input, Lambda, MaxPooling2D, SpatialDropout2D, Dense\nfrom keras.layers import GlobalAveragePooling2D, Dropout\nfrom keras.models import Model\n\ndef make_model():\n    inputs = Input(shape=(28, 28, 1), name=\"input\")\n    x = Lambda(lambda v: v / 255.0, name='scaling')(inputs)\n    \n    x = make_conv_layer(64, '1_1', x)\n    x = make_conv_layer(64, '1_2', x)\n    x = make_conv_layer(64, '1_3', x)\n    x = MaxPooling2D(pool_size=(2, 2), name=\"maxpool_1\")(x)\n    x = SpatialDropout2D(0.25, name='sp_dpout_1')(x)\n\n    x = make_conv_layer(128, '2_1', x)\n    x = make_conv_layer(128, '2_2', x)\n    x = make_conv_layer(128, '2_3', x)\n    x = MaxPooling2D(pool_size=(2, 2), name='maxpool_2')(x)\n    x = SpatialDropout2D(0.25, name='sp_dpout_2')(x)\n\n    x = make_conv_layer(256, '3_1', x)\n    x = make_conv_layer(256, '3_2', x)\n    x = make_conv_layer(256, '3_3', x)\n    x = GlobalAveragePooling2D(name='gblavgpool')(x)\n\n    x = Dense(256, activation='relu', name='dense')(x)\n    x = Dropout(0.25, name='dropout')(x)\n    outputs = Dense(label_count, activation='softmax', name='outputs')(x)\n\n    model = Model(inputs=inputs, outputs=outputs)\n    model.compile(\n        optimizer='adam',\n        loss='sparse_categorical_crossentropy',\n        metrics=['sparse_categorical_accuracy'])\n    \n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_model = make_model()\ntrain_model.summary()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<div id='DataAugmentation'>\n## 3. Data Augmentation\n\nI used [ImageDataGenerator](https://keras.io/preprocessing/image/)\nto make variations of the traing data.\nI drew heatmaps to check how the significant pixels are distributed\nin the original and generated images."},{"metadata":{"trusted":true},"cell_type":"code","source":"import seaborn as sns\n\ndef draw_sum_heatmap(X):\n    X_sum = np.sum(X, axis=0, dtype=np.float32) / 255.0\n    X_reshaped_sum = np.reshape(X_sum, (28, 28))\n    sns.heatmap(X_reshaped_sum)\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"draw_sum_heatmap(X)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator\n\ntrain_image_generator = ImageDataGenerator(\n    rotation_range=20,\n    width_shift_range=0.2,\n    height_shift_range=0.2,\n    shear_range=10,\n    zoom_range=0.2,\n    fill_mode='constant',\n    cval=0,\n    data_format='channels_last')\ntest_image_generator = ImageDataGenerator()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"By calling next(), batch_size number of images are generated.\nIn this case, it is 60,000. "},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_image_flow = train_image_generator.flow(\n    X, y, batch_size=len(X), shuffle=False, seed=rand_seed)\nX_generated_sample, _ = next(sample_image_flow)\nprint(X_generated_sample.shape)\ndraw_sum_heatmap(X_generated_sample)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"batch_size = 256\nsteps_per_epoch = (X_train.shape[0] + batch_size - 1) // batch_size\n\ntrain_image_flow = train_image_generator.flow(\n    X_train, y_train, batch_size=batch_size, shuffle=True, seed=rand_seed)\ntest_image_flow = test_image_generator.flow(\n    X_test, y_test, batch_size=batch_size, shuffle=True, seed=rand_seed)\n\nprint(\"batch_size: {0}\".format(batch_size))\nprint(\"steps_per_epoch: {0}\".format(steps_per_epoch))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<div id='FindingEffectiveLearningRate'>\n## 4. Finding Effective Learning Rate\n\nI referred [Keras Learning Rate Finder](https://www.pyimagesearch.com/2019/08/05/keras-learning-rate-finder/) to make this portion.\nThe idea is:\n* Sweep learning rate from far too small to far too large.\n* Monitor loss while sweeping.\n* The point where the loss becomes decreasing is the minimum available learning rate.\n* The point where the loss stops decreasing is the maximum available learning rate."},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras import backend as K\n\ndef get_lr(model):\n    return K.get_value(model.optimizer.lr)\n\ndef set_lr(model, lr):\n    K.set_value(model.optimizer.lr, lr)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def find_lr_on_batch_end(model, logs, lr_list, loss_list, lr_mult):\n    lr = get_lr(model)\n    lr_list.append(lr)\n    loss = logs['loss']\n    loss_list.append(loss)\n    \n    set_lr(model, lr * lr_mult)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"find_lr_start_lr = 1e-10\nfind_lr_end_lr = 1.0\n\nfind_lr_epochs = 3\nfind_lr_total_batch_count = find_lr_epochs * steps_per_epoch\nfind_lr_lr_mult = (find_lr_end_lr / find_lr_start_lr) ** (1.0 / find_lr_total_batch_count)\n\nprint(\"find_lr_epochs: {0}\".format(find_lr_epochs))\nprint(\"find_lr_total_batch_count: {0}\".format(find_lr_total_batch_count))\nprint(\"find_lr_lr_mult: {0}\".format(find_lr_lr_mult))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.callbacks import LambdaCallback\n\nfind_lr_model = make_model()\nfind_lr_lr_list = []\nfind_lr_loss_list = []\n\nfind_lr_callback = LambdaCallback(\n    on_batch_end=lambda batch, logs: find_lr_on_batch_end(\n        find_lr_model, logs, find_lr_lr_list, find_lr_loss_list, find_lr_lr_mult))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"set_lr(find_lr_model, find_lr_start_lr)\nfind_lr_history = find_lr_model.fit_generator(\n    train_image_flow,\n    steps_per_epoch=steps_per_epoch,\n    epochs=find_lr_epochs,\n    validation_data=test_image_flow,\n    callbacks=[find_lr_callback],\n    verbose=2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.plot(find_lr_lr_list, find_lr_loss_list)\nplt.xscale('log')\nplt.ylim(0, 4)\nplt.title('Learning Rate vs Loss')\nplt.xlabel('Learning Rate (Log Scale)')\nplt.ylabel('Loss')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<div id='Training'>\n## 5. Training\n\n* I used 3 learning rates, maximum, medium, and minimum of the range\nfound in the previous step.\n* I specified the epoch explicitly for changing the learning rate.\nIt's simple.\nBy the loss and accuracy plots below,\nthey are improved at the point where the rate changed.\n* 150 epochs seems a bit too long, however sometimes might get a fantastic result,\nbecause the training step is not deterministic.\n* I chose the best model by using the validation accuracy."},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.callbacks import LearningRateScheduler\n\ntrain_epochs = 150\n\ndef lr_schedule(epoch_index, current_lr):\n    if epoch_index == 0:\n        new_lr = 1e-3\n    elif epoch_index == 49:\n        new_lr = 3e-4\n    elif epoch_index == 99:\n        new_lr = 1e-4\n    else:\n        new_lr = current_lr\n\n    if new_lr != current_lr:\n        print(\n            \"Epoch {0}: Learning late changed from {1:.5f} to {2:.5f}\".format(\n            epoch_index + 1, current_lr, new_lr))\n    return new_lr\n\nlr_scheduler = LearningRateScheduler(lr_schedule, verbose=0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.callbacks import ModelCheckpoint\n\nbest_model_file_name = \"best_model.hdf5\"\nmodel_check_point = ModelCheckpoint(\n    best_model_file_name, monitor='val_sparse_categorical_accuracy', mode='max',\n    verbose=0, save_best_only=True, save_weights_only=True, period=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_history = train_model.fit_generator(\n    train_image_flow,\n    steps_per_epoch=steps_per_epoch,\n    epochs=train_epochs,\n    validation_data=test_image_flow,\n    callbacks=[lr_scheduler, model_check_point],\n    verbose=2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"best_train_model = make_model()\nbest_train_model.load_weights(best_model_file_name)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_result = best_train_model.evaluate(X_test, y_test)\nprint(train_result)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def draw_loss(history, ylim):\n    plt.figure(figsize=(12, 4))\n    plt.plot(history.history['loss'], label='loss')\n    plt.plot(history.history['val_loss'], label='val_loss')\n    plt.title('Loss and Val Loss')\n    plt.xlabel('epochs')\n    plt.ylabel('loss')\n    plt.ylim(*ylim)\n    plt.legend()\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"draw_loss(train_history, (0.0, 0.05))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def draw_acc(history, ylim):\n    plt.figure(figsize=(12, 4))\n    plt.plot(history.history['sparse_categorical_accuracy'], label='acc')\n    plt.plot(history.history['val_sparse_categorical_accuracy'], label='val_acc')\n    plt.title('Acc and Val Acc')\n    plt.xlabel('epochs')\n    plt.ylabel('accuracy')\n    plt.ylim(*ylim)\n    plt.legend()\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"draw_acc(train_history, (0.99, 1.0))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<div id='SubmitPrediction'>\n## 6. Submit Prediction"},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df = pd.read_csv('../input/Kannada-MNIST/test.csv')\ntest_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_pixels_df = test_df.drop(columns='id')\ntest_pixels_array = test_pixels_df.to_numpy(dtype=np.uint8)\ntest_images = test_pixels_array.reshape(-1, 28, 28, 1)\nprint(test_images.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"draw_image(test_images[0])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model_preds = best_train_model.predict(test_images)\nprint(model_preds.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred_labels = np.argmax(model_preds, axis=1)\ndraw_hist(pred_labels, \"Distributions of prediction labels\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_submission_df = pd.read_csv('../input/Kannada-MNIST/sample_submission.csv')\nsample_submission_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_submission_df['label'] = pred_labels\nsample_submission_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_submission_df.to_csv('submission.csv', index=False)\nprint('Done!')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<div id='Reference'>\n## 7. Reference\n\nI referred the following documents and kernels.\nMany thanks to the authors of them.\n\n* [How to use pre-trained models in kernels on Kaggle](https://www.kaggle.com/paultimothymooney/how-to-use-pre-trained-models-in-kernels-on-kaggle) -- at first, I planed to use transfer learning.\n* [Indian way to learn CNN](https://www.kaggle.com/shahules/indian-way-to-learn-cnn) -- referred for reading and handling data.\n* [Keras Learning Rate Finder](https://www.pyimagesearch.com/2019/08/05/keras-learning-rate-finder/) -- so I specified learning rate with confidence.\n* [Cyclical Learning Rates with Keras and Deep Learning](https://www.pyimagesearch.com/2019/07/29/cyclical-learning-rates-with-keras-and-deep-learning/) -- I tried.\n* [An implementation of DropConnect Layer in Keras](https://github.com/andry9454/KerasDropconnect),\n[Fork of Keras CNN - DropConnect](https://www.kaggle.com/naraque/fork-of-keras-cnn-dropconnect) -- I tried too.\n* [Deep Dive in KannadaMnist with tfkeras](https://www.kaggle.com/xiejialun/deep-dive-in-kannadamnist-with-tfkeras) -- \"Symmetric Cross Entropy\" used in this kernel is interesting and I tried."}],"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}