{"cells":[{"metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","collapsed":true,"trusted":false},"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%matplotlib inline\n\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D,MaxPooling2D,Dense,Dropout,Flatten\nfrom keras.optimizers import Adam\nfrom sklearn.model_selection import train_test_split\nfrom keras.utils.np_utils import to_categorical\nfrom keras.preprocessing.image import ImageDataGenerator\nimport plotly.offline as py\nimport plotly.figure_factory as ff\npy.init_notebook_mode(connected=True)\nimport plotly.graph_objs as go\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.\nfrom subprocess import check_output\nprint(check_output(['ls','../input']))","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","collapsed":true,"trusted":false},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"0665356b-8121-4e32-beaf-49c8bb4c5890","_uuid":"3af7db00d3b0d4ff9e7e3a43b15aa301e8c02b0a","collapsed":true,"trusted":false},"cell_type":"code","source":"train=pd.read_csv('../input/train.csv')\ntest=pd.read_csv('../input/test.csv')","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"cad5a088-7a0d-470e-acb9-e0617c5d05f8","_kg_hide-input":true,"_uuid":"e268f8d8fddf1ff84476f002cdb189cf1c047371","collapsed":true,"trusted":false},"cell_type":"code","source":"print(train.shape)\ntrain.head(5)","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"33e120ce-e84b-482e-a7d6-d81c5c529d40","_uuid":"f7956a8af183f43392b1a77c94827ae7b7edfe61","collapsed":true,"trusted":false},"cell_type":"code","source":"print(test.shape)\ntest.head(5)","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"18eabf5d-f646-4f91-af3c-1288a9f506aa","_uuid":"bb394c0dd74fafafdf8f3c911fbb5218bcf207c5"},"cell_type":"markdown","source":"## Divide the training data and Label."},{"metadata":{"_cell_guid":"12851ed7-7128-4e93-9884-6d7dd1a682f2","_kg_hide-input":true,"_uuid":"4d37be8da7176ba95ae03db1392217ad873feba0","collapsed":true,"trusted":false},"cell_type":"code","source":"X_train = (train.iloc[:,1:].values).astype('float32')\ny_train = train.iloc[:,0].values.astype('int32')\nX_test = test.values.astype('float32')","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"d3814389-f518-47fa-a841-59b4d16e368a","_uuid":"1cfcc011632f95424ac7c92dc62ffc856ce506b6","collapsed":true,"trusted":false},"cell_type":"code","source":"X_train.shape","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"8a91ca3f-0b40-4a8a-8090-78153f0d9c1e","_uuid":"cbd0d358cfe724a385a905b8bf1e0345834afd8f"},"cell_type":"markdown","source":"Quick Look at an Image"},{"metadata":{"_cell_guid":"3330eb2d-2d80-4067-bae5-96f12b2fd3b2","_kg_hide-input":true,"_uuid":"3d966ef2b7515bc7854c1e5113ea038f434501d9","collapsed":true,"trusted":false},"cell_type":"code","source":"X_train=X_train.reshape(X_train.shape[0],28,28)\nplt.imshow(X_train[7],cmap=plt.get_cmap('Greys'))\nplt.title(y_train[7])","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"78e157f7-ef8b-4eab-b79e-35cd3dd3b2e1","_uuid":"8eb81c7167fd90a66ef084b140bfc97a270469a5"},"cell_type":"markdown","source":"We need to do this step to standarized the data to get the data value around 0 and 1"},{"metadata":{"_cell_guid":"871a25c7-5fc9-425c-999d-9ad8d28b4411","_kg_hide-input":true,"_uuid":"b79fa476e6a0781282c8d88299d6057ab97731b2","collapsed":true,"trusted":false},"cell_type":"code","source":"train_images=X_train.reshape((X_train.shape[0],28,28,1))\ntrain_images=train_images.astype('float')/255\n\ntest_images=X_test.reshape((test.shape[0],28,28,1))\ntest_images=test_images.astype('float')/255","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"c5747763-0333-4e99-9d05-954cdb6008a2","_kg_hide-input":true,"_uuid":"e9a54300d5ec5e02eff35a7cf31fae55f55bacb6"},"cell_type":"markdown","source":"### One-Hot Encoding Of Label"},{"metadata":{"_cell_guid":"27450eaf-75dd-4590-9c89-f8bd203dacbb","_uuid":"8270ee05a0c4123b152ad14cff003eaf2f1ef316","collapsed":true,"trusted":false},"cell_type":"code","source":"y_train=to_categorical(y_train)","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"2b2cf0ca-fd4b-4bd8-93a9-4919343e4912","_uuid":"129b906305defeab8f13fcb622abe883aec64aa3","collapsed":true,"trusted":false},"cell_type":"code","source":"y_train.shape","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"bac526b6-5a48-4aac-b7b0-65785aed5d0d","_uuid":"35d748a21c1b55444f3195da8ccc44cba3722338"},"cell_type":"markdown","source":"## Split Training and Validation Set"},{"metadata":{"_cell_guid":"889e8f74-2324-4c86-9cb3-29508daba0a5","_uuid":"e530d1e27a556ca76af1350a9d5fea9010d97f69","collapsed":true,"trusted":false},"cell_type":"code","source":"x_train,x_val,y_train,y_val=train_test_split(train_images,y_train,test_size=0.2,random_state=23)","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"a24cef84-5981-4155-8ea3-30d8567ed1d2","_uuid":"38fd7b9189cc2e1dc2c5cf462a15ece3d078d344"},"cell_type":"markdown","source":"## Define The Model"},{"metadata":{"_cell_guid":"2ad4743a-fed5-4840-ac0c-86dcac5df8b6","_uuid":"9a164e312d9858dd94338ce0edefc57978be16bd","collapsed":true,"trusted":false},"cell_type":"code","source":"model=Sequential()\nmodel.add(Conv2D(32,(5,5),activation='relu',padding='same',input_shape=(28,28,1)))\nmodel.add(Conv2D(32,(5,5),activation='relu',padding='same'))\nmodel.add(MaxPooling2D(2,2))\nmodel.add(Dropout(0.3))\n\nmodel.add(Conv2D(64,(3,3),activation='relu',padding='same'))\nmodel.add(Conv2D(64,(3,3),activation='relu',padding='same'))\nmodel.add(MaxPooling2D(2,2))\nmodel.add(Dropout(0.3))\nmodel.add(Conv2D(64,(3,3),activation='relu',padding='same'))\nmodel.add(Conv2D(64,(3,3),activation='relu',padding='same'))\nmodel.add(MaxPooling2D(2,2))\nmodel.add(Dropout(0.3))\nmodel.add(Flatten())\nmodel.add(Dense(512,activation='relu'))\nmodel.add(Dropout(0.3))\nmodel.add(Dense(10,activation='softmax'))","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"bfc2d147-feb0-4ab1-9dbe-e235383e3289","_uuid":"8721d141531c3b5ecfadb8c01f4d63270e4320d0","collapsed":true,"trusted":false},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"3f1bc882-1d41-40f2-a2fa-adf404304735","_uuid":"d1bc1dcd3bb3111502c07e91cb209b7968a6c7f1"},"cell_type":"markdown","source":"## Set the optimizer and Compile It"},{"metadata":{"_cell_guid":"00426df1-f007-4846-a770-4c8634537b5f","_uuid":"6f8e178e134c06740891134e45871f7dee5bc2de","collapsed":true,"trusted":false},"cell_type":"code","source":"model.compile(loss='binary_crossentropy',\n              optimizer=Adam(1e-4),\n              metrics=['acc'])\n","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"edaa9a9b-2c30-4259-af05-49db9b1ff0bd","_uuid":"55e3b31b3d90075419cc295e9c0f60c740f29cf3"},"cell_type":"markdown","source":"## Augment The Data via ImageDataGenerator"},{"metadata":{"_cell_guid":"fd4d0065-23e5-4fc7-84a4-c45646718ebe","_kg_hide-input":true,"_uuid":"b8fc58c9bbcb935f34b5c37d4a32900cd0675c72","collapsed":true,"trusted":false},"cell_type":"code","source":"datagen=ImageDataGenerator(\nrotation_range=10,\n    width_shift_range=0.2,\n    height_shift_range=0.2,\n    shear_range=0.2,\n    zoom_range=0.1,\n  \n    horizontal_flip=False,\n    vertical_flip=False,\n    fill_mode='nearest')\n\ndatagen.fit(x_train)","execution_count":null,"outputs":[]},{"metadata":{"scrolled":true,"_kg_hide-output":true,"_cell_guid":"03ac1224-68e1-4de3-bd35-1dd1849e7af8","_uuid":"b43a8754d28a0aadf6e64ae434213614a75020fa","collapsed":true,"trusted":false},"cell_type":"code","source":"data_generator=datagen.flow(x_train,y_train,batch_size=128)\nhistory=model.fit_generator(data_generator,\n                           epochs=100,\n                           validation_data=(x_val,y_val))","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"aa62477f-bb1e-4861-bf33-fdbb85f93dea","_uuid":"01895cc0ea05278bc42ba469f4b56ef625b60a0c","collapsed":true,"trusted":false},"cell_type":"code","source":"acc=history.history['acc']\nval_acc=history.history['val_acc']\nloss=history.history['loss']\nval_loss=history.history['val_loss']\n\nepochs=range(1,len(acc)+1)\nip_range=[]\nfor i in range(1,len(acc)+1):\n    ip_range.append(i)\n\ntrace1=go.Scatter(\n               x=ip_range,\n               y=acc,\n            mode='lines+markers',\n            name='Train_Accuracy')\n\ntrace2=go.Scatter(\n               x=ip_range,\n               y=val_acc,\n            mode='lines+markers',\n            name='Validation Accuracy')\n\ndata=[trace1,trace2]\npy.iplot(data)","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"e034edd1-20d5-4f51-8be4-2020aa9c30a9","_uuid":"62051320d52035f175f176c22100594075019574","collapsed":true,"trusted":false},"cell_type":"code","source":"trace1=go.Scatter(\n               x=ip_range,\n               y=loss,\n            mode='lines+markers',\n            name='Train_Loss')\n\ntrace2=go.Scatter(\n               x=ip_range,\n               y=val_loss,\n            mode='lines+markers',\n            name='Validation Loss')\n\ndata=[trace1,trace2]\npy.iplot(data)","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"d2d28420-8acf-44aa-94cd-79137f7bf1ed","_uuid":"54009033eee2204b14a0d1fefd1d4fba16f7dce1","collapsed":true,"trusted":false},"cell_type":"code","source":"predictions = model.predict_classes(test_images, verbose=0)\n\nsubmissions=pd.DataFrame({\"ImageId\": list(range(1,len(predictions)+1)),\n                         \"Label\": predictions})\nsubmissions.to_csv(\"cnn.csv\", index=False, header=True)","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}