{"cells":[{"metadata":{"_uuid":"b918e7229b00eb8ab2e985969bf4a81fb5a76e6c"},"cell_type":"markdown","source":"## Importing packages"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"#import python packages\nimport numpy as np\nimport pandas as pd \nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n%matplotlib inline\nimport os\nnp.random.seed(0)","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"# import sklearn packages\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\nimport itertools","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"51eefaff4fbd95a01969eb48c180ff9d42e89d04"},"cell_type":"code","source":"# import keras packages\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","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"715e17e63ae970264f5cd3c98d5f58aefe89f35b"},"cell_type":"markdown","source":"## Load and View Data:"},{"metadata":{"trusted":true,"_uuid":"1fc7efbc19b993740125529a014ddcc13f055b98"},"cell_type":"code","source":"train_data = pd.read_csv('../input/train.csv')\ntest_data = pd.read_csv('../input/test.csv')\n\nX = train_data.drop(labels = ['label'], axis= 1)\ny = train_data['label']\n\n# free space\ndel train_data\n\n# count digits\nsns.countplot(y)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"2c892d93cc20f7d042d7062d9b816d1cd929d66b"},"cell_type":"markdown","source":"## Preprocessing Data:"},{"metadata":{"trusted":true,"_uuid":"09f1d5d4021ac7e33b3517a8d5189ff22df010df"},"cell_type":"code","source":"# check missing values\nX.isnull().any().describe()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a634ed2cfbacf1ac752215d9cf2ba27fe93ca3f8"},"cell_type":"code","source":"# normalize the data\nX = X/255.0\ntest_data = test_data/255.0","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"5031e3c738cf2e2302fbc4274c02681824703685"},"cell_type":"code","source":"# Reshape the data as Keras work with numpy not with dataframes\nX = X.values.reshape(-1,28,28,1)\ntest_data = test_data.values.reshape(-1,28,28,1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"cf8f91c9b7e7cbd4ca1a3a97b1f25eccbb6f56f6"},"cell_type":"code","source":"# Encode the digits using One hot encoding method\ny = to_categorical(y, num_classes=10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"c2ca1c61e06c30569d5a72f4359c313eec7b5717"},"cell_type":"code","source":"# Split the train and val data\nrandom_seed =5\nX_train,X_val,y_train, y_val =train_test_split(X,y,random_state=random_seed, test_size=0.08)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"464b18888c98dbdf9d50a4286b42116129a32f38"},"cell_type":"code","source":"# View digit\nplt.imshow(X_train[4][:,:,0])","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"6fadb83e2e943b556a63e8ecf37b127968b60928"},"cell_type":"markdown","source":"## Keras CNN implementation:"},{"metadata":{"trusted":true,"_uuid":"f394c6fb3073ade379cda36ebfb218949727675d"},"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Conv2D(filters = 64, kernel_size = (5,5),padding = 'Same', \n                 activation ='relu', input_shape = (28,28,1)))\nmodel.add(Conv2D(filters = 64, kernel_size = (5,5),padding = 'Same', \n                 activation ='relu'))\nmodel.add(MaxPool2D(pool_size=(2,2)))\nmodel.add(Dropout(0.3))\n\n\nmodel.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same', \n                 activation ='relu'))\nmodel.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same', \n                 activation ='relu'))\nmodel.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))\nmodel.add(Dropout(0.3))\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":{"trusted":true,"_uuid":"59c4758ca812a85f9a7ddd26f0f6b4c59ce7d988"},"cell_type":"code","source":"# Define the optimizer\noptimizer = RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a4a03c0b1ca670542ad74187cbd9232b0463a7b2"},"cell_type":"code","source":"# Compile the model\nmodel.compile(optimizer = optimizer , loss = \"categorical_crossentropy\", metrics=[\"accuracy\"])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"841147624c30706a8b0ac32813a294939c29bbae"},"cell_type":"code","source":"# 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":{"trusted":true,"_uuid":"bf495a93c754b208d3174f0e1c423bab527f0a6a"},"cell_type":"code","source":"epochs = 35\nbatch_size = 64","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f20508508f390088d76cd74e88e16388827f1a41"},"cell_type":"code","source":"# Data Augmentation(creating extra training data to avoid overfitting)\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,  # 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        )  \ndatagen.fit(X_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"e020437aac5fd30ccd98e161d85086dd5b1e5aa6"},"cell_type":"code","source":"# Fit the model\nhistory = model.fit_generator(datagen.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=[learning_rate_reduction])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"091de2610843abc32a232a12e2697167d19a598f"},"cell_type":"code","source":"# predict results\nresults = model.predict(test_data)\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":"73b98fc242d870aae22e0f221e548a0c477c32da"},"cell_type":"code","source":"submission = pd.concat([pd.Series(range(1,28001),name = \"ImageId\"),results],axis = 1)\nsubmission.to_csv(\"digit_cnn_keras.csv\",index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"52778d064bf8670ded3d77bdd3dc2c1aaba8b57d"},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"bcaf3bfd701ef61c72b83d01cb05da15609427e2"},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"1911e7c6ea067be2e62f60c3dbbf84cb8614acba"},"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}