{"cells":[{"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(0)\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\nsns.set(style = 'white', context = 'notebook', palette = 'deep')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Loading our data ...\n","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"train = pd.read_csv(\"../input/digit-recognizer/train.csv\")\ntest = pd.read_csv(\"../input/digit-recognizer/test.csv\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Extracting X_train and Y_train from train...","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"Y_train = train[\"label\"]\n\nX_train = train.drop(labels = [\"label\"], axis = 1)\ndel train \n\nY_train.value_counts()\nX_train ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"g = sns.countplot(Y_train)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Checking for missing or null values ...","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train.isnull().any().describe() ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test.isnull().any().describe()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"It's Looking good no values are null or missing !","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"### Normalizing...","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train = X_train / 255.0\ntest = test / 255.0\nX_train.shape","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### reshape into m x 28 x 28 x 1 shape needed for keras CNN","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train = np.reshape(X_train.values, (-1, 28, 28, 1))\nX_train.shape\ntest = np.reshape(test.values, (-1, 28, 28, 1))\ntest.shape","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### encoding Labels into one hot vectors...","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"Y_train = to_categorical(Y_train, num_classes = 10)\nY_train[1]","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Splitting Train dataset into train and dev(cross validation) set ","execution_count":null},{"metadata":{"trusted":true},"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)\nX_train.shape","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Visualising Our train data images...","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"idx = 5\ng = plt.imshow(X_train[idx][:,:,0])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Definning the model !","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Conv2D(filters = 32 , kernel_size = (5,5), activation = 'relu', padding = 'Same', input_shape = (28,28,1)))\nmodel.add(Conv2D(filters = 32, kernel_size = (5,5), activation = 'relu', padding = 'Same'))\nmodel.add(MaxPool2D(pool_size = (2,2)))\nmodel.add(Dropout(0.25))\n\n\nmodel.add(Conv2D(filters = 64 , kernel_size = (3,3), activation = 'relu', padding = 'Same'))\nmodel.add(Conv2D(filters = 32 , kernel_size = (3,3), activation = 'relu', padding = 'Same'))\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.5))\nmodel.add(Dense(10, activation = 'softmax' ))\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Setting an optimizer algorithm...","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"optimizer = RMSprop(lr = 0.001, decay = 0.0, epsilon = 1e-08)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Compiling the model ! ","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(optimizer = optimizer, loss = \"categorical_crossentropy\", metrics = [\"accuracy\"])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":" ### reducing the learning rate dynamically ","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"learning_rate_reduction = ReduceLROnPlateau(monitor='val_acc', factor=0.5, patience=3, verbose = 1, min_lr = 0.0001)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"epochs = 1\nbatch_size = 86","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#### Uncomment for fiting without data-aug, expecting 0.97-0.98 val_acc ","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"#history = model.fit(X_train, Y_train, batch_size = batch_size, epochs = epochs, verbose = 2, validation_data = (X_val ,Y_val))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Data Augmentation\nwithout data-aug we can expect a val_accuracy between 0.9790 and 0.98 depending on your number of epochs \nwith data-aug we can do even better...","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"datagen = ImageDataGenerator (featurewise_center = False,\n                              samplewise_center = False, \n                              featurewise_std_normalization = False,\n                              samplewise_std_normalization = False,\n                              zca_whitening=False,\n                              rotation_range = 10,\n                              zoom_range = 0.1,\n                              width_shift_range = 0.1,\n                              height_shift_range = 0.1,\n                              horizontal_flip = False,\n                              vertical_flip=False)\ndatagen.fit(X_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit_generator(datagen.flow(X_train, Y_train, batch_size = batch_size),epochs = epochs,\n validation_data = (X_val, Y_val),verbose = 1,steps_per_epoch = X_train.shape[0] // batch_size,\n                                           callbacks = [learning_rate_reduction])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Evaluating the model...\n","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"fig,ax = plt.subplots(2,1)\nax[0].plot(history.history['loss'], label = \"Training loss\", color =\"b\")\nax[0].plot(history.history['val_loss'], label = \" Validation loss\", color =\"yellow\", axes = ax[0])\nlegend = ax[0].legend(loc = 'best', shadow =True)\n\nax[1].plot(history.history['accuracy'], label = \"Training accuracy\", color = 'b')\nax[1].plot(history.history['val_accuracy'], label = \"Validation accuracy\", color = 'yellow')\nlegend = ax[1].legend(loc = 'best', shadow =True)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#  Confusion Matrix...","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\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = 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":{"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}