{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline\n\n#making random numbers predictable\nnp.random.seed(2)\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\n\nfrom keras.models import Sequential, load_model\nfrom keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D\nfrom keras.optimizers import Adam, RMSprop\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import ReduceLROnPlateau\n\n#one-hot encoding of y\nfrom keras.utils.np_utils import to_categorical\n\n#make it pretty\nsns.set(context = 'notebook', palette='cubehelix', style = 'dark')","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"#get data\n\ntrain = pd.read_csv(\"../input/digit-recognizer/train.csv\")\ntest = pd.read_csv(\"../input/digit-recognizer/train.csv\")\n\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Exploring the Data","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"Y_train = train['label']\nX_train = train.drop(labels= ['label'], axis = 1)\n#Check if dropped\nX_train.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Y_test = test['label']\nX_test = test.drop(labels= ['label'], axis = 1)\n#Test test\nX_test.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#See our training label distribution\nplt.figure(figsize = (8,4))\nsns.countplot(Y_train)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Y_train.value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#check missing values\nX_train.isnull().any().describe()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_test.isnull().any().describe()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"No missing values, yay","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"# Preprocessing","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"## Normalise","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"#To reduce effect of illumination, we normalise to greyscale\nX_train = X_train / 255 \nX_test = X_test/255\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Reshape data","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"img_width = 28\nimg_height = 28\nchannels = 1","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#-1 in the shape makes it compatible with the original shape. \n#We want the new data to have shape (width, height, channels)\n\nX_train = X_train.values.reshape(-1,28,28,1)\nX_test = X_test.values.reshape(-1,28,28,1)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## One Hot Encoding ","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"#endoding y as a one hot vector of 10\n\nY_train = to_categorical(Y_train, num_classes = 10)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Split into Train and Validation","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"#using a 90-10 ratio\nX_train, X_val, Y_train, Y_val = train_test_split(X_train, Y_train, test_size = 0.10, shuffle = True)\n\n#alt: use random seed instead of shuffle\n#random_seed = 2\n#X_train, X_val, Y_train, Y_val = train_test_split(X_train, Y_train, test_size = 0.1, random_state=random_seed)\n\nprint(X_train.shape, Y_train.shape, X_val.shape, Y_val.shape)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Model Construction","execution_count":null},{"metadata":{},"cell_type":"markdown","source":" CNN Model: *Conv2D-ReLU -> Conv2D-ReLU -> MaxPool2D -> Dropout -> Conv2D-ReLU -> Conv2D-ReLU -> MaxPool2D -> Dropout -> Flatten -> Dense -> Dropout ","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"## Build","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"#Build\n\nmodel = Sequential()\n\nmodel.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', activation ='relu', input_shape = (img_width,img_height,channels)))\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\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\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":{},"cell_type":"markdown","source":"## RMSProp Optimizer","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"#Optimiser\n\n#using categorical crossentropy for categorical loss\n#using RMSProp with default values\n#Gradient Stochastic Descent is slower\n\noptimizer = RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Compile","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"#Compile\nmodel.compile(optimizer = optimizer , loss = \"categorical_crossentropy\", metrics=[\"accuracy\"])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"IMPORTANT change epoch sizes while demos, it takes a while to run. Use GPU, CPU has a hilariously long run time","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"epochs = 30\nbatch_size = 64\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#train to see accuracy\n\nhistory = model.fit(X_train, Y_train, batch_size = batch_size, epochs = epochs, validation_data = (X_val, Y_val), \n                    verbose = 2)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":" Accuracy: 98.83","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"## Annealer","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"#Annealer\n#Reduce learning by half if accuracy not improved in 3 epochs\n#We use an annealer to decrease the learning rate so it converges to global minima and not local minima\n#verbose=1 to give update messages\n#min_lr: lower bound on learning rate\n\nannealer = ReduceLROnPlateau(monitor='val_accuracy', patience=3, verbose=1, factor=0.5, min_lr=0.00001)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#using annealer\nhistory = model.fit(X_train, Y_train, batch_size = batch_size, epochs = epochs, validation_data = (X_val, Y_val), \n                    verbose = 2, callbacks= [annealer])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Accuracy: 99.61","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"Annealer incresed the accuracy, try data augmentation to prevent overfitting","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"## Augmentation","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"#Augmenting the data by rondomly rotating images by 10 degrees\n\nimggen = ImageDataGenerator(\n        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) \n\nimggen.fit(X_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#fit model to check accuracy with the augmented\n\nhistory = model.fit_generator(imggen.flow(X_train,Y_train, batch_size=batch_size),\n                              epochs = epochs, validation_data = (X_val,Y_val),\n                              verbose = 2, steps_per_epoch=X_train.shape[0] // batch_size,\n                              callbacks=[annealer])\n\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Accuracy: 95.55","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"# Model Evaluation","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"## Accuracy","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"#Accuracy\n\nplt.plot(history.history['accuracy'], color='navy', label=\"Training Accuracy\")\nplt.plot(history.history['val_accuracy'], color='purple', label=\"Validation Accuracy\")\nplt.title('Model Accuracy')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(loc='best')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Loss","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"#Loss\n\nplt.plot(history.history['loss'], color='navy', label=\"Training Loss\")\nplt.plot(history.history['val_loss'], color='purple', label=\"Validation Loss\")\nplt.title('Model Loss')\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.legend(loc='best')\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\n\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) \ncm = confusion_matrix(Y_true, Y_pred_classes)\n\nprint(cm)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Predicting Results","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"results = model.predict(X_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":{},"cell_type":"markdown","source":"# Submission","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = pd.concat([pd.Series(range(1,28001),name = \"ImageId\"),results],axis = 1)\n\nsubmission.to_csv(\"DRSubmission.csv\",index=False)\n","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}