{"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\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 read-only \"../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# You can write up to 5GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"data_dir = \"/kaggle/input/Kannada-MNIST/\"\ntrain = pd.read_csv(data_dir + \"train.csv\")\ntrain.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test = pd.read_csv(data_dir + \"test.csv\")\ntest.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train = train.iloc[:,1:]\ny_train = train.iloc[:,0]\nX_test = test.iloc[:,1:]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train = np.array(X_train)\ny_train = np.array(y_train)\nX_test = np.array(X_test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Normalize pixel values to be between 0 and 1\nX_train, X_test = X_train / 255.0, X_test / 255.0","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nX_train,X_vali, y_train, y_vali = train_test_split(X_train,\n                                                   y_train,\n                                                   test_size = 0.2)\n\nprint(X_train.shape, X_vali.shape, y_train.shape, y_vali.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def reshape(X_train): \n    X_train_reshape = []\n    for i in range(len(X_train)):\n        X_train_reshape.append(X_train[i].reshape(28, 28, 1))\n    X_train_reshape = np.array(X_train_reshape)\n    return X_train_reshape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train_reshape = reshape(X_train)\nX_vali_reshape = reshape(X_vali)\nX_test_reshape = reshape(X_test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.utils import to_categorical\ny_train = to_categorical(y_train)\ny_vali = to_categorical(y_vali)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.callbacks import ReduceLROnPlateau\n\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nimport tensorflow as tf\n\nfrom tensorflow.keras import datasets, layers, models\n\nfrom tensorflow.keras.optimizers import Adam","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"datagen = ImageDataGenerator(\n    rotation_range=10,\n    zoom_range = 0.1,\n    width_shift_range=0.1,\n    height_shift_range=0.1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"datagen.fit(X_train_reshape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"reduce_lr = ReduceLROnPlateau(monitor='val_accuracy', factor=0.5, patience = 3,\n                              verbose = 1, min_lr=0.00001)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = models.Sequential()\n\nmodel.add(layers.Conv2D(filters = 32, kernel_size = (5, 5), \n                        activation='relu', \n                        padding = 'same', \n                        input_shape=(28, 28, 1)))\nmodel.add(layers.Conv2D(filters = 32, kernel_size = (5, 5), \n                        activation='relu', \n                        padding = 'same'))\nmodel.add(layers.BatchNormalization(momentum = 0.1))\nmodel.add(layers.MaxPooling2D((2,2)))\nmodel.add(layers.Dropout(0.2))\n\nmodel.add(layers.Conv2D(filters = 64, kernel_size = (3, 3), \n                        activation='relu', \n                        padding = 'same'))\nmodel.add(layers.Conv2D(filters = 64, kernel_size = (3, 3), \n                        activation='relu', \n                        padding = 'same'))\nmodel.add(layers.BatchNormalization(momentum = 0.1))\nmodel.add(layers.MaxPooling2D((2,2), strides=(2,2)))\nmodel.add(layers.Dropout(0.2))\n\nmodel.add(layers.Conv2D(filters = 32, kernel_size = (5, 5), \n                        activation='relu', \n                        padding = 'same'))\nmodel.add(layers.Conv2D(filters = 32, kernel_size = (5, 5), \n                        activation='relu', \n                        padding = 'same'))\nmodel.add(layers.BatchNormalization(momentum = 0.1))\nmodel.add(layers.MaxPooling2D((2,2)))\nmodel.add(layers.Dropout(0.2))\n\nmodel.add(layers.Flatten())\nmodel.add(layers.Dense(128, activation='relu'))\nmodel.add(layers.Dropout(0.4))\nmodel.add(layers.Dense(64, activation='relu'))\nmodel.add(layers.Dropout(0.4))\nmodel.add(layers.Dense(10, activation='softmax'))\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"optimizer=Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999)\n\nmodel.compile(optimizer=optimizer,\n          loss=['categorical_crossentropy'],\n          metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"batch_size = 64\nepochs = 30\n\nhistory = model.fit(datagen.flow(X_train_reshape, y_train), epochs=epochs, batch_size = batch_size,\n                    validation_data=(X_vali_reshape, y_vali), verbose = 2, \n                    steps_per_epoch = X_vali.shape[0]//batch_size,\n                    callbacks=[reduce_lr])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def plot_accuracy(history):\n    plt.plot(history.history['accuracy'], label='accuracy')\n    plt.plot(history.history['val_accuracy'], label = 'val_accuracy')\n    plt.xlabel('Epoch')\n    plt.ylabel('Accuracy')\n    # plt.ylim([0.5, 1])\n    plt.legend(loc='lower right')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.plot(history.history['accuracy'], label='accuracy')\nplt.plot(history.history['val_accuracy'], label = 'val_accuracy')\nplt.xlabel('Epoch')\nplt.ylabel('Accuracy')\n# plt.ylim([0.5, 1])\nplt.legend(loc='lower right')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predicted = model.predict(X_test_reshape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predicted = np.argmax(predicted, axis = 1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"index = np.array(test.index)\nres = pd.DataFrame(np.concatenate([index[:,np.newaxis],predicted[:,np.newaxis]], axis = 1), columns = ['id', 'label'])\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"res","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"res.to_csv('submission.csv', index = False)","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}