{"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":"## Reference notebooks\nhttps://www.kaggle.com/code/ayushksingh28/mnist-digit-classification-explore","metadata":{}},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport cv2 as cv\n\nimport tensorflow as tf\nimport tensorflow.keras as keras\nfrom tensorflow.keras import layers\nkeras.backend.set_image_data_format('channels_last')\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Conv2D, MaxPool2D, Flatten, Dropout\nfrom tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau\nfrom tensorflow.keras.optimizers import RMSprop\n\nfrom keras.preprocessing.image import ImageDataGenerator\n\nimport itertools","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-12-02T11:18:51.912634Z","iopub.execute_input":"2022-12-02T11:18:51.913016Z","iopub.status.idle":"2022-12-02T11:18:51.920471Z","shell.execute_reply.started":"2022-12-02T11:18:51.912984Z","shell.execute_reply":"2022-12-02T11:18:51.918802Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Loading the data","metadata":{}},{"cell_type":"code","source":"train = pd.read_csv('../input/digit-recognizer/train.csv')\ntest = pd.read_csv('../input/digit-recognizer/test.csv')\n\ntrain.head()","metadata":{"execution":{"iopub.status.busy":"2022-12-02T11:18:51.925614Z","iopub.execute_input":"2022-12-02T11:18:51.926659Z","iopub.status.idle":"2022-12-02T11:18:55.049158Z","shell.execute_reply.started":"2022-12-02T11:18:51.926599Z","shell.execute_reply":"2022-12-02T11:18:55.048144Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Cheking if there are null values in any image\ntrain.columns[train.isna().sum()>0]","metadata":{"execution":{"iopub.status.busy":"2022-12-02T11:18:55.051013Z","iopub.execute_input":"2022-12-02T11:18:55.052347Z","iopub.status.idle":"2022-12-02T11:18:55.100573Z","shell.execute_reply.started":"2022-12-02T11:18:55.052309Z","shell.execute_reply":"2022-12-02T11:18:55.099500Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Seeing the distribution of the  classes\nplt.figure(figsize=(10,6))\nplt.title(\"Distribution of classes\")\nsns.countplot(data=train, x=train.label, palette=\"pastel\")","metadata":{"execution":{"iopub.status.busy":"2022-12-02T11:18:55.102304Z","iopub.execute_input":"2022-12-02T11:18:55.102670Z","iopub.status.idle":"2022-12-02T11:18:55.367977Z","shell.execute_reply.started":"2022-12-02T11:18:55.102634Z","shell.execute_reply":"2022-12-02T11:18:55.366999Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"We are gonna visualize some digits now, to see how the images look and if there is noise.","metadata":{}},{"cell_type":"code","source":"fig, axes = plt.subplots(nrows=10,ncols=6, figsize=(20,40),sharey=True, sharex=True)\nidx = 0\nfor i in range(10):\n    for j in (train[train.label==i].sample(n=6).index):\n        digit = train['label'].loc[j]\n        idx += 1\n        plt.subplot(10,6,idx)\n        plt.imshow(np.array(train.iloc[j,1:]).reshape(28,28), cmap='gray')\n        plt.title(f'Digit {digit}',fontsize=14)\n        plt.grid(None)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-12-02T11:18:55.370769Z","iopub.execute_input":"2022-12-02T11:18:55.371128Z","iopub.status.idle":"2022-12-02T11:19:02.366292Z","shell.execute_reply.started":"2022-12-02T11:18:55.371068Z","shell.execute_reply":"2022-12-02T11:19:02.365389Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"There is some noise around certain numbers.\n\nWe are going to apply an OTSU thresholding.","metadata":{}},{"cell_type":"code","source":"fig, axes = plt.subplots(nrows=10,ncols=2, figsize=(20,40),sharey=True, sharex=True)\nidx = 0\nfor k in np.random.choice(range(42000), 10):\n    img = np.array(train.iloc[k,1:]).reshape(28,28)\n    idx += 1\n    plt.grid(None)        \n    plt.subplot(10,2,idx)\n    plt.imshow(img, cmap='gray')\n    plt.title(f'Original Image\\n Digit={train.iloc[k,0]}',fontsize=14)\n    idx +=1\n    plt.grid(None)    \n    plt.subplot(10,2,idx)\n    img = img.astype(\"uint8\")\n    ret,th = cv.threshold(img, 0, 255, cv.THRESH_BINARY+cv.THRESH_OTSU)\n    plt.imshow(th, cmap='gray')\n    plt.title('OTSU Binarization',fontsize=14)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-12-02T11:19:02.367671Z","iopub.execute_input":"2022-12-02T11:19:02.368213Z","iopub.status.idle":"2022-12-02T11:19:04.699231Z","shell.execute_reply.started":"2022-12-02T11:19:02.368175Z","shell.execute_reply":"2022-12-02T11:19:04.698247Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"As we can see, after OTSU binarization the numbers are much more defined.","metadata":{}},{"cell_type":"markdown","source":"## Splitting the data","metadata":{}},{"cell_type":"code","source":"X_train = train.drop(\"label\", axis = 1).copy()\nX_test = test.copy()\nY_train = train[\"label\"].copy()\n\nX_train = X_train/255.0\nX_test = X_test/255.0\n\nX_train = X_train.values.reshape(-1, 28, 28, 1)\nX_test = X_test.values.reshape(-1, 28, 28, 1)","metadata":{"execution":{"iopub.status.busy":"2022-12-02T11:19:04.700587Z","iopub.execute_input":"2022-12-02T11:19:04.701099Z","iopub.status.idle":"2022-12-02T11:19:05.456131Z","shell.execute_reply.started":"2022-12-02T11:19:04.701046Z","shell.execute_reply":"2022-12-02T11:19:05.455118Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"'''\n# Applying OTSU thresholding to all images in the dataset\n# Train dataset\ni=0\nfor img in X_train:\n    img = img.astype(\"uint8\")\n    ret,th = cv.threshold(img, 0, 255, cv.THRESH_BINARY+cv.THRESH_OTSU)\n    X_train[i] = np.array(th).reshape(-1, 28, 28, 1)\n    i = i+1\n\n# Test dataset\ni=0\nfor img in X_test:\n    img = img.astype(\"uint8\")\n    ret,th = cv.threshold(img, 0, 255, cv.THRESH_BINARY+cv.THRESH_OTSU)\n    X_test[i] = np.array(th).reshape(-1, 28, 28, 1)\n    i = i+1\n\nplt.imshow(X_train[0], cmap=\"gray\")\n'''","metadata":{"execution":{"iopub.status.busy":"2022-12-02T11:19:05.459802Z","iopub.execute_input":"2022-12-02T11:19:05.460107Z","iopub.status.idle":"2022-12-02T11:19:05.466296Z","shell.execute_reply.started":"2022-12-02T11:19:05.460069Z","shell.execute_reply":"2022-12-02T11:19:05.465258Z"},"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)","metadata":{"execution":{"iopub.status.busy":"2022-12-02T11:19:05.467742Z","iopub.execute_input":"2022-12-02T11:19:05.468502Z","iopub.status.idle":"2022-12-02T11:19:05.923338Z","shell.execute_reply.started":"2022-12-02T11:19:05.468467Z","shell.execute_reply":"2022-12-02T11:19:05.922270Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Get one-hot encoding\nY_train = keras.utils.to_categorical(Y_train, num_classes = 10)\nY_val = keras.utils.to_categorical(Y_val, num_classes = 10)","metadata":{"execution":{"iopub.status.busy":"2022-12-02T11:19:05.924901Z","iopub.execute_input":"2022-12-02T11:19:05.925599Z","iopub.status.idle":"2022-12-02T11:19:05.933625Z","shell.execute_reply.started":"2022-12-02T11:19:05.925563Z","shell.execute_reply":"2022-12-02T11:19:05.932734Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Creating the model","metadata":{}},{"cell_type":"code","source":"# In -> [[Conv2D->relu]*2 -> MaxPool2D -> Dropout]*2 -> Flatten -> Dense -> Dropout -> Out\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":"2022-12-02T11:19:05.940953Z","iopub.execute_input":"2022-12-02T11:19:05.943093Z","iopub.status.idle":"2022-12-02T11:19:06.044238Z","shell.execute_reply.started":"2022-12-02T11:19:05.943041Z","shell.execute_reply":"2022-12-02T11:19:06.042606Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Define the optimizer\noptimizer = RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0)\n\nmodel.compile(optimizer = optimizer, loss = \"CategoricalCrossentropy\", metrics = \"accuracy\")\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2022-12-02T11:19:06.045920Z","iopub.execute_input":"2022-12-02T11:19:06.046494Z","iopub.status.idle":"2022-12-02T11:19:06.063896Z","shell.execute_reply.started":"2022-12-02T11:19:06.046461Z","shell.execute_reply":"2022-12-02T11:19:06.062114Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"early_stop = EarlyStopping(monitor = \"val_loss\", patience = 7, restore_best_weights=True)","metadata":{"execution":{"iopub.status.busy":"2022-12-02T11:19:06.065030Z","iopub.execute_input":"2022-12-02T11:19:06.065410Z","iopub.status.idle":"2022-12-02T11:19:06.075853Z","shell.execute_reply.started":"2022-12-02T11:19:06.065365Z","shell.execute_reply":"2022-12-02T11:19:06.074498Z"},"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":"2022-12-02T11:19:06.077477Z","iopub.execute_input":"2022-12-02T11:19:06.078004Z","iopub.status.idle":"2022-12-02T11:19:06.084798Z","shell.execute_reply.started":"2022-12-02T11:19:06.077969Z","shell.execute_reply":"2022-12-02T11:19:06.083588Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Data Augmentation","metadata":{}},{"cell_type":"code","source":"datagen = 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.1, # 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":"2022-12-02T11:19:06.086259Z","iopub.execute_input":"2022-12-02T11:19:06.086756Z","iopub.status.idle":"2022-12-02T11:19:06.197170Z","shell.execute_reply.started":"2022-12-02T11:19:06.086715Z","shell.execute_reply":"2022-12-02T11:19:06.196131Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Model training","metadata":{}},{"cell_type":"code","source":"epochs = 50\nbatch_size = 128\nmodel.fit(datagen.flow(X_train,Y_train, batch_size=batch_size), \n          batch_size = batch_size,\n          epochs = epochs, validation_data = (X_val,Y_val),\n          verbose = 2, callbacks=[early_stop, learning_rate_reduction])","metadata":{"execution":{"iopub.status.busy":"2022-12-02T11:19:06.200980Z","iopub.execute_input":"2022-12-02T11:19:06.204031Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"metrics = pd.DataFrame(model.history.history)\nmetrics[[\"loss\",\"val_loss\"]].plot()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"metrics[[\"accuracy\", \"val_accuracy\"]].plot()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Predicting","metadata":{}},{"cell_type":"code","source":"def predict(model, X, imgs):\n    s = int(np.sqrt(imgs))\n    fig, ax = plt.subplots(s, s, sharex=True, sharey=True, figsize=(15, 15))\n    ax = ax.flatten()\n    preds = model.predict(X[:imgs])\n    for i in range(imgs):\n        y_pred = np.argmax(preds[i])\n        img = X[i].reshape(28, 28)\n        ax[i].imshow(img, cmap='Greys', interpolation='nearest')\n        ax[i].set_title(f'p: {y_pred}')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predict(model, X_test, 25)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Confusion Matrix","metadata":{}},{"cell_type":"code","source":"def plot_confusion_matrix(cm, classes,\n                          normalize=False,\n                          title='Confusion matrix',\n                          cmap=plt.cm.RdPu):\n    \"\"\"\n    This function prints and plots the confusion matrix.\n    Normalization can be applied by setting `normalize=True`.\n    \"\"\"\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\n# Predict the values from the validation dataset\nY_pred = model.predict(X_val)\n# Convert predictions classes to one hot vectors \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) \n# compute the confusion matrix\nconfusion_mtx = confusion_matrix(Y_true, Y_pred_classes) \n# plot the confusion matrix\nplot_confusion_matrix(confusion_mtx, classes = range(10))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Display some error results \n\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    \"\"\" This function shows 6 images with their predicted and real labels\"\"\"\n    n = 0\n    nrows = 2\n    ncols = 3\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)), cmap=\"gray\")\n            ax[row,col].set_title(\"Predicted label :{}\\nTrue label :{}\".format(pred_errors[error],obs_errors[error]))\n            n += 1\n\n# Probabilities of the wrong predicted numbers\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 6 errors \nmost_important_errors = sorted_dela_errors[-6:]\n\n# Show the top 6 errors\ndisplay_errors(most_important_errors, X_val_errors, Y_pred_classes_errors, Y_true_errors)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Final prediction","metadata":{}},{"cell_type":"code","source":"y_pred = model.predict(X_test)\ny_pred = np.argmax(y_pred, axis=1)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_pred = pd.Series(y_pred, name='Label')\nsub = pd.concat([pd.Series(range(1, 28001), name=\"ImageId\"), y_pred], axis=1)\nsub.to_csv(\"submission.csv\", index=False)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub.sample(2)","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}