{"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 in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"../input\"))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\n\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, Lambda, MaxPooling2D # convolution layers\nfrom keras.layers import Dense, Dropout, Flatten # core layers\n\nfrom keras.layers.normalization import BatchNormalization\n\nfrom keras.preprocessing.image import ImageDataGenerator\n\nfrom keras.utils.np_utils import to_categorical","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#load data\ntrain = pd.read_csv('../input/train.csv')\ntest = pd.read_csv('../input/test.csv')\nsubmission = pd.read_csv('../input/sample_submission.csv')\n#print size of training data and testing data\nprint(f\"Size of training data => {train.shape}\\nSize of Testing data => {test.shape}\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#split labels and image data\nX = train.drop(['label'], 1).values\ny = train['label'].values\n\ntest_x = test.values","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#convert our images to grayscale\nX = X / 255.0\ntest_x = test_x / 255.0","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Reshape image in 3 dimensions (height = 28px, width = 28px , canal = 1)\n# canal = 1 => For gray scale\nX = X.reshape(-1,28,28,1)\ntest_x = test_x.reshape(-1,28,28,1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Encode labels to one hot vectors (ex : 2 -> [0,0,1,0,0,0,0,0,0,0])\ny = to_categorical(y)\n\nprint(f\"Label size {y.shape}\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Split the train and the validation set for the fitting (90% train, 10% test)\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=0)\n#print new sizes\nX_train.shape, X_test.shape, y_train.shape, y_test.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"epochs = 50\nbatch_size = 64","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Defining model of our CNN\nmodel=Sequential()\n\nmodel.add(Conv2D(filters=64, kernel_size = (3,3), activation=\"relu\", input_shape=(28,28,1)))\nmodel.add(Conv2D(filters=64, kernel_size = (3,3), activation=\"relu\"))\n\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(filters=128, kernel_size = (3,3), activation=\"relu\"))\nmodel.add(Conv2D(filters=128, kernel_size = (3,3), activation=\"relu\"))\n\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(BatchNormalization())    \nmodel.add(Conv2D(filters=256, kernel_size = (3,3), activation=\"relu\"))\n    \nmodel.add(MaxPooling2D(pool_size=(2,2)))\n    \nmodel.add(Flatten())\nmodel.add(BatchNormalization())\nmodel.add(Dense(512,activation=\"relu\"))\n    \nmodel.add(Dense(10,activation=\"softmax\"))\n    \nmodel.compile(loss=\"categorical_crossentropy\", optimizer=\"adam\", metrics=[\"accuracy\"])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#In order to avoid overfitting problem, we need to expand artificially our handwritten digit dataset\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        horizontal_flip=False,  # randomly flip images\n        vertical_flip=False)  # randomly flip images\n\ntrain_gen = datagen.flow(X_train, y_train, batch_size=batch_size)\ntest_gen = datagen.flow(X_test, y_test, batch_size=batch_size)\n#Randomly rotate some training images by 10 degrees\n#Randomly Zoom by 10% some training images\n#Randomly shift images horizontally by 10% of the width\n#Randomly shift images vertically by 10% of the height\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Fit the model\nhistory = model.fit_generator(train_gen, \n                              epochs = epochs, \n                              steps_per_epoch = X_train.shape[0] // batch_size,\n                              validation_data = test_gen,\n                              validation_steps = X_test.shape[0] // batch_size)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n\nfig = plt.figure(figsize=(10, 10)) # Set Figure\n\ny_pred = model.predict(X_test) # Predict encoded label as 2 => [0, 0, 1, 0, 0, 0, 0, 0, 0, 0]\n\nY_pred = np.argmax(y_pred, 1) # Decode Predicted labels\nY_test = np.argmax(y_test, 1) # Decode labels\n\nmat = confusion_matrix(Y_test, Y_pred) # Confusion matrix\n\n# Plot Confusion matrix\nsns.heatmap(mat.T, square=True, annot=True, cbar=False, cmap=plt.cm.Blues)\nplt.xlabel('Predicted Values')\nplt.ylabel('True Values');\nplt.show();\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Submition & Prediciting the Outputs\npred = model.predict_classes(test_x, verbose=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission['Label'] = pred\nsubmission.to_csv(\"CNN_keras_sub.csv\", index=False)\nsubmission.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"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.4","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}