{"cells":[{"metadata":{"trusted":true,"_uuid":"6f0bb736724124c43dfb1ee6f0d31e6e57a06863"},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"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\nnp.random.seed(2)\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 keras.optimizers import RMSprop\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import ReduceLROnPlateau\n\n\nsns.set(style='white', context='notebook', palette='deep')","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"train = pd.read_csv(\"../input/train.csv\")\ntest = pd.read_csv(\"../input/test.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"8bc4163995a30ac69d2090c383cc1e679b05bfcc"},"cell_type":"code","source":"train.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"8a61cc76a4531ce6cd7a5bf8728baadc997cd72d"},"cell_type":"code","source":"Y_train=train.label\nX_train = train.drop(labels = [\"label\"],axis = 1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"b0f60acd1af75285c6dc06df9fe404a0db31f5ae"},"cell_type":"code","source":"print(X_train.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"3529d1f25b56bb732b4a4a81a87fb1f20ea179d4"},"cell_type":"code","source":"del train\ng=sns.countplot(Y_train)\nY_train.value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a5a10df31ff8ad82f2efdcf100626cef6dd6fa7f"},"cell_type":"code","source":"X_train.isnull().any().describe()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"922e7f7965d6d92209f2effee809891faa5ffc60"},"cell_type":"code","source":"test.isnull().any().value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"48ce12372e4e46f4bf8ca048639c98d7e0e28437"},"cell_type":"code","source":"X_train=X_train/255.0\ntest=test/255.0","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f45cfef2c918d2f74ccb6245fae838b31cb55317"},"cell_type":"code","source":"X_train=X_train.values.reshape(-1,28,28,1)\ntest=test.values.reshape(-1,28,28,1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a0814d2cab726a56b384944664f68d925d511c08"},"cell_type":"code","source":"Y_train = to_categorical(Y_train, num_classes = 10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"1daeed0adb4efecbadcbabe232e31522064efbd0"},"cell_type":"code","source":"random_seed=2\nX_train,X_val,Y_train,Y_val=train_test_split(X_train,Y_train,test_size=0.1,random_state=random_seed)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"10905ed1185f88eb46a87415fc744e5f7f4e56a7"},"cell_type":"code","source":"plt.imshow(X_train[0][:,:,0])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"909436cda29ed35f2df5060d6204097a64b73f83"},"cell_type":"code","source":"model= Sequential()\nmodel.add(Conv2D(filters=32,kernel_size=(5,5),padding='Same',activation='relu',input_shape=(28,28,1)))\nmodel.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', activation ='relu'))\nmodel.add(MaxPool2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(filters=64, kernel_size=(3,3),padding ='Same',activation= 'relu'))\nmodel.add(Conv2D(filters=64,kernel_size=(3,3),padding='Same',activation='relu'))\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.25))\nmodel.add(Dense(10,activation='softmax'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f988ad67d18f84d7e7acacda4c3bf2b21bce505e"},"cell_type":"code","source":"Optimizer=RMSprop(lr=.001,rho=0.9,epsilon=1e-8)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"99d1198c5f3251a02a0d6bf6b3968d00cdd2946f"},"cell_type":"code","source":"    model.compile(optimizer = Optimizer , loss = \"categorical_crossentropy\", metrics=[\"accuracy\"])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"8a6440cd2e5ca2896062c41f5b5dea37e6c9f84f"},"cell_type":"code","source":"learning_rate_reduction= ReduceLROnPlateau(monitor=\"val_acc\",patience=3,verbose=1,factor=0.5,min_lr=.00001)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"dd98d70e4a3adc88b2f6d74e4383286946bf7127"},"cell_type":"code","source":"epochs= 1\nbatch_size=86","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"37e1524d86b9c4f471458ae1c005480ef7bc5251"},"cell_type":"code","source":"model.fit(X_train,Y_train,batch_size=batch_size,epochs=epochs,validation_data=(X_val,Y_val),verbose=2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"142e09ef99cea8fe7b9009cf149665e107539342"},"cell_type":"code","source":"datagen = ImageDataGenerator(\n        rotation_range=10, \n        zoom_range = 0.1,\n        width_shift_range=0.1, \n        height_shift_range=0.1)  \ndatagen.fit(X_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"2d7c99b38bfd292e65ccf6bfff97db43e3770bee"},"cell_type":"code","source":"history= model.fit_generator(datagen.flow(X_train,Y_train,batch_size=batch_size),epochs=epochs,validation_data=(X_val,Y_val),verbose=2,steps_per_epoch=X_train.shape[0],callbacks=[learning_rate_reduction])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"123594e447917d97f3047abe3040eabb8e48765f"},"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['acc'], color='b', label=\"Training accuracy\")\nax[1].plot(history.history['val_acc'], color='r',label=\"Validation accuracy\")\nlegend = ax[1].legend(loc='best', shadow=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"252c90a00ad95497456a2b16061c950a47b9cf30"},"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    \"\"\"\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)) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"c3b867664c13f5439c0d79be5aa4ba3c509eb61b"},"cell_type":"code","source":"# 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)))\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)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a875a04210173d3e4759fa24ab18e566aba1bfa2"},"cell_type":"code","source":"# predict results\nresults = model.predict(test)\n\n# select the indix with the maximum probability\nresults = np.argmax(results,axis = 1)\n\nresults = pd.Series(results,name=\"Label\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"e879db2319c8405fbb1c047ed22e4fc6dfab04e2"},"cell_type":"code","source":"submission = pd.concat([pd.Series(range(1,28001),name = \"ImageId\"),results],axis = 1)\n\nsubmission.to_csv(\"mnistdeep.csv\",index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"0956d95ffeeb8f5db7d149ad97c9839763889776"},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"1027b429fe47a5f3a9649e2cd142de9caaaf9e88"},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"328a18d0ea3585d8530ed1d88a4142d237c78e6e"},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"b178deb0fb5269bd2d66df4b0d63da7243eb2125"},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"75787207d35c73ce555c953acc417f370eaf8750"},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"1a6712d7dcec2d1429783ac9f19d00228291b08d"},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f863b2d7950830b047eba9bb45bb67293e5ea12b"},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"e33329ab7eba7d53378f3b3e495184fd35f54c9d"},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"5ef13acc00d39148b0a76a95ceeb41ccac2b1bbe"},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"d0e4e65c0b2a8d21de87ba0eb01c649dd44daefd"},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"882a92d43340f522fc46083469e4a2c72a81ad44"},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f4ccf0a6171f7b22e89b30c13b9eb637b1674b01"},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"c2e55e2e75303948935092b9d32771f7c6fd06d2"},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}