{"cells":[{"metadata":{"_uuid":"b3cc8a2c7c3f098b9b13bf284ab9441d0533d8bb"},"cell_type":"markdown","source":"\n\n* **1. Data preparation**\n    * 1.1 Load data\n    * 1.2 Check for null and missing values\n    * 1.3 Normalization\n    * 1.4 Reshape\n    * 1.5 Label encoding\n    * 1.6 Split training and valdiation set\n* **2. CNN**\n    * 2.1 Define the model\n    * 2.2 Set the optimizer and annealer\n    * 2.3 Data augmentation\n* **3. Evaluate the model**\n    * 3.1 Fitting the CNN to the Image"},{"metadata":{"_uuid":"0e0036570fabcf805c3f21669a95e4c2c85c2944"},"cell_type":"markdown","source":"# ***Intro***\n# 1.1 Load Data"},{"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 seaborn as sns\nimport warnings\nwarnings.filterwarnings('ignore')","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')\n\nX = train.drop('label', axis=1)\ny = train['label']","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"8576c4859fce9664aef1de64d044d3c09c30815e"},"cell_type":"markdown","source":"# 1.2 Check for null and missing values"},{"metadata":{"trusted":true,"_uuid":"5ebc54423463062c949025a822430064e169b842"},"cell_type":"code","source":"train.isnull().sum().any()\ntest.isnull().sum().any()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"7536636844995c1414102acd31ef4bb919a9bda2"},"cell_type":"code","source":"sns.countplot(x = y)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"0c00a9a796f599f3f740a1751c3f79ee392419ea"},"cell_type":"markdown","source":"# 1.4 Normalization"},{"metadata":{"trusted":true,"_uuid":"b1a903cf328be5c2129b07cbde180e4b6a4392c9"},"cell_type":"code","source":"X = X / 255.0\ntest = test / 255.0","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"12e0ef23fcc7ba3b7c4755ba0a3115a1f4fdae39"},"cell_type":"markdown","source":" # 1.3 Reshape"},{"metadata":{"trusted":true,"_uuid":"28b0e926ffd3d9f224d1b330846e4238e9277851"},"cell_type":"code","source":"X.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"3092a3f024130411fad1a9d71e770d9bee765cfb"},"cell_type":"code","source":"X = X.values.reshape(-1,28,28,1)\ntest = test.values.reshape(-1,28,28,1)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"432edfac9c963e3bd00a99d85fffe66747cd27a5"},"cell_type":"markdown","source":"The train and test dataframe has correspond to 1D which we try to reshape all photos to height = 28px , width = 28px, channel=3 (RGB)."},{"metadata":{"_uuid":"c674385c166351ec712d835b6dc06000ab7ee68f"},"cell_type":"markdown","source":"# 1.4 Label encoding"},{"metadata":{"trusted":true,"_uuid":"0b1188474d70cf7beb3278bda4c4fe6bac85e96a"},"cell_type":"code","source":"from keras.utils.np_utils import to_categorical","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"76b57a90069542d31c608535cbe841dd07b96148"},"cell_type":"code","source":"y = to_categorical(y, num_classes = 10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"b00e7132da4db42a4c8f8d37d2bfb8ff6c1d3299"},"cell_type":"markdown","source":"# 1.5 Split training and valdiation set"},{"metadata":{"trusted":true,"_uuid":"ac2330791eef949181d5b84e2aa3d5daed9c3e39"},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"2933267817d897e0f4baf742fb05080eb61e8722"},"cell_type":"markdown","source":"# **2. CNN**\n# 2.1 Define the model"},{"metadata":{"trusted":true,"_uuid":"c4dcf204ac8cbd3402df1c4db6d4ab68cbdaf45e"},"cell_type":"code","source":"from keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import ReduceLROnPlateau","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"985c9b7e060d04b14b276433852ed4b54de73756"},"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Conv2D(32, (5, 5), padding = 'Same', activation ='relu', input_shape = (28,28,1)))\nmodel.add(Conv2D(32, (5,5), padding = 'Same', activation ='relu'))\nmodel.add(MaxPool2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(64, (3,3), padding = 'Same', activation ='relu'))\nmodel.add(Conv2D(64, (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.5))\nmodel.add(Dense(10, activation = \"softmax\"))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"94c2bcdb7984b78100b8321bff6bddc1db2454e6"},"cell_type":"code","source":"model.compile(optimizer = 'adam' , loss = \"categorical_crossentropy\", metrics=[\"accuracy\"])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a62898ea90cf8d6dde0b127120cdae066dc4deb7"},"cell_type":"code","source":"learning_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":{"_uuid":"d9de8e54f7a3ad4a9394cc507703735e47567f06"},"cell_type":"markdown","source":"# ***3. Evaluate the model***\n## 3.1 Fitting the CNN to the Image"},{"metadata":{"trusted":true,"_uuid":"f007795811a631cc369615751f659b3eda6916fb"},"cell_type":"code","source":"datagen = 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,  # apply ZCA whitening\n        rotation_range=10,  # randomly rotate images in the range (degrees, 0 to 180)\n        zoom_range = 0.1, # Randomly zoom image \n        width_shift_range=0.1,  # randomly shift images horizontally (fraction of total width)\n        height_shift_range=0.1,  # randomly shift images vertically (fraction of total height)\n        horizontal_flip=False,  # randomly flip images\n        vertical_flip=False)  # randomly flip images\n\n\ndatagen.fit(X_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"8aaa0fd0aeba61df838eb737f6eba5c854804897","scrolled":true},"cell_type":"code","source":"# Fit the model\nhistory = model.fit_generator(datagen.flow(X_train,y_train, batch_size=86),\n                              epochs = 20, validation_data = (X_test, y_test),\n                              verbose = 2, steps_per_epoch=X_train.shape[0] // 86\n                              , callbacks=[learning_rate_reduction])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"75efc0be44bd11fd6fc9194c21dfe6fc51430535"},"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":"d07445d2058c453ff2671d0262f1cc02ae434bc3"},"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,"_uuid":"53553b342893857555ea0cc45784e99a81008135"},"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}