{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 5GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import numpy as np # linear algebra\nimport matplotlib.pyplot as plt\n%matplotlib inline\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from 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, BatchNormalization\nfrom keras.optimizers import Adam\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import LearningRateScheduler","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# read train \ntrain = pd.read_csv(\"../input/digit-recognizer/train.csv\")\nprint(\"Shape of train data : \" ,train.shape)\nprint(\"Train data :\")\n\ntrain.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# read test \ntest= pd.read_csv(\"../input/digit-recognizer/test.csv\")\nprint(\"Shape of test data : \" ,test.shape)\nprint(\"Test data :\")\n\ntest.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_train, x_val, y_train, y_val = train_test_split(train.drop(\"label\",axis=1) , train[\"label\"], test_size=0.1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# visualize number of digits classes\nimport seaborn as sns\nplt.figure(figsize=(15,7))\ng = sns.countplot(y_train, palette=\"icefire\")\nplt.title(\"Number of digit classes\")\ny_train.value_counts()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"From the data we can conclude that all the labels are balanced","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"fig= plt.figure( figsize=(30,6))\nplt.plot(x_train.iloc[0])\nplt.title('784x1 data')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# plot some samples\nfig, ((ax1, ax2),(ax3,ax4)) = plt.subplots(ncols=2,nrows=2 , figsize=(14,14))\nimg = x_train.iloc[0].to_numpy()\nimg = img.reshape((28,28))\nax1.imshow(img,cmap='gray')\n\nimg = x_train.iloc[1].to_numpy()\nimg = img.reshape((28,28))\nax2.imshow(img,cmap='gray')\n\nimg = x_train.iloc[28].to_numpy()\nimg = img.reshape((28,28))\nax3.imshow(img,cmap='gray')\n\nimg = x_train.iloc[30].to_numpy()\nimg = img.reshape((28,28))\nax4.imshow(img,cmap='gray')\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Normalising data :\n\nWe perform a grayscale normalization to reduce the effect of illumination's differences.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# Normalize the data\nx_train = x_train / 255.0\ntest = test / 255.0\nprint(\"x_train shape: \",x_train.shape)\nprint(\"test shape: \",test.shape)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Reshaping the data :\n\nWe reshape the data of (28 x 28) to 28x28x1 3D matrices .Keras needs an extra dimension in the end which correspond to channels. Our images are gray scaled so it use only one channel.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# Reshape\nx_train = x_train.values.reshape(-1,28,28,1)\ntest = test.values.reshape(-1,28,28,1)\nprint(\"x_train shape: \",x_train.shape)\nprint(\"test shape: \",test.shape)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Label encoding the data :\nTo take care of the labels ","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# Label Encoding \nfrom keras.utils.np_utils import to_categorical \n# convert to one-hot-encoding\ny_train = to_categorical(y_train, num_classes = 10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_train","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Split the train and the validation set for the fitting\nfrom sklearn.model_selection import train_test_split\nX_train, X_val, Y_train, Y_val = train_test_split(x_train, y_train, test_size = 0.33, random_state=2)\nprint(\"x_train shape\",X_train.shape)\nprint(\"x_test shape\",X_val.shape)\nprint(\"y_train shape\",Y_train.shape)\nprint(\"y_test shape\",Y_val.shape)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Data Augmentation:\n\nTo avoid overfitting problem, we need to expand artificially our handwritten digit dataset.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# data augmentation\ndatagen = 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,   # dimesion reduction\n        rotation_range=0.5,    # randomly rotate images in the range 5 degrees\n        zoom_range = 0.5,      # Randomly zoom image 5%\n        width_shift_range=0.5, # randomly shift images horizontally 5%\n        height_shift_range=0.5,# randomly shift images vertically 5%\n        horizontal_flip=False, # randomly flip images\n        vertical_flip=False)   # randomly flip images\n\ndatagen.fit(X_train)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Visualising Augmented Data","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# plot some samples\nfig, ((ax1, ax2),(ax3,ax4)) = plt.subplots(ncols=2,nrows=2 , figsize=(14,14))\nimg = X_train[0]\nimg = img.reshape((28,28))\nax1.imshow(img,cmap='gray')\n\nimg = X_train[1]\nimg = img.reshape((28,28))\nax2.imshow(img,cmap='gray')\n\nimg = X_train[280]\nimg = img.reshape((28,28))\nax3.imshow(img,cmap='gray')\n\nimg = X_train[200]\nimg = img.reshape((28,28))\nax4.imshow(img,cmap='gray')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Building the CNN model :","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# Conv2D -> MaxPool2D -> Dropout -> Conv2D -> MaxPool2D -> Dropout \n# -> FULLY CONNECTED LAYER(Flatten -> Dense -> Dropout -> Dense)\n\n \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,Adam\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import ReduceLROnPlateau\n\nmodel = Sequential()\n#\nmodel.add(Conv2D(filters = 8, kernel_size = (5,5),padding = 'Same', \n                 activation ='relu', input_shape = (28,28,1)))\nmodel.add(MaxPool2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))\n#\nmodel.add(Conv2D(filters = 16, 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# fully connected layer \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":{},"cell_type":"markdown","source":"Defining Optimizer :","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# Define the optimizer\noptimizer = Adam(lr=0.001, beta_1=0.9, beta_2=0.999)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Compile model:","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# Compile the model\nmodel.compile(optimizer = optimizer , loss = \"categorical_crossentropy\", metrics=[\"accuracy\"])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Early stopping","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.callbacks import EarlyStopping,ReduceLROnPlateau\nearlystop = EarlyStopping(monitor='loss',patience=2,verbose=0,mode='min')\n# 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)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Fitting the model ","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# Fit the model\n\nhistory = model.fit_generator(datagen.flow(X_train,Y_train, batch_size=86),\n                              epochs = 15, validation_data = (X_val,Y_val), \n                              steps_per_epoch=X_train.shape[0]//86 ,callbacks = [learning_rate_reduction] )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"loss = pd.DataFrame(model.history.history)\nprint(\"Model History :\")\nloss","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"loss[['val_loss',\"loss\"]]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Plot the loss curves for training and validation \nloss[['val_loss',\"loss\"]].plot()\nplt.title(\"Loss\")\nplt.xlabel(\"Number of Epochs\")\nplt.ylabel(\"Loss\")\nplt.legend()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Plot the accuracy curves for training and validation \nloss[['val_accuracy',\"accuracy\"]].plot()\nplt.title(\"Accuracy\")\nplt.xlabel(\"Number of Epochs\")\nplt.ylabel(\"Accuracy\")\nplt.legend()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Confusion matrix :","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# confusion matrix\nimport seaborn as sns\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\nf,ax = plt.subplots(figsize=(14,14))\nsns.heatmap(confusion_mtx, annot=True, linewidths=0.01,cmap=\"icefire\",linecolor=\"gray\", fmt= '.1f',ax=ax)\nplt.xlabel(\"Predicted Label\")\nplt.ylabel(\"True Label\")\nplt.title(\"Confusion Matrix\")\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Visualising Wrong Predictions","execution_count":null},{"metadata":{"trusted":true},"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,figsize = (13,13))\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)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Visualising Correct Predictions:","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"\n# Right are difference between predicted labels and true labels\nright = (Y_pred_classes - Y_true == 0)\n\nY_pred_classes_errors = Y_pred_classes[right]\nY_pred_errors = Y_pred[right]\nY_true_errors = Y_true[right]\nX_val_errors = X_val[right]\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,figsize = (13,13))\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)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Making submission :","execution_count":null},{"metadata":{"trusted":true},"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\")\nsubmission = pd.concat([pd.Series(range(1,28001),name = \"ImageId\"),results],axis = 1)\n\nsubmission.to_csv(\"cnn_mnist_datagen.csv\",index=False)","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}