{"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)\nimport matplotlib as ml\nimport matplotlib.pyplot as plt\n%matplotlib inline\nml.style.use('ggplot')\n\nfrom sklearn.model_selection import train_test_split\nfrom keras.utils.np_utils import to_categorical\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.optimizers import Adam\nfrom keras.utils.np_utils import to_categorical\nfrom keras.layers import Dropout, Flatten ,BatchNormalization , MaxPool2D\nfrom keras.layers.convolutional import Conv2D\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":"train = pd.read_csv('/kaggle/input/digit-recognizer/train.csv')\ntest = pd.read_csv('/kaggle/input/digit-recognizer/test.csv')\ntrain.head(10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X = train.drop(['label'],axis=1)\ny = train['label']","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Normalizing and Reshaping the data\n### I am using Grayscale normalization as the model will work faster for the interval of data between [0,1], instead of [0,255]","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"X = X / 255.0\ntest = test / 255.0\n\n# Reshaping to 28 x 28 x 1, where 1 represents the color channel\nX = X.values.reshape(-1,28,28,1)\ntest = test.values.reshape(-1,28,28,1)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Visualizing to check if the labels are correct","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"fig,axes = plt.subplots(1,20,figsize=(30,10))\nfig.tight_layout()\n\nfor i in range(20):\n    axes[i].imshow(X[i].reshape(28,28))          # 28 x 28 matrix\n    axes[i].axis('off')\n    axes[i].set_title(y[i])           # Setting the title of all images to the label to see if they match\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Split to train test batches","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 5)\nprint(\"X : \", X_train.shape, X_test.shape)\nprint(\"y : \", y_train.shape, y_test.shape)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Performing Data augmentation with ImageDataGenerator\n### Performing in-place augmentation by random translations","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"aug = ImageDataGenerator(width_shift_range=0.1,   \n                            height_shift_range=0.1,\n                            zoom_range=0.2,  \n                            shear_range=0.1, \n                            rotation_range=10)  \naug.fit(X_train)\nitr = aug.flow(X_train,y_train,batch_size=20)       # Creating an iterator from the dataset. Returns one batch of augmented images for each iteration.\nX_batch,y_batch = next(itr)\n\n# Visualizing to check\nfig,axes = plt.subplots(1,10,figsize=(30,10))\nfig.tight_layout()\n\nfor i in range(10):\n    axes[i].imshow(X_batch[i].reshape(28,28))          # 28 x 28 matrix\n    axes[i].axis('off')\n    axes[i].set_title(y_batch[i])           # Setting the title of all images to the label to see if they match\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Building the model : Convolutional Neural Network (CNN)\n### Step 1 : Label encoding","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"y_train = to_categorical(y_train,10)\ny_test = to_categorical(y_test,10)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Step 2 : Building the net","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"cnn = Sequential()\n\n# First\ncnn.add(Conv2D(filters = 64, kernel_size = (3,3) ,activation ='relu', input_shape = (28,28,1)))\ncnn.add(Conv2D(filters = 56, kernel_size = (3,3),activation ='relu'))\ncnn.add(BatchNormalization())\ncnn.add(MaxPool2D(pool_size=(2,2)))\ncnn.add(Dropout(0.2))\n\n# Second\ncnn.add(Conv2D(filters = 64, kernel_size = (3,3),activation ='relu'))\ncnn.add(Conv2D(filters = 48, kernel_size = (3,3),activation ='relu'))\ncnn.add(Conv2D(filters = 32, kernel_size = (3,3),activation ='relu'))\ncnn.add(BatchNormalization())\ncnn.add(MaxPool2D(pool_size=(2,2)))\ncnn.add(Dropout(0.2))\n\n# Third\ncnn.add(Flatten())\ncnn.add(Dense(256, activation = \"relu\"))           # (64 x 7 x 7) x 256\ncnn.add(Dense(128, activation = \"relu\"))           # 256 x 128\ncnn.add(Dense(64, activation = \"relu\"))           # 128 x 64\ncnn.add(Dropout(0.4))\n\n#Output\ncnn.add(Dense(10, activation = \"softmax\"))           # 64 x 10\ncnn.compile(Adam(lr=0.001),loss='categorical_crossentropy',metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Step 3 : Print model summary","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"print(cnn.summary())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"status = cnn.fit_generator(aug.flow(X_train,y_train, batch_size=56),\n                              epochs = 10, validation_data = (X_test,y_test),\n                              verbose = 2, steps_per_epoch=660)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Step 4 : Evaluating the model","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure()\nfig,(ax1, ax2)=plt.subplots(1,2,figsize=(15,5))\nax1.plot(status.history['loss'])\nax1.plot(status.history['val_loss'])\nax1.legend(['Training','Validation'])\nax1.set_title('Loss')\nax1.set_xlabel('Epoch')\n\nax2.plot(status.history['accuracy'])\nax2.plot(status.history['val_accuracy'])\nax2.legend(['Training','Validation'])\nax2.set_title('Acurracy')\nax2.set_xlabel('Epoch')\n\nplt.show()\n\nscore = cnn.evaluate(X_test,y_test,verbose = 1)\nprint('Test Score: ',score[0])\nprint('Test Accuracy: ',score[1])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Step 5 : Final prediction and creating the submission file","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"res = cnn.predict(test)\nres = np.argmax(res,axis = 1)\nres = pd.Series(res,name=\"Label\")\nfinal = pd.concat([pd.Series(range(1,28001),name = \"ImageId\"),res],axis = 1)\nfinal.to_csv(\"Balaka_Digit_Recognition2.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}