{"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\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport tensorflow as tf\nfrom tensorflow import keras\n# Input data files are available in the read-only \"../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# You can write up to 5GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nfrom keras.preprocessing.image import ImageDataGenerator","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')\ntrain.head()\nprint()\ntest=pd.read_csv('../input/digit-recognizer/test.csv')\ntest.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.models import Sequential\nfrom keras.layers import Conv2D\nfrom keras.layers import MaxPool2D\nfrom keras.layers import Flatten\nfrom keras.utils.np_utils import to_categorical\nfrom keras.layers import Dense,Dropout","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(train.shape)\nprint(test.shape)\ny_train=train['label']\n#y_train.unique()\ny_train=to_categorical(y_train,10)\nx_train=train.drop('label',axis=1)\nx_test=train.drop('label',axis=1)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#Noralization","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"x_train=x_train/255\nx_test=x_test/255","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Reshape\nx_train = x_train.values.reshape(-1,28,28,1)\nx_test = x_test.values.reshape(-1,28,28,1)\n#(-1,28,28,1)   nrows,height,width,channel(for  us its  gray scale)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#splitting data into train and validation\nX_train,X_val,y_train,y_val=train_test_split(x_train,y_train,test_size=0.25,random_state=22)\nprint(f'x_train {X_train.shape}')\nprint(f'x_val {X_val.shape}')\nprint(f'y_train {y_train.shape}')\nprint(f'y_val {y_val.shape}')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model=Sequential()\n#adding first conv layer\nmodel.add(Conv2D(32,(3,3),input_shape=(28,28,1),activation='relu'))\nmodel.add(MaxPool2D(pool_size = (2, 2)))\n\n#adding 2nd conv layer\nmodel.add(Conv2D(64, kernel_size=(5, 5), activation='relu'))\nmodel.add(MaxPool2D(pool_size=(2, 2)))\n\n\nmodel.add(Flatten())\nmodel.add(Dense(120,activation='relu'))\nmodel.add(Dense(84,activation='relu'))\nmodel.add(Dense(10,activation='softmax'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(optimizer = 'adam', loss = \"categorical_crossentropy\", metrics = ['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit(X_train, y_train, batch_size = 32, epochs = 1, validation_data = (X_val, y_val), verbose = 2)\nhistory","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred=model.predict_classes(x_test)\npred","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train.shape[0]//32","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Trying with data augumentation\n\ntrain_datagen = ImageDataGenerator(shear_range = 0.2,\n                                   zoom_range = 0.2,\n                                   horizontal_flip = True,\n                                   vertical_flip = True)\ntrain_datagen.fit(X_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit_generator(train_datagen.flow(X_train,y_train, batch_size=32),\n                              epochs = 50, validation_data = (X_val,y_val),\n                              verbose = 2, steps_per_epoch=X_train.shape[0] // 32)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"a=pd.DataFrame(model.history.history)\nimport  matplotlib.pyplot as plt\nplt.plot(a['loss'],label='loss')\nplt.plot(a['val_loss'],color='orange',label='val_loss')\nplt.legend()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.plot(a['accuracy'],label='accuracy')\nplt.plot(a['val_accuracy'],label='val_acc')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#we can see that the cal_loss and acc are fluctuating , it may be case of overfitting, we try adding drpout/batchnormalizatiom\nfrom tensorflow.keras.layers import BatchNormalization\n\n\nmodel=Sequential()\n#adding first conv layer\nmodel.add(Conv2D(32,(3,3),input_shape=(28,28,1),activation='relu'))\nmodel.add(Dropout(0.4))\nmodel.add(MaxPool2D(pool_size = (2, 2)))\n\n#adding 2nd conv layer\nmodel.add(Conv2D(16, kernel_size=(5, 5), activation='relu'))\nmodel.add(Dropout(0.4))\nmodel.add(MaxPool2D(pool_size=(2, 2)))\n\n\n\n\nmodel.add(Flatten())\nmodel.add(Dense(120,activation='relu'))\nmodel.add(Dense(84,activation='relu'))\nmodel.add(Dense(10,activation='softmax'))\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(optimizer='adam',loss='categorical_crossentropy',metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.callbacks import EarlyStopping\nearly_stop = EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=25)\nmodel.fit(X_train, y_train, batch_size = 64, epochs = 4, validation_data = (X_val, y_val), verbose = 1,callbacks=[early_stop])\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model_loss = pd.DataFrame(model.history.history)\nplt.plot(model_loss['loss'])\nplt.plot(model_loss['val_loss'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predictions = model.predict_classes(x_test, verbose=0)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission=pd.DataFrame({\"ImageId\": list(range(1,len(predictions)+1)),\n                         \"Label\": predictions})\n\nsubmission.to_csv(\"FirstCNN\", index=False, header=True)","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}