{"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":"from __future__ import absolute_import, division, print_function, unicode_literals\nimport functools\nimport tensorflow as tf\nfrom tensorflow.keras.callbacks import ReduceLROnPlateau, EarlyStopping\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense,Conv2D,Flatten,MaxPooling2D,Dropout,BatchNormalization\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras import layers, models\nfrom tensorflow import keras\nprint(tf.__version__)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = pd.read_csv(\"/kaggle/input/Kannada-MNIST/train.csv\")\nvalidation = pd.read_csv(\"/kaggle/input/Kannada-MNIST/Dig-MNIST.csv\")\ntrain = train.append(validation)\n\ntest = pd.read_csv(\"/kaggle/input/Kannada-MNIST/test.csv\")\nsample_submission = pd.read_csv(\"/kaggle/input/Kannada-MNIST/sample_submission.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"(train_label, train_features) = (train[\"label\"], train.drop([\"label\"],axis=1))\n(test_id, test_features) = (test[\"id\"], test.drop([\"id\"],axis=1))\n\n(train_x, train_y) = (train_features.values, train_label.values)\ntest_x = test_features.values","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_x, valid_x, train_y, valid_y = train_test_split(train_x, train_y, test_size = 0.05, random_state=42)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"reshaped_train_x = tf.reshape(train_x, [-1,28,28,1])\nreshaped_valid_x = tf.reshape(valid_x, [-1,28,28,1])\nreshaped_test_x = tf.reshape(test_x, [-1,28,28,1])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"normalized_train_x = reshaped_train_x/255\nnormalized_valid_x = reshaped_valid_x/255\nnormalized_test_x = reshaped_test_x/255\ntrain_labels = keras.utils.to_categorical(train_y, 10)\nvalid_labels = keras.utils.to_categorical(valid_y, 10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"datagen_train = ImageDataGenerator(rotation_range=15,\n                             width_shift_range = 0.2,\n                             height_shift_range = 0.2,\n                             shear_range = 25,\n                             zoom_range = 0.4,)\ndatagen_valid = ImageDataGenerator()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Conv2D(64, kernel_size=3, activation='relu', input_shape=(28, 28, 1)))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(64, kernel_size=3, activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(64, kernel_size=5, padding='same', activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.2))\n\nmodel.add(Conv2D(128, kernel_size=3, activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(128, kernel_size=3, activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(128, kernel_size=5, padding='same', activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.2))\n\nmodel.add(Conv2D(256, kernel_size=3, activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.2))\n\nmodel.add(Flatten())\nmodel.add(Dense(256))\nmodel.add(BatchNormalization())\nmodel.add(Dense(128))\nmodel.add(BatchNormalization())\nmodel.add(Dense(10, activation='softmax'))\n\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"lr = 2e-3\nbatch_size=128\nepochs=50\n\nlearning_rate_reduction = ReduceLROnPlateau(monitor='val_loss', \n                                            patience=5,\n                                            verbose=1,\n                                            factor=0.2)\n\nearlystop = EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=8)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit(datagen_train.flow(normalized_train_x, train_labels, batch_size=batch_size),\n                    epochs = epochs,\n                    steps_per_epoch=normalized_train_x.shape[0] // batch_size,\n                    validation_data = (normalized_valid_x,valid_labels),\n                    shuffle=True,\n                    callbacks=[learning_rate_reduction, earlystop])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"prediction = model.predict(normalized_test_x)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test['label'] = np.argmax(prediction, axis=1)\n\nsubmission = test[['id', 'label']]\nsubmission.to_csv(\"submission.csv\",index=False)","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":1}