{"cells":[{"metadata":{},"cell_type":"markdown","source":"Here we are trying to recognize a digit from given datasets. we have test data and training data. I am going to use Convolutional Neural Network (CNN) to identify the digit from it's pixels 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":"Importing required packages"},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport seaborn as sns","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Importing csv files and creating data frames from the them. "},{"metadata":{"trusted":true},"cell_type":"code","source":"#load data \n\ntrain_data = pd.read_csv('/kaggle/input/digit-recognizer/train.csv')\ntest_data = pd.read_csv('/kaggle/input/digit-recognizer/test.csv')\n\n#verifying data \n\nprint(train_data.head())\nprint(test_data.head())\n\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Create dataframes to train model "},{"metadata":{"trusted":true},"cell_type":"code","source":"Y_train = train_data['label']\n\n#drop columnm named label \n\nX_train = train_data.drop(labels = ['label'], axis = 1).values\nprint(X_train)\nprint(Y_train)\n\nX_test = test_data.values\n\nprint(X_test)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"verifying data"},{"metadata":{"trusted":true},"cell_type":"code","source":"#checking the counts for each label \nsns.countplot(Y_train)\n\nprint(Y_train.value_counts().sort_index())\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"    visulizing some of the labels from training data "},{"metadata":{"trusted":true},"cell_type":"code","source":"#making plot \nplt.figure(figsize=(15,6))\nfor i in range(30):\n    plt.subplot(3,10,i+1)\n    plt.imshow(X_train[i].reshape((28,28)),cmap = plt.cm.binary)\n    plt.title(\"label= %d\" % Y_train[i], y=0.9)\n    plt.axis('off')\nplt.subplots_adjust(wspace=0.2,hspace= 0.1)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"creating test and training data from given test data"},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nX, X_test_1, Y, Y_test_1 = train_test_split(X_train, Y_train, test_size = 0.2)\n\nprint(X.shape, Y.shape)\nprint(X_test_1.shape, Y_test_1.shape)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"    preparing training data for CNN model "},{"metadata":{"trusted":true},"cell_type":"code","source":"#reshape flattened data into 3D tensor & normalize the value in the dataset by dividingby 255\n\nn_x = 28\n\ntrain_img = X.reshape((-1,n_x,n_x,1)).astype('float32')/255\ndev_img = X_test_1.reshape((-1,n_x,n_x,1)).astype('float32')/255\ntest_img = X_test.reshape((-1,n_x,n_x,1)).astype('float32')/255\n\n\nprint(train_img.shape, dev_img.shape, test_img.shape)\n\n\n#encode the labels in Y, Y_test_1\n\nfrom keras.utils.np_utils import to_categorical \n\ntrain_label = to_categorical(Y)\ndev_label = to_categorical(Y_test_1)\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"    Creating CNN Model to train and predict the values based on input datafeames. \n    "},{"metadata":{"trusted":true},"cell_type":"code","source":"from 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)\n\n\n\nfrom 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', input_shape = (28,28,1)))\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 model "},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics = ['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"    Training model "},{"metadata":{"trusted":true},"cell_type":"code","source":"epochs = 5\nbatch_size = 64\nlog = model.fit_generator(data_augment.flow(train_img, train_label, batch_size = batch_size),epochs=epochs, steps_per_epoch=train_img.shape[0]//batch_size,validation_data=(dev_img, dev_label) )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#predict on test set \n\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)\n\n# 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('/kaggle/input/digit-recognizer/sample_submission.csv')\n\n# 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":{"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}