{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"scrolled":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,"scrolled":true},"cell_type":"code","source":"#print training set \ntrain = pd.read_csv(\"/kaggle/input/digit-recognizer/train.csv\")\ntrain.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"scrolled":true},"cell_type":"code","source":"#print test set\ntest=pd.read_csv(\"/kaggle/input/digit-recognizer/test.csv\")\ntest.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"scrolled":true},"cell_type":"code","source":"# Seperate out image data and label\ny_train = train[\"label\"]\nx_train = train.drop([\"label\"],axis=1)\ny_train.value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"scrolled":true},"cell_type":"code","source":"#Normalization for faster convergence\nx_train = x_train/255.0","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"scrolled":true},"cell_type":"code","source":"#Reshape datasets\nx_train = x_train.values.reshape(-1,28,28,1)\nx_test = test.values.reshape(-1,28,28,1)\nfrom keras.utils import to_categorical\ny_train = to_categorical(y_train,num_classes=10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"scrolled":true},"cell_type":"code","source":"#Split data to training and cross vaildation set\nfrom sklearn.model_selection import train_test_split\nX_train, X_cv, Y_train, Y_cv = train_test_split(x_train, y_train, test_size=0.2, random_state=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"scrolled":true},"cell_type":"code","source":"# Visualizing the training data\nplt.imshow(X_train[25][:,:,0])\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"scrolled":true},"cell_type":"code","source":"#CNN model\n#Using relu activation in the hidden layers for adding non-linearity to network\n#Using softmax activation at ouput layer to give output in terms of probability\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D\nfrom keras.layers import Dense\nfrom keras.layers import Flatten\nmodel = Sequential()\nmodel.add(Conv2D(filters=20,kernel_size=5,strides=(1,1),padding=\"valid\",activation='relu', input_shape=(28,28,1)))\nmodel.add(Conv2D(filters=20,kernel_size=5,strides=(1,1),padding=\"valid\",activation='relu'))\nmodel.add(Conv2D(filters=50,kernel_size=5,strides=(1,1),padding=\"valid\",activation='relu'))\nmodel.add(Conv2D(filters=50,kernel_size=5,strides=(1,1),padding=\"valid\",activation='relu'))\nmodel.add(Conv2D(filters=50,kernel_size=5,strides=(1,1),padding=\"valid\",activation='relu'))\nmodel.add(Conv2D(filters=50,kernel_size=5,strides=(1,1),padding=\"valid\",activation='relu'))\nmodel.add(Flatten())\nmodel.add(Dense(units=500,activation='relu'))\nmodel.add(Dense(units=10,activation='softmax'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"scrolled":true},"cell_type":"code","source":"# Specifying optimizer and cost fuction. RMSprop is faster version of \n# gradient descent\nfrom keras.optimizers import RMSprop\nopt = RMSprop(learning_rate=0.01, rho=0.9)\nmodel.compile(loss=\"categorical_crossentropy\",optimizer=opt)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"scrolled":true},"cell_type":"code","source":"# Using data augmentation for giving more generalization capability to network.\n#model.fit(X_train,Y_train,batch_size=32,epochs=2,validation_data=(X_cv, Y_cv))\nfrom keras.preprocessing.image import ImageDataGenerator\ndataAugmentation = ImageDataGenerator(rotation_range = 10,\n                                     width_shift_range = 0.1,\n                                     height_shift_range = 0.1,\n                                     zoom_range = 0.1,\n                                     horizontal_flip = False,\n                                     vertical_flip = False)\n#Fit the model to training data\nmodel.fit_generator(dataAugmentation.flow(X_train,Y_train,batch_size=32), epochs=2, validation_data=(X_cv, Y_cv))\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"scrolled":true},"cell_type":"code","source":"#Predict the output for test set\ny_test = model.predict(x_test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"scrolled":true},"cell_type":"code","source":"#Visualizing the predicted output for one sample\nplt.imshow(x_test[25000][:,:,0])\nplt.show()\nprint(y_test[25000])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Construct labels from the prediction output and put it in .csv file\nlabels = np.argmax(y_test, axis=1)\nimageIds = np.arange(1,28001)\noutput = pd.DataFrame({'ImageId':imageIds, 'Label':labels})\noutput.to_csv('output.csv', index=False)\nprint(output)\nprint(\"Your submission is successful.\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"scrolled":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}