{"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)\nimport matplotlib.pyplot as plt\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 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# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"train=pd.read_csv('../input/digit-recognizer/train.csv')\ntest=pd.read_csv('../input/digit-recognizer/test.csv')\nprint(train.head())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#null-check\nprint(train.isnull().any().describe())\nprint(train.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train = train.drop('label', axis=1)\ny_train = train.iloc[:, 0]\n\n# normalize the pixel intensity values.\nX_train = X_train / 255.0\ntest = test / 255.0\n\n# reshape to a matrix of m * 28 * 28 where 1 is for 1D.\nX_train = X_train.values.reshape(-1,28,28,1)\ntest = test.values.reshape(-1,28,28,1)\n\n# Encode labels to one hot vectors (ex : 2 -> [0,0,1,0,0,0,0,0,0,0])\nfrom keras.utils import np_utils \nY_train =  np_utils.to_categorical(y_train, num_classes = 10)\n\n# split set into training and validation. \nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X_train, Y_train, test_size=0.1, random_state=42)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Building the CNN\n\n# Importing the Keras libraries and packages\nfrom keras.models import Sequential\nfrom keras.layers import Convolution2D\nfrom keras.layers import MaxPooling2D\nfrom keras.layers import Flatten\nfrom keras.layers import Dense, Dropout\n# Initializing layers\nmodel = Sequential()\n# Adding a convolutional layer\nmodel.add(Convolution2D(filters = 32, kernel_size = (5,5),\n                 activation ='relu', input_shape = (28,28,1)))\nmodel.add(Convolution2D(filters = 32, kernel_size = (5,5), \n                 activation ='relu'))\n# Adding a pooling layer\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))\n\n# Adding a 2nd convolutional layer\nmodel.add(Convolution2D(filters = 64, kernel_size = (3,3),\n                 activation ='relu'))\nmodel.add(Convolution2D(filters = 64, kernel_size = (3,3), \n                 activation ='relu'))\nmodel.add(MaxPooling2D(pool_size=(2,2), strides=(2,2)))\nmodel.add(Dropout(0.25))\n#Dropout reduces overfitting\n\n# Flattening\nmodel.add(Flatten())\n\n# Making full connection\nmodel.add(Dense(256, activation = \"relu\"))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(10, activation = \"softmax\"))\n\n# Compiling the CNN\nmodel.compile(optimizer='rmsprop',\n              loss='categorical_crossentropy',\n              metrics=['accuracy'])\n\n# Image Augmentation, creating more images with ImageDataGenerator\nfrom keras.preprocessing.image import ImageDataGenerator\nimagegen = 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\nimagegen.fit(X_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# fit the model with generated images. \nfitobj = model.fit_generator(imagegen.flow(X_train,y_train, batch_size=86),\n                              epochs = 1, validation_data = (X_test,y_test),\n                              verbose = 1, steps_per_epoch=X_train.shape[0])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# predict results\nresults = model.predict(test)\n\n# change results in appropriate format for the submission\nresults = np.argmax(results,axis = 1)\nresults = pd.Series(results,name=\"Label\")\n\nsubmission = pd.concat([pd.Series(range(1,28001),name = \"ImageId\"),results],axis = 1)\nsubmission.to_csv(\"cnn_mnist_datagen.csv\",index=False)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<a href='cnn_mnist_datagen.csv'>Click here to download submission</a>"}],"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":1}