{"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":{},"cell_type":"markdown","source":"### Importing the required libraries"},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import tensorflow as tf\nimport pandas as pd\nimport numpy as np\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.layers import Flatten, Dense, Activation, Dropout\nfrom keras.layers import LeakyReLU\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.preprocessing import image\nimport matplotlib.pyplot as plt\n%matplotlib inline\nfrom sklearn.metrics import accuracy_score\nfrom tensorflow.keras.callbacks import LearningRateScheduler\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.callbacks import EarlyStopping","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Reading the Data"},{"metadata":{"trusted":true},"cell_type":"code","source":"train= pd.read_csv('/kaggle/input/Kannada-MNIST/train.csv')\ntrain.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test= pd.read_csv(\"/kaggle/input/Kannada-MNIST/test.csv\")\ntest.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Val= pd.read_csv(\"/kaggle/input/Kannada-MNIST/Dig-MNIST.csv\")\nVal.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train= train.drop(['label'],axis=1).values\nX_train.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Y_train=train['label'].values\nY_train.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train = X_train.reshape(X_train.shape[0],28,28,1)\nX_train.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"np.unique(Y_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_val= Val.drop(['label'],axis=1).values\nX_val= X_val.reshape(X_val.shape[0],28,28,1)\nX_val.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Y_val= Val['label'].values","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Scaling the Pixel Values"},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train,X_val= X_train/255.0, X_val/255.0","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train1, X_valid1, Y_train1, Y_valid1 = train_test_split(X_train, Y_train, test_size = 0.10, random_state=42)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_d = ImageDataGenerator(rescale = 1./255.,\n                                   rotation_range = 10,\n                                   width_shift_range = 0.25,\n                                   height_shift_range = 0.25,\n                                   shear_range = 0.1,\n                                   zoom_range = 0.25,\n                                   horizontal_flip = False)\nvalid_d = ImageDataGenerator(rescale=1./255) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def lr_decay(epoch):\n    return initial_learningrate * 0.99 ** epoch","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"es = EarlyStopping(monitor='val_loss', verbose=1, patience=10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"initial_learningrate=2e-3\nbatch_size = 1000\nepochs = 10\ninput_shape = (28, 28, 1)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Neural Layers"},{"metadata":{"trusted":true},"cell_type":"code","source":"model= Sequential()\nmodel.add(Conv2D(128,(3,3),input_shape=(28,28,1),activation='relu',padding='same'))\nmodel.add(BatchNormalization(momentum=0.9, epsilon=1e-5, gamma_initializer=\"uniform\"))\nmodel.add(MaxPooling2D(pool_size=(2,2),padding='same')) \n\nmodel.add(Conv2D(256,(3,3),padding='same',activation='relu')) \nmodel.add(BatchNormalization(momentum=0.9, epsilon=1e-5, gamma_initializer=\"uniform\"))\nmodel.add(LeakyReLU(alpha=0.1))#2nd Convol Layer\nmodel.add(MaxPooling2D(pool_size=(2,2),padding='same'))\nmodel.add(Dropout(0.3))\n\nmodel.add(Conv2D(128,(3,3),padding='same',activation='relu')) \nmodel.add(BatchNormalization(momentum=0.9, epsilon=1e-5, gamma_initializer=\"uniform\"))\nmodel.add(LeakyReLU(alpha=0.1))#2nd Convol Layer\nmodel.add(MaxPooling2D(pool_size=(2,2),padding='same'))\nmodel.add(Dropout(0.3))\n\nmodel.add(Conv2D(64,(3,3),padding='same',activation='relu')) \nmodel.add(BatchNormalization(momentum=0.9, epsilon=1e-5, gamma_initializer=\"uniform\"))\nmodel.add(LeakyReLU(alpha=0.1))#2nd Convol Layer\nmodel.add(MaxPooling2D(pool_size=(2,2),padding='same'))\nmodel.add(Dropout(0.3))\n\nmodel.add(Conv2D(64,(3,3),padding='same',activation='relu')) \nmodel.add(BatchNormalization(momentum=0.9, epsilon=1e-5, gamma_initializer=\"uniform\"))\nmodel.add(LeakyReLU(alpha=0.1))#2nd Convol Layer\nmodel.add(MaxPooling2D(pool_size=(2,2),padding='same'))\nmodel.add(Dropout(0.3))\n\nmodel.add(Flatten())  #Flatten #No Neurons here\nmodel.add(Dense(64,activation='relu')) \nmodel.add(Dense(10,activation='softmax'))\n# Final 10 Output Layer\n\nmodel.summary()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['accuracy'])\nhistory = model.fit_generator(\n      train_d.flow(X_train,Y_train, batch_size=batch_size),\n      steps_per_epoch=100,\n      epochs=epochs,\n      callbacks=[LearningRateScheduler(lr_decay),es           \n               ],\n      validation_data=valid_d.flow(X_valid1,Y_valid1),\n      validation_steps=10,  \n      verbose=2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"preds_Val=model.predict_classes(X_val/255)\naccuracy_score(preds_Val, Y_val)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_test= test.drop(['id'],axis=1).values\nX_test = X_test.reshape(X_test.shape[0],28,28,1)\nX_test.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predictions = model.predict_classes(X_test/255.)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = pd.read_csv('../input/Kannada-MNIST/sample_submission.csv')\nsubmission['label'] = predictions\nsubmission.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission.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}