{"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":"from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom sklearn.model_selection import train_test_split\nfrom keras.utils.np_utils import to_categorical\nfrom tensorflow.keras.optimizers import RMSprop\nfrom keras.callbacks import ReduceLROnPlateau\nfrom sklearn.metrics import confusion_matrix\nfrom keras.models import Sequential\nimport matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport pandas as pd\nimport numpy as np\n%matplotlib inline\n\nnp.random.seed(2)\n\nimport itertools\n\nsns.set(style='white', context='notebook', palette='deep')","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2021-11-27T03:27:46.967369Z","iopub.execute_input":"2021-11-27T03:27:46.968059Z","iopub.status.idle":"2021-11-27T03:27:52.444623Z","shell.execute_reply.started":"2021-11-27T03:27:46.967970Z","shell.execute_reply":"2021-11-27T03:27:52.443844Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 2. Data Preparation","metadata":{}},{"cell_type":"markdown","source":"### 2.1 Load Data","metadata":{}},{"cell_type":"code","source":"train = pd.read_csv('../input/digit-recognizer/train.csv')\ntest = pd.read_csv(\"../input/digit-recognizer/test.csv\")","metadata":{"execution":{"iopub.status.busy":"2021-11-27T03:27:52.447729Z","iopub.execute_input":"2021-11-27T03:27:52.447979Z","iopub.status.idle":"2021-11-27T03:27:57.723517Z","shell.execute_reply.started":"2021-11-27T03:27:52.447949Z","shell.execute_reply":"2021-11-27T03:27:57.722704Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_train = train['label']\n\nX_train = train.drop(labels = ['label'], axis=1)\n\ndel train\n\ng = sns.countplot(y_train)\n\ny_train.value_counts()","metadata":{"execution":{"iopub.status.busy":"2021-11-27T03:27:57.726769Z","iopub.execute_input":"2021-11-27T03:27:57.726975Z","iopub.status.idle":"2021-11-27T03:27:58.107888Z","shell.execute_reply.started":"2021-11-27T03:27:57.726950Z","shell.execute_reply":"2021-11-27T03:27:58.107187Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 2.2 Check for null and missing values","metadata":{}},{"cell_type":"code","source":"X_train.isnull().any().describe()","metadata":{"execution":{"iopub.status.busy":"2021-11-27T03:27:58.109768Z","iopub.execute_input":"2021-11-27T03:27:58.110639Z","iopub.status.idle":"2021-11-27T03:27:58.129413Z","shell.execute_reply.started":"2021-11-27T03:27:58.110598Z","shell.execute_reply":"2021-11-27T03:27:58.128647Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test.isnull().any().describe()","metadata":{"execution":{"iopub.status.busy":"2021-11-27T03:27:58.130873Z","iopub.execute_input":"2021-11-27T03:27:58.131137Z","iopub.status.idle":"2021-11-27T03:27:58.146558Z","shell.execute_reply.started":"2021-11-27T03:27:58.131103Z","shell.execute_reply":"2021-11-27T03:27:58.145727Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 2.3 Normalization","metadata":{}},{"cell_type":"code","source":"X_train = X_train / 255.0\ntest = test / 255.0","metadata":{"execution":{"iopub.status.busy":"2021-11-27T03:27:58.148090Z","iopub.execute_input":"2021-11-27T03:27:58.148338Z","iopub.status.idle":"2021-11-27T03:27:58.313649Z","shell.execute_reply.started":"2021-11-27T03:27:58.148305Z","shell.execute_reply":"2021-11-27T03:27:58.312911Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 2.4 Reshape","metadata":{}},{"cell_type":"code","source":"# Reshape image in 3 dimensions (height=28px, width=28px, channel=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-11-27T03:27:58.315057Z","iopub.execute_input":"2021-11-27T03:27:58.315311Z","iopub.status.idle":"2021-11-27T03:27:58.321299Z","shell.execute_reply.started":"2021-11-27T03:27:58.315279Z","shell.execute_reply":"2021-11-27T03:27:58.320313Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Gray-scale = 1D vector of 784 values being reshaped to 28x28x1 3D matrices\nRGB-images = 3 Channels 28x28x3 3D matrices","metadata":{}},{"cell_type":"markdown","source":"### 2.5 Label Encoding","metadata":{}},{"cell_type":"code","source":"y_train = to_categorical(y_train, num_classes=10)","metadata":{"execution":{"iopub.status.busy":"2021-11-27T03:27:58.323033Z","iopub.execute_input":"2021-11-27T03:27:58.323347Z","iopub.status.idle":"2021-11-27T03:27:58.330643Z","shell.execute_reply.started":"2021-11-27T03:27:58.323309Z","shell.execute_reply":"2021-11-27T03:27:58.330020Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Labels are 10 digits from 0 to 9","metadata":{}},{"cell_type":"markdown","source":"### 2.6 Split training and validation set","metadata":{}},{"cell_type":"code","source":"random_seed = 2","metadata":{"execution":{"iopub.status.busy":"2021-11-27T03:27:58.332295Z","iopub.execute_input":"2021-11-27T03:27:58.332598Z","iopub.status.idle":"2021-11-27T03:27:58.337091Z","shell.execute_reply.started":"2021-11-27T03:27:58.332564Z","shell.execute_reply":"2021-11-27T03:27:58.336440Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-11-27T03:27:58.340425Z","iopub.execute_input":"2021-11-27T03:27:58.341227Z","iopub.status.idle":"2021-11-27T03:27:58.719136Z","shell.execute_reply.started":"2021-11-27T03:27:58.341176Z","shell.execute_reply":"2021-11-27T03:27:58.718404Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"g = plt.imshow(X_train[0][:,:,0])","metadata":{"execution":{"iopub.status.busy":"2021-11-27T03:27:58.720294Z","iopub.execute_input":"2021-11-27T03:27:58.720804Z","iopub.status.idle":"2021-11-27T03:27:58.972012Z","shell.execute_reply.started":"2021-11-27T03:27:58.720765Z","shell.execute_reply":"2021-11-27T03:27:58.971342Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 3. CNN","metadata":{}},{"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Conv2D(filters = 32, kernel_size=(5,5), padding='Same',\n                 activation='relu', input_shape=(28,28,1)))\n\nmodel.add(Conv2D(filters = 32, kernel_size=(5,5), padding='Same',\n                 activation='relu', input_shape=(28,28,1)))\n\nmodel.add(MaxPool2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))\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'))\n\nmodel.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))\nmodel.add(Dropout(0.25))\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-11-27T03:27:58.973678Z","iopub.execute_input":"2021-11-27T03:27:58.973925Z","iopub.status.idle":"2021-11-27T03:28:01.266908Z","shell.execute_reply.started":"2021-11-27T03:27:58.973891Z","shell.execute_reply":"2021-11-27T03:28:01.266126Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 3.2 Optimizer and annealer","metadata":{}},{"cell_type":"code","source":"optimizer = RMSprop(learning_rate=0.001, rho=0.9, epsilon=1e-08, decay=0.0)","metadata":{"execution":{"iopub.status.busy":"2021-11-27T03:28:01.267986Z","iopub.execute_input":"2021-11-27T03:28:01.269639Z","iopub.status.idle":"2021-11-27T03:28:01.274311Z","shell.execute_reply.started":"2021-11-27T03:28:01.269598Z","shell.execute_reply":"2021-11-27T03:28:01.273555Z"},"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-11-27T03:28:01.275413Z","iopub.execute_input":"2021-11-27T03:28:01.275705Z","iopub.status.idle":"2021-11-27T03:28:01.290910Z","shell.execute_reply.started":"2021-11-27T03:28:01.275669Z","shell.execute_reply":"2021-11-27T03:28:01.290069Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Set learning rate\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-11-27T03:28:01.293252Z","iopub.execute_input":"2021-11-27T03:28:01.293461Z","iopub.status.idle":"2021-11-27T03:28:01.300703Z","shell.execute_reply.started":"2021-11-27T03:28:01.293435Z","shell.execute_reply":"2021-11-27T03:28:01.299683Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"epochs = 25\nbatch_size = 96","metadata":{"execution":{"iopub.status.busy":"2021-11-27T03:28:01.302274Z","iopub.execute_input":"2021-11-27T03:28:01.302593Z","iopub.status.idle":"2021-11-27T03:28:01.309726Z","shell.execute_reply.started":"2021-11-27T03:28:01.302554Z","shell.execute_reply":"2021-11-27T03:28:01.308894Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 3.3 Data Augmentation","metadata":{}},{"cell_type":"code","source":"# Training without augmentations\nhistory = model.fit(X_train, y_train, batch_size=batch_size, epochs=epochs,\n                    validation_data=(X_val, y_val), verbose=2)","metadata":{"execution":{"iopub.status.busy":"2021-11-27T03:28:01.312551Z","iopub.execute_input":"2021-11-27T03:28:01.313067Z","iopub.status.idle":"2021-11-27T03:28:58.370934Z","shell.execute_reply.started":"2021-11-27T03:28:01.313032Z","shell.execute_reply":"2021-11-27T03:28:58.370210Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Augmentations\ndatagen = ImageDataGenerator(featurewise_center = False,\n                             samplewise_center = False,\n                             featurewise_std_normalization=False,\n                             samplewise_std_normalization=False,\n                             zca_whitening=False,\n                             rotation_range=10,\n                             zoom_range=0.1,\n                             width_shift_range=0.1,\n                             height_shift_range=0.1,\n                             horizontal_flip=False,\n                             vertical_flip=False)\n\ndatagen.fit(X_train)","metadata":{"execution":{"iopub.status.busy":"2021-11-27T03:30:34.550179Z","iopub.execute_input":"2021-11-27T03:30:34.550449Z","iopub.status.idle":"2021-11-27T03:30:34.646053Z","shell.execute_reply.started":"2021-11-27T03:30:34.550418Z","shell.execute_reply":"2021-11-27T03:30:34.645305Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Fit augmentation model\nhistory_aug = model.fit_generator(datagen.flow(X_train, y_train, batch_size=batch_size),\n                             epochs=epochs, validation_data=(X_val, y_val),\n                             verbose=2, steps_per_epoch=X_train.shape[0] // batch_size,\n                             callbacks=[learning_rate_reduction])","metadata":{"execution":{"iopub.status.busy":"2021-11-27T03:30:36.147730Z","iopub.execute_input":"2021-11-27T03:30:36.148203Z","iopub.status.idle":"2021-11-27T03:37:38.417610Z","shell.execute_reply.started":"2021-11-27T03:30:36.148166Z","shell.execute_reply":"2021-11-27T03:37:38.416743Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 4. Evaluate the Model","metadata":{}},{"cell_type":"markdown","source":"### 4.1 Train and val curves","metadata":{}},{"cell_type":"code","source":"# For non-augmented data\nfig, ax = plt.subplots(2,1)\nax[0].plot(history.history['loss'], color='b', label='Training loss')\nax[0].plot(history.history['val_loss'], color='r', label='validation loss', axes=ax[0])\nlegend = ax[0].legend(loc='best', shadow=True)\n\nax[1].plot(history.history['accuracy'], color='b', label='Training accuracy')\nax[1].plot(history.history['val_accuracy'], color='r', label='Validation accuracy')\n\nlegend = ax[1].legend(loc='best', shadow=True)","metadata":{"execution":{"iopub.status.busy":"2021-11-27T03:47:08.145204Z","iopub.execute_input":"2021-11-27T03:47:08.145460Z","iopub.status.idle":"2021-11-27T03:47:08.709263Z","shell.execute_reply.started":"2021-11-27T03:47:08.145424Z","shell.execute_reply":"2021-11-27T03:47:08.708562Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# For augmented data\nfig, ax = plt.subplots(2,1)\nax[0].plot(history_aug.history['loss'], color='b', label='Training loss')\nax[0].plot(history_aug.history['val_loss'], color='r', label='validation loss', axes=ax[0])\nlegend = ax[0].legend(loc='best', shadow=True)\n\nax[1].plot(history_aug.history['accuracy'], color='b', label='Training accuracy')\nax[1].plot(history_aug.history['val_accuracy'], color='r', label='Validation accuracy')\n\nlegend = ax[1].legend(loc='best', shadow=True)","metadata":{"execution":{"iopub.status.busy":"2021-11-27T03:47:10.102544Z","iopub.execute_input":"2021-11-27T03:47:10.103364Z","iopub.status.idle":"2021-11-27T03:47:10.550730Z","shell.execute_reply.started":"2021-11-27T03:47:10.103323Z","shell.execute_reply":"2021-11-27T03:47:10.550023Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 4.2 Confusion Matrix","metadata":{}},{"cell_type":"code","source":"def plot_confusion_matrix(cm, classes, normalize=False, 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\")","metadata":{"execution":{"iopub.status.busy":"2021-11-27T03:47:16.432793Z","iopub.execute_input":"2021-11-27T03:47:16.433426Z","iopub.status.idle":"2021-11-27T03:47:16.441893Z","shell.execute_reply.started":"2021-11-27T03:47:16.433377Z","shell.execute_reply":"2021-11-27T03:47:16.440950Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_pred = model.predict(X_val)\ny_pred_classes = np.argmax(y_pred, axis=1)\n\ny_true = np.argmax(y_val, axis=1)\n\nconfusion_mtx = confusion_matrix(y_true, y_pred_classes)\n\nplot_confusion_matrix(confusion_mtx, classes = range(10))","metadata":{"execution":{"iopub.status.busy":"2021-11-27T03:47:23.236406Z","iopub.execute_input":"2021-11-27T03:47:23.236999Z","iopub.status.idle":"2021-11-27T03:47:24.646590Z","shell.execute_reply.started":"2021-11-27T03:47:23.236956Z","shell.execute_reply":"2021-11-27T03:47:24.645873Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"accuracy_score = model.evaluate(X_val, y_pred, verbose=2)","metadata":{"execution":{"iopub.status.busy":"2021-11-27T03:52:03.609297Z","iopub.execute_input":"2021-11-27T03:52:03.610224Z","iopub.status.idle":"2021-11-27T03:52:03.953011Z","shell.execute_reply.started":"2021-11-27T03:52:03.610180Z","shell.execute_reply":"2021-11-27T03:52:03.952212Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"## Display wrong result\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 = 3\n    fig, ax = plt.subplots(nrows, ncols, sharex=True, sharey=True)\n    \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(\"Predicted 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)\ntrue_prob_errors = np.diagonal(np.take(y_pred_errors, y_true_errors, axis=1))\n\ndelta_pred_true_errors = y_pred_errors_prob - true_prob_errors\n\nsorted_delta_errors = np.argsort(delta_pred_true_errors)\n\nmost_important_errors = sorted_delta_errors[-6:]\n\n# show 6 top errors\ndisplay_errors(most_important_errors, X_val_errors, \n               y_pred_classes_errors, y_true_errors)","metadata":{"execution":{"iopub.status.busy":"2021-11-27T03:49:17.913970Z","iopub.execute_input":"2021-11-27T03:49:17.914235Z","iopub.status.idle":"2021-11-27T03:49:18.604774Z","shell.execute_reply.started":"2021-11-27T03:49:17.914205Z","shell.execute_reply":"2021-11-27T03:49:18.603965Z"},"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-11-27T03:49:32.459619Z","iopub.execute_input":"2021-11-27T03:49:32.460165Z","iopub.status.idle":"2021-11-27T03:49:34.099681Z","shell.execute_reply.started":"2021-11-27T03:49:32.460116Z","shell.execute_reply":"2021-11-27T03:49:34.098884Z"},"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(\"cnn_mnist_prdictions.csv\", index=False)","metadata":{"execution":{"iopub.status.busy":"2021-11-27T03:53:01.553083Z","iopub.execute_input":"2021-11-27T03:53:01.553329Z","iopub.status.idle":"2021-11-27T03:53:01.605281Z","shell.execute_reply.started":"2021-11-27T03:53:01.553300Z","shell.execute_reply":"2021-11-27T03:53:01.604621Z"},"trusted":true},"execution_count":null,"outputs":[]}]}