{"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_minor":4,"nbformat":4,"cells":[{"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.","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Imports","metadata":{}},{"cell_type":"code","source":"import tensorflow as tf\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sns\n\nfrom sklearn.metrics import precision_score\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\n\ntrain=pd.read_csv('../input/Kannada-MNIST/train.csv')\ntest=pd.read_csv('../input/Kannada-MNIST/test.csv')\nsample_sub=pd.read_csv('../input/Kannada-MNIST/sample_submission.csv')","metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Visualising data","metadata":{}},{"cell_type":"code","source":"img = train.drop('label',axis=1)\n\nimg = img.to_numpy()\none = img[0].reshape(28,28)\ntwo = img[1].reshape(28,28)\nthree = img[2].reshape(28,28)\nfour = img[3].reshape(28,28)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.imshow(one)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Normalization","metadata":{}},{"cell_type":"code","source":"training_labels=train.label\n\ntraining_images=train.drop('label',axis=1)\n  \n# Normalizing and reshaping data\ntraining_images=training_images.values.reshape(-1, 28, 28, 1)\ntraining_images=training_images / 255.0","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"training_labels = training_labels.to_numpy()\ntraining_labels = training_labels.reshape(-1,1)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Encoding","metadata":{}},{"cell_type":"code","source":"enc = OneHotEncoder(handle_unknown='ignore', sparse=False)\ntraining_labels = enc.fit_transform(training_labels)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"training_labels = pd.DataFrame(training_labels)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train, X_test, Y_train, Y_test = train_test_split(training_images, training_labels, test_size=0.2, random_state=20)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Creating model","metadata":{}},{"cell_type":"code","source":"def train_mnist_conv():  \n    # Creating model\n    model = tf.keras.models.Sequential([\n            tf.keras.layers.Conv2D(64, (3,3), input_shape=(28, 28, 1)),\n            tf.keras.layers.PReLU(alpha_initializer='zeros'),\n            tf.keras.layers.MaxPooling2D(2, 2, padding='same'),\n#             tf.keras.layers.Conv2D(32, (3,3)),\n#             tf.keras.layers.PReLU(alpha_initializer='zeros'),\n#             tf.keras.layers.MaxPooling2D(2, 2, padding='same'),\n            tf.keras.layers.Flatten(),\n            tf.keras.layers.Dense(512, activation='relu'),\n            tf.keras.layers.Dense(10, activation='softmax')\n    ])\n\n    model.compile(optimizer='adam', loss='categorical_crossentropy', metrics = ['accuracy', tf.keras.metrics.Precision(), tf.keras.metrics.Recall()])\n    return model\n    \nnew_model = train_mnist_conv()\nnew_model.summary()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = new_model.fit(X_train, Y_train, epochs = 10)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Accuracy and loss ","metadata":{}},{"cell_type":"code","source":"acc = history.history['accuracy']\nloss = history.history['loss']\n \nepochs = range(len(acc))\n \nplt.plot(epochs, acc, 'r', label='Training accuracy')\nplt.title('Traaining accuracy')\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.legend(loc=0)\nplt.figure()\n \nplt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"loss_train = history.history['loss']\n\nplt.plot(loss_train, 'g', label='Training loss')\nplt.title('Training Loss')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.legend()\nplt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Evaluating model","metadata":{}},{"cell_type":"code","source":"X_test = X_test.reshape(-1, 28, 28, 1)\nX_test = X_test/255.0","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"preds = new_model.predict(X_test)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"new_model.evaluate(X_test, Y_test)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Y_test = Y_test.to_numpy()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"new_preds = np.argmax(preds, axis=1)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"new_truth = np.argmax(Y_test, axis=1)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Confusion Matrix\ncm = confusion_matrix(new_truth, new_preds)\nplt.figure(figsize=(8,8))\nsns.heatmap(cm, fmt='.0f', annot=True, linewidths=0.2, linecolor='purple')\nplt.xlabel('predicted value')\nplt.ylabel('Truth value')\nplt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_id=test.id\n\ntest_images=test.drop('id',axis=1)\n\ntest_val=test.id\n\ntest_images = test_images.values.reshape(-1, 28, 28, 1)\ntest_images=test_images/255.0\n\ny_pre=new_model.predict(test_images)     #making prediction\ny_pre=np.argmax(y_pre,axis=1) #changing the prediction intro labels\n\nsample_sub['label']=y_pre\nsample_sub.to_csv('submission.csv',index=False)\n\nsample_sub.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}