{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Digit Identification"},{"metadata":{},"cell_type":"markdown","source":"## 1. Importing Libaries"},{"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\nimport csv\n\nfrom sklearn.model_selection import train_test_split\n\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\nimport tensorflow as tf\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":{},"cell_type":"markdown","source":"## 2. Getting Data"},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"#this lines are to import all the data needed\nfile=open('/kaggle/input/digit-recognizer/train.csv')\ndata=pd.read_csv(file)\ndata2=pd.read_csv('/kaggle/input/digit-recognizer/test.csv')\n#data.head()\n#data2.head()\nx_train=np.array(data.iloc[:,1:].astype('float32')) \ny_train=np.array(data.iloc[:,0:1].astype('float32'))    \nx_test=np.array(data2.iloc[:,:].astype('float32'))      \nprint(x_train.shape,y_train.shape,x_test.shape)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 3. Preparing the Data"},{"metadata":{"trusted":true},"cell_type":"code","source":"#all about getting the data ready\n\n#turning y values into one hot matrix\ny_train=to_categorical(y_train)\n\n#normalizing x data values\nx_train=x_train/255\nx_test=x_test/255\n\n#reshaping the images\nx_train=x_train.reshape(x_train.shape[0],28,28,1)\nx_test=x_test.reshape(x_test.shape[0],28,28,1)\n\n#dividing into train and validation sets\nseed=3\nx_train,x_val,y_train,y_val=train_test_split(x_train,y_train,test_size=0.2,random_state=seed)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 4. CNN"},{"metadata":{"trusted":true},"cell_type":"code","source":"#now we set up our model\nmodel=Sequential()\n\n#adding 2 convolution layer of filter 32 followed by a pooloing layer and dropouts\nmodel.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', \n                 activation ='relu', input_shape = (28,28,1)))\nmodel.add(MaxPool2D(pool_size=(2,2)))\n\n#adding the above layers only this time with 64 filters\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.25))\n\n\nmodel.add(Flatten())\n\n#creating a Dense layer with 256 units\nmodel.add(Dense(256, activation = \"relu\"))\n\n#another Dense layer with 10 unit i.e, 10 digits as output\nmodel.add(Dense(10, activation = \"softmax\"))\n\n#display the model summary\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 5. Compile and Run"},{"metadata":{"trusted":true},"cell_type":"code","source":"#compiling our model\nmodel.compile(optimizer='adam',loss='categorical_crossentropy',metrics=[\"accuracy\"])\n\n#fitting the data\nrecords=model.fit(x_train,y_train,epochs=10,batch_size=64,validation_data=(x_val,y_val))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 6. Visualisation"},{"metadata":{"trusted":true},"cell_type":"code","source":"#here we will analyze our model with plots and results\naccu_ratings=records.history['accuracy']\nplt.plot(range(len(accu_ratings)),accu_ratings)\nplt.show()\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 7. Predictions "},{"metadata":{"trusted":true},"cell_type":"code","source":"#finding the predictions for x_test\npred=model.predict(x_test)\n\n#combining the one_hot matrix to numbers\npred=np.argmax(pred,axis=1)\nprint(pred)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 8. Results in File"},{"metadata":{"trusted":true},"cell_type":"code","source":"pred = pd.Series(pred,name=\"Label\")\nsubmission = pd.concat([pd.Series(range(1,28001),name = \"ImageId\"),pred],axis = 1)\nsubmission.to_csv(\"results.csv\",index=False)","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}