{"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":"Libs","metadata":{}},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport itertools\nimport tensorflow as tf\nfrom tensorflow import keras \nimport seaborn as sns","metadata":{"execution":{"iopub.status.busy":"2022-04-30T12:16:47.496734Z","iopub.execute_input":"2022-04-30T12:16:47.497349Z","iopub.status.idle":"2022-04-30T12:16:52.31731Z","shell.execute_reply.started":"2022-04-30T12:16:47.497256Z","shell.execute_reply":"2022-04-30T12:16:52.31652Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Reading 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')","metadata":{"execution":{"iopub.status.busy":"2022-04-30T12:16:52.320699Z","iopub.execute_input":"2022-04-30T12:16:52.320917Z","iopub.status.idle":"2022-04-30T12:16:57.309706Z","shell.execute_reply.started":"2022-04-30T12:16:52.32089Z","shell.execute_reply":"2022-04-30T12:16:57.308938Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train=train.astype(np.uint8)","metadata":{"execution":{"iopub.status.busy":"2022-04-30T12:16:57.312859Z","iopub.execute_input":"2022-04-30T12:16:57.313065Z","iopub.status.idle":"2022-04-30T12:16:57.343851Z","shell.execute_reply.started":"2022-04-30T12:16:57.31304Z","shell.execute_reply":"2022-04-30T12:16:57.343179Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"len(train),len(test)","metadata":{"execution":{"iopub.status.busy":"2022-04-30T12:16:57.346526Z","iopub.execute_input":"2022-04-30T12:16:57.346778Z","iopub.status.idle":"2022-04-30T12:16:57.354087Z","shell.execute_reply.started":"2022-04-30T12:16:57.346735Z","shell.execute_reply":"2022-04-30T12:16:57.353231Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.info()","metadata":{"execution":{"iopub.status.busy":"2022-04-30T12:16:57.355547Z","iopub.execute_input":"2022-04-30T12:16:57.356185Z","iopub.status.idle":"2022-04-30T12:16:57.412124Z","shell.execute_reply.started":"2022-04-30T12:16:57.356146Z","shell.execute_reply":"2022-04-30T12:16:57.411314Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Splitting the data into train and validation steps","metadata":{}},{"cell_type":"code","source":"X = train.drop(columns=['label'])      # Reading the images by not including the labels\ny = train['label']                     # Reading all the labels","metadata":{"execution":{"iopub.status.busy":"2022-04-30T12:16:57.413566Z","iopub.execute_input":"2022-04-30T12:16:57.413863Z","iopub.status.idle":"2022-04-30T12:16:57.47829Z","shell.execute_reply.started":"2022-04-30T12:16:57.413824Z","shell.execute_reply":"2022-04-30T12:16:57.477178Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X = X / 255.0","metadata":{"execution":{"iopub.status.busy":"2022-04-30T12:16:57.480727Z","iopub.execute_input":"2022-04-30T12:16:57.481335Z","iopub.status.idle":"2022-04-30T12:16:57.576657Z","shell.execute_reply.started":"2022-04-30T12:16:57.481289Z","shell.execute_reply":"2022-04-30T12:16:57.575888Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test = test / 255.0","metadata":{"execution":{"iopub.status.busy":"2022-04-30T12:16:57.578132Z","iopub.execute_input":"2022-04-30T12:16:57.578406Z","iopub.status.idle":"2022-04-30T12:16:57.651315Z","shell.execute_reply.started":"2022-04-30T12:16:57.578369Z","shell.execute_reply":"2022-04-30T12:16:57.650539Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test=test.values.reshape(-1,28,28,1)","metadata":{"execution":{"iopub.status.busy":"2022-04-30T12:16:57.652557Z","iopub.execute_input":"2022-04-30T12:16:57.652828Z","iopub.status.idle":"2022-04-30T12:16:57.660349Z","shell.execute_reply.started":"2022-04-30T12:16:57.652792Z","shell.execute_reply":"2022-04-30T12:16:57.659599Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X=X.values.reshape(-1,28,28,1)","metadata":{"execution":{"iopub.status.busy":"2022-04-30T12:16:57.664628Z","iopub.execute_input":"2022-04-30T12:16:57.664835Z","iopub.status.idle":"2022-04-30T12:16:57.669616Z","shell.execute_reply.started":"2022-04-30T12:16:57.664811Z","shell.execute_reply":"2022-04-30T12:16:57.668704Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.imshow(X[3], cmap = 'gray');","metadata":{"execution":{"iopub.status.busy":"2022-04-30T12:16:57.671158Z","iopub.execute_input":"2022-04-30T12:16:57.671629Z","iopub.status.idle":"2022-04-30T12:16:57.87624Z","shell.execute_reply.started":"2022-04-30T12:16:57.671588Z","shell.execute_reply":"2022-04-30T12:16:57.875583Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y = keras.utils.to_categorical(y, num_classes = 10,dtype='uint8')","metadata":{"execution":{"iopub.status.busy":"2022-04-30T12:16:57.877809Z","iopub.execute_input":"2022-04-30T12:16:57.878282Z","iopub.status.idle":"2022-04-30T12:16:58.722009Z","shell.execute_reply.started":"2022-04-30T12:16:57.878245Z","shell.execute_reply":"2022-04-30T12:16:58.721253Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nX_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2,random_state=0,stratify=y)","metadata":{"execution":{"iopub.status.busy":"2022-04-30T12:16:58.724016Z","iopub.execute_input":"2022-04-30T12:16:58.72421Z","iopub.status.idle":"2022-04-30T12:16:59.840868Z","shell.execute_reply.started":"2022-04-30T12:16:58.724185Z","shell.execute_reply":"2022-04-30T12:16:59.8401Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"len(X_train),len(X_test),len(y_train),len(y_test)","metadata":{"execution":{"iopub.status.busy":"2022-04-30T12:16:59.842032Z","iopub.execute_input":"2022-04-30T12:16:59.843969Z","iopub.status.idle":"2022-04-30T12:16:59.850165Z","shell.execute_reply.started":"2022-04-30T12:16:59.843936Z","shell.execute_reply":"2022-04-30T12:16:59.849505Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train.shape","metadata":{"execution":{"iopub.status.busy":"2022-04-30T12:16:59.851208Z","iopub.execute_input":"2022-04-30T12:16:59.851672Z","iopub.status.idle":"2022-04-30T12:16:59.859102Z","shell.execute_reply.started":"2022-04-30T12:16:59.851635Z","shell.execute_reply":"2022-04-30T12:16:59.858275Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Creating the model","metadata":{}},{"cell_type":"code","source":"# From https://www.kaggle.com/code/ahmed121ashraf131/mnist-simple-cnn-knn-accuracy-100-top-1 good CNN\n\nmodel = keras.models.Sequential()\n\nmodel.add(keras.layers.Conv2D(filters = 64, kernel_size = (5,5),padding = 'Same', activation ='relu', input_shape = (28,28,1)))\nmodel.add(keras.layers.BatchNormalization())\n\nmodel.add(keras.layers.Conv2D(filters = 64, kernel_size = (5,5),padding = 'Same', activation ='relu'))\nmodel.add(keras.layers.BatchNormalization())\n\nmodel.add(keras.layers.MaxPool2D(pool_size=(2,2)))\nmodel.add(keras.layers.Dropout(0.25))\n\nmodel.add(keras.layers.Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same', activation ='relu'))\nmodel.add(keras.layers.BatchNormalization())\n\nmodel.add(keras.layers.Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same', activation ='relu'))\nmodel.add(keras.layers.BatchNormalization())\nmodel.add(keras.layers.MaxPool2D(pool_size=(2,2), strides=(2,2)))\nmodel.add(keras.layers.Dropout(0.25))\n\nmodel.add(keras.layers.Conv2D(filters = 64, kernel_size = (3,3), padding = 'Same',  activation ='relu'))\nmodel.add(keras.layers.BatchNormalization())\nmodel.add(keras.layers.Dropout(0.25))\n\nmodel.add(keras.layers.Flatten())\nmodel.add(keras.layers.Dense(256, activation = \"relu\"))\nmodel.add(keras.layers.BatchNormalization())\nmodel.add(keras.layers.Dropout(0.25))\n\nmodel.add(keras.layers.Dense(10, activation = \"softmax\"))\n","metadata":{"execution":{"iopub.status.busy":"2022-04-30T12:16:59.860451Z","iopub.execute_input":"2022-04-30T12:16:59.861242Z","iopub.status.idle":"2022-04-30T12:17:02.208048Z","shell.execute_reply.started":"2022-04-30T12:16:59.861204Z","shell.execute_reply":"2022-04-30T12:17:02.207304Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.utils import plot_model\nplot_model(model, to_file='model.png', show_shapes=True)\nfrom IPython.display import Image\nImage(\"model.png\")","metadata":{"execution":{"iopub.status.busy":"2022-04-30T12:17:02.209115Z","iopub.execute_input":"2022-04-30T12:17:02.209691Z","iopub.status.idle":"2022-04-30T12:17:03.075435Z","shell.execute_reply.started":"2022-04-30T12:17:02.209635Z","shell.execute_reply":"2022-04-30T12:17:03.074682Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"batch_size=128\nepochs=49","metadata":{"execution":{"iopub.status.busy":"2022-04-30T12:17:03.076779Z","iopub.execute_input":"2022-04-30T12:17:03.077015Z","iopub.status.idle":"2022-04-30T12:17:03.081631Z","shell.execute_reply.started":"2022-04-30T12:17:03.076985Z","shell.execute_reply":"2022-04-30T12:17:03.081059Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"optimizer = tf.keras.optimizers.RMSprop(lr=0.006, rho=0.9, epsilon=1e-08, decay=0.0)","metadata":{"execution":{"iopub.status.busy":"2022-04-30T12:17:03.082854Z","iopub.execute_input":"2022-04-30T12:17:03.083727Z","iopub.status.idle":"2022-04-30T12:17:03.092905Z","shell.execute_reply.started":"2022-04-30T12:17:03.083688Z","shell.execute_reply":"2022-04-30T12:17:03.091949Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(optimizer = optimizer , loss = \"categorical_crossentropy\", metrics=[\"accuracy\"])","metadata":{"execution":{"iopub.status.busy":"2022-04-30T12:17:03.094768Z","iopub.execute_input":"2022-04-30T12:17:03.095135Z","iopub.status.idle":"2022-04-30T12:17:03.11272Z","shell.execute_reply.started":"2022-04-30T12:17:03.095094Z","shell.execute_reply":"2022-04-30T12:17:03.1118Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"learning_rate_reduction = keras.callbacks.ReduceLROnPlateau(monitor='val_accuracy', \n                                            patience=2, \n                                            verbose=1, \n                                            factor=0.6, \n                                            min_lr=0.00001)","metadata":{"execution":{"iopub.status.busy":"2022-04-30T12:17:03.114657Z","iopub.execute_input":"2022-04-30T12:17:03.115157Z","iopub.status.idle":"2022-04-30T12:17:03.119679Z","shell.execute_reply.started":"2022-04-30T12:17:03.115114Z","shell.execute_reply":"2022-04-30T12:17:03.119019Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"datagen = keras.preprocessing.image.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\ndatagen.fit(X_train)","metadata":{"execution":{"iopub.status.busy":"2022-04-30T12:26:13.536424Z","iopub.execute_input":"2022-04-30T12:26:13.536649Z","iopub.status.idle":"2022-04-30T12:26:13.622109Z","shell.execute_reply.started":"2022-04-30T12:26:13.536621Z","shell.execute_reply":"2022-04-30T12:26:13.621322Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit_generator(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_rate_reduction])","metadata":{"execution":{"iopub.status.busy":"2022-04-30T12:17:03.213127Z","iopub.execute_input":"2022-04-30T12:17:03.213375Z","iopub.status.idle":"2022-04-30T12:26:09.014187Z","shell.execute_reply.started":"2022-04-30T12:17:03.213343Z","shell.execute_reply":"2022-04-30T12:26:09.013378Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig, 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\")\nlegend = ax[1].legend(loc='best', shadow=True)","metadata":{"execution":{"iopub.status.busy":"2022-04-30T12:26:09.016792Z","iopub.execute_input":"2022-04-30T12:26:09.017315Z","iopub.status.idle":"2022-04-30T12:26:09.320221Z","shell.execute_reply.started":"2022-04-30T12:26:09.017276Z","shell.execute_reply":"2022-04-30T12:26:09.319543Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Visualizing and Testing on custom data","metadata":{}},{"cell_type":"code","source":"from sklearn.metrics import confusion_matrix\ndef plot_confusion_matrix(cm, classes,\n                          normalize=False,\n                          title='Confusion matrix',\n                          cmap=plt.cm.Blues):\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_test)\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_test,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":{"execution":{"iopub.status.busy":"2022-04-30T12:26:15.467711Z","iopub.execute_input":"2022-04-30T12:26:15.468287Z","iopub.status.idle":"2022-04-30T12:26:16.777066Z","shell.execute_reply.started":"2022-04-30T12:26:15.468249Z","shell.execute_reply":"2022-04-30T12:26:16.775302Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"results = model.predict(test)\nresults = np.argmax(results,axis = 1)\nresults = pd.Series(results,name=\"Label\")","metadata":{"execution":{"iopub.status.busy":"2022-04-30T12:26:16.778735Z","iopub.execute_input":"2022-04-30T12:26:16.779011Z","iopub.status.idle":"2022-04-30T12:26:18.658615Z","shell.execute_reply.started":"2022-04-30T12:26:16.778975Z","shell.execute_reply":"2022-04-30T12:26:18.65781Z"},"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(\"Submission.csv\",index=False)","metadata":{"execution":{"iopub.status.busy":"2022-04-30T12:26:18.661182Z","iopub.execute_input":"2022-04-30T12:26:18.661639Z","iopub.status.idle":"2022-04-30T12:26:18.708549Z","shell.execute_reply.started":"2022-04-30T12:26:18.661598Z","shell.execute_reply":"2022-04-30T12:26:18.707793Z"},"trusted":true},"execution_count":null,"outputs":[]}]}