{"cells":[{"metadata":{},"cell_type":"markdown","source":"* Run Below Snippet to get all the data."},{"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":"**Steps:**\n* Importing data from kaggle repo.\n* verifiying the teat data"},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"#importing data from csv file and creating dataframes\nkannada_test_data = pd.read_csv('/kaggle/input/Kannada-MNIST/test.csv')\nkannada_train_data =pd.read_csv('/kaggle/input/Kannada-MNIST/train.csv')\nkannada_dig_data = pd.read_csv('/kaggle/input/Kannada-MNIST/Dig-MNIST.csv')\n\n#verifying data \nprint(kannada_test_data.head())\nprint(kannada_train_data.head())\nprint(kannada_dig_data.head())\n\n#printing the shapes of the dataframes \nprint(kannada_test_data.shape, kannada_train_data.shape, kannada_dig_data.shape)\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"    checking the number of image entries avialable for each image "},{"metadata":{"trusted":true},"cell_type":"code","source":"kannada_train_data['label'].value_counts().sort_index()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"kannada_dig_data['label'].value_counts().sort_index()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"creating training output and features dataframe from given data. "},{"metadata":{"trusted":true},"cell_type":"code","source":"X = kannada_train_data.drop(['label'], axis=1).values\nY = kannada_train_data['label']\nX_test = kannada_test_data.drop(['id'], axis=1).values\nX_test_1 = kannada_dig_data.drop(['label'], axis=1).values\nY_test_1 = kannada_dig_data['label']\n\n#verifying data frame sizes \nprint(X.shape, Y.shape, X_test.shape, X_test_1.shape, Y_test_1.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n# look at some of the digits from train dataset\nplt.figure(figsize=(15,6))\nfor i in range(40):  \n    plt.subplot(4, 10, i+1)\n    plt.imshow(X[i].reshape((28,28)),cmap=plt.cm.binary)\n    plt.title(\"label=%d\" % Y[i],y=0.9)\n    plt.axis('off')\nplt.subplots_adjust(wspace=0.3, hspace=-0.1)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"    creat training and test data from training data"},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nX_train, X_devtest, Y_train, Y_devtest = train_test_split(X, Y, test_size = 0.2)\n\nprint(X_train.shape, Y_train.shape)\nprint(X_devtest.shape, Y_devtest.shape)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Prepare the data for use in CNN"},{"metadata":{"trusted":true},"cell_type":"code","source":"#preparing data for CNN\n\n#reshape flattend data into 3D tensor & standarize the value in the dataset by dividing by 255\n\nn_x = 28 \ntrain_img = X_train.reshape((-1,n_x,n_x, 1)).astype('float32')/255\ndev_img = X_devtest.reshape((-1,n_x,n_x,1)).astype('float32')/255\ntest_img = X_test.reshape((-1,n_x,n_x,1)).astype('float32')/255\ndig_img = X_test_1.reshape((-1,n_x,n_x,1)).astype('float32')/255\nprint(train_img.shape, dev_img.shape, test_img.shape, dig_img.shape)\n\n#one-hot encode the labels in Y_train, Y_devtest, Y_test_1\n\nfrom keras.utils.np_utils import to_categorical\ntrain_labels = to_categorical(Y_train)\ndev_labels = to_categorical(Y_devtest)\ndig_labels = to_categorical(Y_test_1)\n\nprint(train_labels.shape, dev_labels.shape, dig_labels.shape)\nprint(Y_test_1[8],dig_labels[8])\n\nplt.figure(figsize=(1,1))\nplt.imshow(X_test_1[8].reshape((28,28)), cmap=plt.cm.binary)\nplt.show()\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"raw","source":"    creating CNN Model "},{"metadata":{"trusted":true},"cell_type":"code","source":"#use keras data generator to augment the training set\n\nfrom keras_preprocessing.image import ImageDataGenerator\ndata_augment = ImageDataGenerator(rotation_range =10, zoom_range =0.1, width_shift_range =0.1, height_shift_range = 0.1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras import models \nfrom keras import layers\n\nmodel = models.Sequential()\nmodel.add(layers.Conv2D(16, kernel_size=3, padding ='same', activation = 'relu', input_shape=(28,28,1)))\nmodel.add(layers.Conv2D(32, kernel_size =5, padding= 'same', activation = 'relu'))\nmodel.add(layers.MaxPooling2D(pool_size=(2,2)))\nmodel.add(layers.Dropout(rate=0.4))\nmodel.add(layers.Conv2D(64, kernel_size = 5, activation= 'relu'))\nmodel.add(layers.MaxPooling2D(pool_size=(2,2)))\nmodel.add(layers.Dropout(rate=0.4))\nmodel.add(layers.Conv2D(128,kernel_size=3,activation = 'relu'))\nmodel.add(layers.Flatten())\nmodel.add(layers.Dense(256, activation = 'relu'))\nmodel.add(layers.Dropout(rate=0.4))\nmodel.add(layers.Dense(10,activation = 'softmax'))\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"compile the model "},{"metadata":{"trusted":true},"cell_type":"code","source":"#compiling model \n\nmodel.compile(optimizer ='adam', loss='categorical_crossentropy',metrics = ['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nepochs = 30\nbatch_size = 64\nhistory = model.fit_generator(data_augment.flow(train_img, train_labels, batch_size = batch_size),epochs=epochs, steps_per_epoch=train_img.shape[0]//batch_size,validation_data=(dev_img, dev_labels) )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Error Analysis \n\npred_dig = model.predict(dig_img)\npred_dig_labels = []\nfor i in range(len(dig_img)):\n    pred_dig_label = np.argmax(pred_dig[i])\n    pred_dig_labels.append(pred_dig_label)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#finding the numbers which were right while prediction \n\nresult = pd.DataFrame(Y_test_1)\nresult['Y_pred'] = pred_dig_labels\nresult['correct'] = result['label'] - result['Y_pred']\nerror = result[result['correct'] != 0]\nerror_list = error.index\n\nprint('Number of error is :', len(error))\nprint('The incidents are : ', error_list)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# predict on test set\npredictions = model.predict(test_img)\nprint(predictions.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# set the predicted labels to be the one with the highest probability\npredicted_labels = []\nfor i in range(len(predictions)):\n    predicted_label = np.argmax(predictions[i])\n    predicted_labels.append(predicted_label)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# look at some of the predictions for test_X\nplt.figure(figsize=(15,6))\nfor i in range(40):  \n    plt.subplot(4, 10, i+1)\n    plt.imshow(test_img[i].reshape((28,28)),cmap=plt.cm.binary)\n    plt.title(\"predict=%d\" % predicted_labels[i],y=0.9)\n    plt.axis('off')\nplt.subplots_adjust(wspace=0.3, hspace=-0.1)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# creating submission file\nsubmission = pd.read_csv('../input/Kannada-MNIST/sample_submission.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# generate submission file\n\n\nsubmission['label'] = predicted_labels\n\nsubmission.to_csv('submission.csv', index=False)\n\nprint(submission)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**As I am new to Kaggle and machine learning, i was not getting what to do. so I got the inspiration from [@Hoon Beng](https://www.kaggle.com/rhodiumbeng). it  looks like my code is copied from yours, but I learned a lot from your code. Thanks. **"}],"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}