{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Importing Libraries\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"import pandas as pd  ## Processing\nimport numpy as np  ##Linear Algebra\nimport matplotlib.pyplot as plt ## Plots\nimport seaborn as sns\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\nimport itertools\n\nfrom keras.models import Sequential, load_model\nfrom keras.layers import Flatten, Dense, MaxPool2D, Conv2D, Dropout, BatchNormalization\nfrom keras.optimizers import RMSprop\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import ReduceLROnPlateau, EarlyStopping, ModelCheckpoint\nfrom tensorflow.keras.datasets import mnist\nfrom keras.utils.np_utils import to_categorical\n\nsns.set(style = 'white', context = 'notebook', palette = 'deep')\n\n%matplotlib inline","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Gathering Data Set"},{"metadata":{"trusted":true},"cell_type":"code","source":"## Loading train Dataset\n\ndf_train = pd.read_csv(\"../input/digit-recognizer/train.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"## A glimpse at the data\n\ndf_train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"## showing total values and columns\n\ndf_train.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Loading test data\n\ndf_test = pd.read_csv('../input/digit-recognizer/test.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"## A look at the test data\n\ndf_test.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"## values and colums of the test data\n\ndf_test.shape","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# EDA/Processing"},{"metadata":{"trusted":true},"cell_type":"code","source":"y_train = df_train['label']\n\nX_train = df_train.drop(labels = ['label'], axis = 1)\n\nhist = y_train.value_counts()\n\nhist.plot.bar()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"## checking for missing values in the data\n\ndf_train.isnull().sum()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"## Normalization\n\nX_train = X_train / 255.0\n\ndf_test = df_test / 255.0","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"## Reshape\n\nX_train = X_train.values.reshape(-1, 28,28, 1)\n\ndf_test = df_test.values.reshape(-1, 28,28, 1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"## Label Encoding\n\ny_train = to_categorical(y_train, num_classes = 10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"## Split training testing/training\n\nX_train, X_test, y_train, y_test = train_test_split(X_train, y_train, test_size\n                                                   = 0.1, random_state = 2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"## Showing split data\n\nprint('X_train shape: ', X_train.shape)\nprint('X_test shape: ', X_test.shape)\nprint('y_train shape: ', y_train.shape)\nprint('y_test shape: ', y_test.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"nrows = 2\n\nncols = 2\n\npic_indexes = np.random.randint(X_train.shape[0], size\n                             =(nrows * ncols))\n\nf, axs = plt.subplots(nrows, ncols, figsize = (12,9))\n\naxs = axs.flatten()\n\npicture_index = 0\n\nfor picture_index, ax in zip(pic_indexes, axs):\n    ax.imshow(X_train[picture_index].reshape(28, 28), cmap = 'gray')\n    \n    ax.set_title(f'Label: {y_train[picture_index]}')\n    \n    \nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"g = plt.imshow(X_train[0][:, :, 0])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_train[0]","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# CNN"},{"metadata":{"trusted":true},"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                \n\nmodel.add(Conv2D(filters = 32, kernel_size = (5,5), padding = 'Same', activation\n                 = 'relu'))\n\nmodel.add(MaxPool2D(pool_size = (2,2)))\nmodel.add(Dropout(0.25))\n\n\nmodel.add(Conv2D(filters = 64, kernel_size = (3,3), padding \n                = 'Same', activation = 'relu'))\nmodel.add(Conv2D(filters = 64, kernel_size = (3,3), padding\n                = 'Same', 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'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"optimizer = RMSprop(lr = 0.001, rho = 0.9, epsilon = 1e-08, decay\n                  = 0.0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(optimizer = optimizer, loss = 'categorical_crossentropy', metrics\n             = ['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learning_reduction = ReduceLROnPlateau(monitor = 'val_loss',\n                                     patience = 3,\n                                     verbose = 1,\n                                     factor = 0.5,\n                                     min_lr = 0.00001)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"epochs = 50 \n\nbatch_size = 86","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"****Augmentation****"},{"metadata":{"trusted":true},"cell_type":"code","source":"datagen = ImageDataGenerator(\n       \n        featurewise_center=False, \n       \n        samplewise_center=False,  \n       \n        featurewise_std_normalization=False, \n      \n        samplewise_std_normalization=False, \n      \n        zca_whitening=False,  \n       \n        rotation_range=10, \n       \n        zoom_range = 0.1,  \n        \n        width_shift_range=0.1,  \n            \n        height_shift_range=0.1, \n        \n        horizontal_flip=False,  \n        \n        vertical_flip=False) \n\n\ndatagen.fit(X_train)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit(datagen.flow(X_train,y_train, batch_size=batch_size),\n                              epochs = epochs, validation_data = (X_test,y_test),\n                              verbose = 2, steps_per_epoch=X_train.shape[0] // batch_size\n                              , callbacks=[learning_reduction])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def plot_confusion_matrix(cm, classes,\n                          normalize=False,\n                          title='Confusion matrix',\n                          cmap=plt.cm.Blues):\n    \n    \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\nY_pred = model.predict(X_test)\n \nY_pred_classes = np.argmax(Y_pred,axis = 1) \n\nY_true = np.argmax(y_test,axis = 1) \n\nconfusion_mtx = confusion_matrix(Y_true, Y_pred_classes) \n# plot the confusion matrix\nplot_confusion_matrix(confusion_mtx, classes = range(10))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"score = model.evaluate(X_test, y_test, verbose = 0)\n\nprint('Test Accuracy: ', score[1])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Tripple CNN"},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_newtriplecnn():\n    return Sequential([\n        Conv2D(32, kernel_size=(3, 3), activation='relu', padding='same', input_shape = (28,28,1)),\n        Conv2D(32, kernel_size=(3, 3), activation='relu', padding='same'),\n        BatchNormalization(),\n        MaxPool2D(pool_size=(2, 2)),\n        Dropout(0.25),\n        \n        Conv2D(64, kernel_size=(3, 3), activation='relu', padding='same'),\n        Conv2D(64, kernel_size=(3, 3), activation='relu', padding='same' ),\n        BatchNormalization(),\n        MaxPool2D(pool_size=(2, 2)),\n        Dropout(0.25),\n        \n        Conv2D(128, kernel_size=(3, 3), activation='relu', padding='same' ),\n        Conv2D(128, kernel_size=(3, 3), activation='relu', padding='same' ),\n        BatchNormalization(),\n        MaxPool2D(pool_size=(2, 2)),\n        Dropout(0.25),\n        \n        \n        Flatten(),\n          \n        Dense(512, activation='relu'),\n        BatchNormalization(),\n        Dropout(0.5),\n        \n        Dense(256, activation='relu'),\n        BatchNormalization(),\n        Dropout(0.4),\n        \n        Dense(64, activation='relu'),\n        BatchNormalization(),\n        Dropout(0.3),\n        \n        Dense(10, activation = \"softmax\")\n        \n    ])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = get_newtriplecnn()\n\nmodel.compile(optimizer = 'Adam', loss = 'categorical_crossentropy', metrics = ['accuracy'])\n\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"callbacks1 = [ \n    EarlyStopping(monitor = 'loss', patience = 6), \n    ReduceLROnPlateau(monitor = 'loss', patience = 3), \n    ModelCheckpoint('model.best.hdf5', save_best_only=True) # saving the best model\n]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit(datagen.flow(X_train, y_train, batch_size = batch_size), epochs = 50,\n                               steps_per_epoch = X_train.shape[0] // batch_size,\n                               validation_data = (X_test, y_test),\n                               callbacks = callbacks1,\n                             )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"result = model.predict(df_test)\n\nresult = np.argmax(result, axis=1)\n\nresult = pd.Series(result, name ='Label')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = pd.concat([pd.Series(range(1,28001),name = \"ImageId\"),result],axis = 1)\n\nsubmission.to_csv(\"./submission_cnn.csv\",index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","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":4}