{"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":"markdown","source":"# Digit Recognizer - Accuracy (97%-99.3%)","metadata":{}},{"cell_type":"markdown","source":"## Summary","metadata":{}},{"cell_type":"markdown","source":"### Here we focus on identifying handwriting images via CNN. The CNN architecture used is  -\n\n####   [[Conv2D->relu]*2 -> MaxPool2D -> Dropout]*2 -> Flatten -> Dense -> Dropout -> Out\n\n##### Conv2D is the first layer is which is used as a filter. The filters here can be seen as a transformation of the image. The CNN then maps these features from the transformed images. \n\n##### Next layer is the MaxPool2D layer which is used to reduce computational cost and reduce overfitting. It is more like a downsampling filter which picks it’s 2 neighbouring pixels and chooses the maximum value. We pick the pooling size and as the size increases the downsampling becomes more significant.\n\n##### Dropout is a regularization method, where a proportion of nodes in the layer are randomly ignored by setting their weights to zero for each training sample. This drops randomly a proportion of the network and forces the network to learn features in a distributed way. This technique also improves generalization and reduces the overfitting.\n\n##### We have used ReLu as the activation function. 'relu' is the rectifier (activation function max(0,x). which is used to add nonlinearity to the network.\n\n##### The Flatten layer is used to convert the final feature maps into a one single 1D vector. This flattening step is needed so that you can make use of fully connected layers after some convolutional/maxpool layers. It combines all the found local features of the previous convolutional layers.\n\n#### We have considered epochs to be 2 to computational time, it can be increased to 30 for a higher acuuracy.\n","metadata":{}},{"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\n%matplotlib inline\n\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\nimport itertools\n\nfrom keras.utils.np_utils import to_categorical # convert to one-hot-encoding\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D\nfrom tensorflow.keras.optimizers import RMSprop\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import ReduceLROnPlateau\n\n\n","metadata":{"execution":{"iopub.status.busy":"2021-10-16T16:48:35.608516Z","iopub.execute_input":"2021-10-16T16:48:35.608856Z","iopub.status.idle":"2021-10-16T16:48:35.618556Z","shell.execute_reply.started":"2021-10-16T16:48:35.608823Z","shell.execute_reply":"2021-10-16T16:48:35.617546Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 1. Load Data","metadata":{}},{"cell_type":"code","source":"train = pd.read_csv(r\"../input/digit-recognizer/train.csv\")\ntest = pd.read_csv(r\"../input/digit-recognizer/test.csv\")\n","metadata":{"execution":{"iopub.status.busy":"2021-10-16T16:48:36.277306Z","iopub.execute_input":"2021-10-16T16:48:36.277622Z","iopub.status.idle":"2021-10-16T16:48:41.549113Z","shell.execute_reply.started":"2021-10-16T16:48:36.277589Z","shell.execute_reply":"2021-10-16T16:48:41.548381Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"np.random.seed(7)\n","metadata":{"execution":{"iopub.status.busy":"2021-10-16T16:48:41.550453Z","iopub.execute_input":"2021-10-16T16:48:41.550660Z","iopub.status.idle":"2021-10-16T16:48:41.556902Z","shell.execute_reply.started":"2021-10-16T16:48:41.550636Z","shell.execute_reply":"2021-10-16T16:48:41.556013Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train = train.drop(labels = [\"label\"],axis = 1) \nY_train = train[\"label\"]\n\n\ndel train","metadata":{"execution":{"iopub.status.busy":"2021-10-16T16:48:41.558110Z","iopub.execute_input":"2021-10-16T16:48:41.558721Z","iopub.status.idle":"2021-10-16T16:48:41.685468Z","shell.execute_reply.started":"2021-10-16T16:48:41.558689Z","shell.execute_reply":"2021-10-16T16:48:41.684581Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 2. Data Preparation","metadata":{}},{"cell_type":"markdown","source":"#### 2.1 Check for missing values","metadata":{}},{"cell_type":"code","source":"X_train.isna().any().sum()","metadata":{"execution":{"iopub.status.busy":"2021-10-16T16:48:41.687753Z","iopub.execute_input":"2021-10-16T16:48:41.688560Z","iopub.status.idle":"2021-10-16T16:48:41.707469Z","shell.execute_reply.started":"2021-10-16T16:48:41.688515Z","shell.execute_reply":"2021-10-16T16:48:41.706843Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test.isna().any().sum()","metadata":{"execution":{"iopub.status.busy":"2021-10-16T16:48:41.708301Z","iopub.execute_input":"2021-10-16T16:48:41.708970Z","iopub.status.idle":"2021-10-16T16:48:41.722994Z","shell.execute_reply.started":"2021-10-16T16:48:41.708941Z","shell.execute_reply":"2021-10-16T16:48:41.722176Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 2.2 Reshape the image in 3 dimensions","metadata":{}},{"cell_type":"code","source":"# Reshape image in 3 dimensions (height = 28px, width = 28px , canal = 1)\nX_train = X_train.values.reshape(-1,28,28,1)\ntest = test.values.reshape(-1,28,28,1)","metadata":{"execution":{"iopub.status.busy":"2021-10-16T16:48:41.724097Z","iopub.execute_input":"2021-10-16T16:48:41.724398Z","iopub.status.idle":"2021-10-16T16:48:41.729133Z","shell.execute_reply.started":"2021-10-16T16:48:41.724370Z","shell.execute_reply":"2021-10-16T16:48:41.728206Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 2.3 Normalize the Data","metadata":{}},{"cell_type":"code","source":"X_train = X_train / 255.0\ntest = test / 255.0","metadata":{"execution":{"iopub.status.busy":"2021-10-16T16:48:41.730269Z","iopub.execute_input":"2021-10-16T16:48:41.730569Z","iopub.status.idle":"2021-10-16T16:48:41.938376Z","shell.execute_reply.started":"2021-10-16T16:48:41.730542Z","shell.execute_reply":"2021-10-16T16:48:41.937537Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 2.4 Encode labels to one hot vectors (ex : 3 -> [0,0,0,1,0,0,0,0,0,0])","metadata":{}},{"cell_type":"code","source":"\nY_train = to_categorical(Y_train, num_classes = 10)","metadata":{"execution":{"iopub.status.busy":"2021-10-16T16:48:41.939381Z","iopub.execute_input":"2021-10-16T16:48:41.939600Z","iopub.status.idle":"2021-10-16T16:48:41.945530Z","shell.execute_reply.started":"2021-10-16T16:48:41.939575Z","shell.execute_reply":"2021-10-16T16:48:41.944649Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nrandom_seed = 7","metadata":{"execution":{"iopub.status.busy":"2021-10-16T16:48:41.946684Z","iopub.execute_input":"2021-10-16T16:48:41.946864Z","iopub.status.idle":"2021-10-16T16:48:41.955526Z","shell.execute_reply.started":"2021-10-16T16:48:41.946841Z","shell.execute_reply":"2021-10-16T16:48:41.954965Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 2.5 Split the data in train and test set","metadata":{}},{"cell_type":"code","source":"X_train, X_val, Y_train, Y_val = train_test_split(X_train, Y_train, test_size = 0.1, random_state=random_seed)","metadata":{"execution":{"iopub.status.busy":"2021-10-16T16:48:41.957652Z","iopub.execute_input":"2021-10-16T16:48:41.958166Z","iopub.status.idle":"2021-10-16T16:48:42.361034Z","shell.execute_reply.started":"2021-10-16T16:48:41.958135Z","shell.execute_reply":"2021-10-16T16:48:42.360314Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\ng = plt.imshow(X_train[0][:,:,0])\nprint(Y_train[0])\n","metadata":{"execution":{"iopub.status.busy":"2021-10-16T16:48:42.362385Z","iopub.execute_input":"2021-10-16T16:48:42.362954Z","iopub.status.idle":"2021-10-16T16:48:42.591207Z","shell.execute_reply.started":"2021-10-16T16:48:42.362906Z","shell.execute_reply":"2021-10-16T16:48:42.590634Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"g = plt.imshow(X_train[2][:,:,0])\nprint(Y_train[2])","metadata":{"execution":{"iopub.status.busy":"2021-10-16T16:48:42.592297Z","iopub.execute_input":"2021-10-16T16:48:42.592572Z","iopub.status.idle":"2021-10-16T16:48:42.798705Z","shell.execute_reply.started":"2021-10-16T16:48:42.592543Z","shell.execute_reply":"2021-10-16T16:48:42.798169Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 3. CNN ","metadata":{}},{"cell_type":"code","source":"\n# CNN architechture followed is -> [[Conv2D->relu]*2 -> MaxPool2D -> Dropout]*2 -> Flatten -> Dense -> Dropout -> Out\n\nmodel = Sequential()\n\nmodel.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', \n                 activation ='relu', input_shape = (28,28,1)))\nmodel.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', \n                 activation ='relu'))\nmodel.add(MaxPool2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))\n\n\nmodel.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same', \n                 activation ='relu'))\nmodel.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same', \n                 activation ='relu'))\nmodel.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))\nmodel.add(Dropout(0.25))\n\n\nmodel.add(Flatten())\nmodel.add(Dense(256, activation = \"relu\"))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(10, activation = \"softmax\"))","metadata":{"execution":{"iopub.status.busy":"2021-10-16T16:48:42.799676Z","iopub.execute_input":"2021-10-16T16:48:42.800314Z","iopub.status.idle":"2021-10-16T16:48:42.971732Z","shell.execute_reply.started":"2021-10-16T16:48:42.800281Z","shell.execute_reply":"2021-10-16T16:48:42.971171Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Define the optimizer\noptimizer = RMSprop(learning_rate=0.001, rho=0.9, epsilon=1e-08, decay=0.0)","metadata":{"execution":{"iopub.status.busy":"2021-10-16T16:48:42.972594Z","iopub.execute_input":"2021-10-16T16:48:42.973237Z","iopub.status.idle":"2021-10-16T16:48:42.977286Z","shell.execute_reply.started":"2021-10-16T16:48:42.973202Z","shell.execute_reply":"2021-10-16T16:48:42.976471Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(optimizer = optimizer , loss = \"categorical_crossentropy\", metrics=[\"accuracy\"])","metadata":{"execution":{"iopub.status.busy":"2021-10-16T16:48:42.978512Z","iopub.execute_input":"2021-10-16T16:48:42.978768Z","iopub.status.idle":"2021-10-16T16:48:42.999800Z","shell.execute_reply.started":"2021-10-16T16:48:42.978741Z","shell.execute_reply":"2021-10-16T16:48:42.998834Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Set a learning rate annealer\nlearning_rate_reduction = ReduceLROnPlateau(monitor='val_acc', \n                                            patience=3, \n                                            verbose=1, \n                                            factor=0.5, \n                                            min_lr=0.00001)","metadata":{"execution":{"iopub.status.busy":"2021-10-16T16:48:43.001178Z","iopub.execute_input":"2021-10-16T16:48:43.001871Z","iopub.status.idle":"2021-10-16T16:48:43.008032Z","shell.execute_reply.started":"2021-10-16T16:48:43.001829Z","shell.execute_reply":"2021-10-16T16:48:43.006887Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 3.1 Data Augmentation","metadata":{}},{"cell_type":"code","source":"##### We use data augmentation to prevent overfitting and boost accuracy\n\ndatagen = ImageDataGenerator(\n        featurewise_center=False,  # set input mean to 0 over the dataset\n        samplewise_center=False,  # set each sample mean to 0\n        featurewise_std_normalization=False,  # divide inputs by std of the dataset\n        samplewise_std_normalization=False,  # divide each input by its std\n        zca_whitening=False,  # apply ZCA whitening\n        rotation_range=10,  # randomly rotate images in the range (degrees, 0 to 180)\n        zoom_range = 0.05, # Randomly zoom image \n        width_shift_range=0.1,  # randomly shift images horizontally (fraction of total width)\n        height_shift_range=0.1,  # randomly shift images vertically (fraction of total height)\n        horizontal_flip=False,  # randomly flip images\n        vertical_flip=False)  # randomly flip images\n\n\ndatagen.fit(X_train)","metadata":{"execution":{"iopub.status.busy":"2021-10-16T16:48:43.009616Z","iopub.execute_input":"2021-10-16T16:48:43.010542Z","iopub.status.idle":"2021-10-16T16:48:43.110291Z","shell.execute_reply.started":"2021-10-16T16:48:43.010501Z","shell.execute_reply":"2021-10-16T16:48:43.109701Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Fit the model\nhistory = model.fit(datagen.flow(X_train,Y_train, batch_size=86),\n                              epochs = 2, validation_data = (X_val,Y_val),\n                              verbose = 2, steps_per_epoch=X_train.shape[0] // 86\n                              , callbacks=[learning_rate_reduction])","metadata":{"execution":{"iopub.status.busy":"2021-10-16T16:48:43.111553Z","iopub.execute_input":"2021-10-16T16:48:43.112438Z","iopub.status.idle":"2021-10-16T16:51:23.486856Z","shell.execute_reply.started":"2021-10-16T16:48:43.112393Z","shell.execute_reply":"2021-10-16T16:51:23.485864Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 4. Confusion Matrix","metadata":{}},{"cell_type":"code","source":"# Look at confusion matrix \n\ndef plot_confusion_matrix(cm, classes,\n                          normalize=False,\n                          title='Confusion matrix',\n                          cmap=plt.cm.Blues):\n    plt.imshow(cm, interpolation='nearest', cmap=cmap)\n    plt.title(title)\n    plt.colorbar()\n    tick_marks = np.arange(len(classes))\n    plt.xticks(tick_marks, classes, rotation=45)\n    plt.yticks(tick_marks, classes)\n\n    if normalize:\n        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n\n    thresh = cm.max() / 2.\n    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n        plt.text(j, i, cm[i, j],\n                 horizontalalignment=\"center\",\n                 color=\"white\" if cm[i, j] > thresh else \"black\")\n\n    plt.tight_layout()\n    plt.ylabel('True label')\n    plt.xlabel('Predicted label')\n\nY_pred = model.predict(X_val)\nY_pred_classes = np.argmax(Y_pred,axis = 1) \n# Convert validation observations to one hot vectors\nY_true = np.argmax(Y_val,axis = 1) \nconfusion_mtx = confusion_matrix(Y_true, Y_pred_classes) \nplot_confusion_matrix(confusion_mtx, classes = range(10),cmap=\"rocket_r\") ","metadata":{"execution":{"iopub.status.busy":"2021-10-16T16:51:23.490056Z","iopub.execute_input":"2021-10-16T16:51:23.490387Z","iopub.status.idle":"2021-10-16T16:51:26.754420Z","shell.execute_reply.started":"2021-10-16T16:51:23.490350Z","shell.execute_reply":"2021-10-16T16:51:26.753504Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n# Errors are difference between predicted labels and true labels\nerrors = (Y_pred_classes - Y_true != 0)\n\nY_pred_classes_errors = Y_pred_classes[errors]\nY_pred_errors = Y_pred[errors]\nY_true_errors = Y_true[errors]\nX_val_errors = X_val[errors]\n\ndef display_errors(errors_index,img_errors,pred_errors, obs_errors):\n    n = 0\n    nrows = 2\n    ncols = 4\n    fig, ax = plt.subplots(nrows,ncols,sharex=True,sharey=True)\n    for row in range(nrows):\n        for col in range(ncols):\n            error = errors_index[n]\n            ax[row,col].imshow((img_errors[error]).reshape((28,28)))\n            ax[row,col].set_title(\"Pred. Label :{}\\nTrue label :{}\".format(pred_errors[error],obs_errors[error]))\n            n += 1\n            \nY_pred_errors_prob = np.max(Y_pred_errors,axis = 1)\n\n# Predicted probabilities of the true values in the error set\ntrue_prob_errors = np.diagonal(np.take(Y_pred_errors, Y_true_errors, axis=1))\n\n# Difference between the probability of the predicted label and the true label\ndelta_pred_true_errors = Y_pred_errors_prob - true_prob_errors\n\n# Sorted list of the delta prob errors\nsorted_dela_errors = np.argsort(delta_pred_true_errors)\n\n# Top 8 errors \nmost_important_errors = sorted_dela_errors[-8:]\n\n# Show the top 8 errors\ndisplay_errors(most_important_errors, X_val_errors, Y_pred_classes_errors, Y_true_errors)","metadata":{"execution":{"iopub.status.busy":"2021-10-16T16:51:26.755559Z","iopub.execute_input":"2021-10-16T16:51:26.755780Z","iopub.status.idle":"2021-10-16T16:51:27.631929Z","shell.execute_reply.started":"2021-10-16T16:51:26.755754Z","shell.execute_reply":"2021-10-16T16:51:27.630856Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"results = model.predict(test)\n\nresults = np.argmax(results,axis = 1)\n\nresults = pd.Series(results,name=\"Label\")","metadata":{"execution":{"iopub.status.busy":"2021-10-16T16:51:27.633230Z","iopub.execute_input":"2021-10-16T16:51:27.633498Z","iopub.status.idle":"2021-10-16T16:51:43.992894Z","shell.execute_reply.started":"2021-10-16T16:51:27.633468Z","shell.execute_reply":"2021-10-16T16:51:43.992122Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission = pd.concat([pd.Series(range(1,28001),name = \"ImageId\"),results],axis = 1)\n\nsubmission.to_csv(r\"../submission.csv,index=False\")","metadata":{"execution":{"iopub.status.busy":"2021-10-16T16:51:51.191996Z","iopub.execute_input":"2021-10-16T16:51:51.192293Z","iopub.status.idle":"2021-10-16T16:51:51.281615Z","shell.execute_reply.started":"2021-10-16T16:51:51.192254Z","shell.execute_reply":"2021-10-16T16:51:51.280782Z"},"trusted":true},"execution_count":null,"outputs":[]}]}