{"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)\n\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":{},"cell_type":"markdown","source":"# Import Libraries"},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import numpy as np \nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n#import seaborn as sns\n\nnp.random.seed(2)\nnum_classes=10\n\nfrom sklearn.model_selection import train_test_split \nfrom sklearn.metrics import confusion_matrix\nimport itertools\nimport keras\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,BatchNormalization\nfrom keras.optimizers import RMSprop\nfrom keras.preprocessing.image import ImageDataGenerator","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Data Reading"},{"metadata":{"trusted":true},"cell_type":"code","source":"train=pd.read_csv(\"../input/digit-recognizer/train.csv\")\ntest=pd.read_csv(\"../input/digit-recognizer/test.csv\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## ImageData Visullization"},{"metadata":{"trusted":true},"cell_type":"code","source":"train_images=[]\nfor i in range(0,len(train)):\n    x=np.array(train.iloc[i][1:].values)\n    x=x.reshape(28,28)\n    train_images.append(x)\ntrain_images = np.asarray(train_images) \n\n\ntest_images = []\nfor i in range(0,len(test)):\n    x = np.array(test.iloc[i].values)\n    x = x.reshape(28,28)\n    test_images.append(x)\ntest_images = np.asarray(test_images)\n\nplt.imshow(train_images[7],cmap='gray')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(train.shape)\nprint(test.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train = train.drop(labels=[\"label\"],axis=1)\nY_train = train['label']","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Data Processing"},{"metadata":{},"cell_type":"markdown","source":"## Normalisation"},{"metadata":{"trusted":true},"cell_type":"code","source":"# normalising the data values\nX_train = X_train / 255.0\ntest = test / 255.0\n#images converted to grayscale ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Reshape"},{"metadata":{"trusted":true},"cell_type":"code","source":"# reshape which will convert to a 28x28x1 array. height = width = 28. Gray scale so 1. RGB => 3\nX_train = X_train.values.reshape(-1,28,28,1)\ntest = test.values.reshape(-1,28,28,1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(X_train.shape)\nprint(test.shape)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## One Hot Encoading"},{"metadata":{"trusted":true},"cell_type":"code","source":"# onehot encoding for label \nY_train_cat = to_categorical(Y_train, num_classes = 10)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Data Modelling"},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential()\nmodel.add(Conv2D(64,(5,5),padding=\"valid\",strides=1,name=\"Conv1\",activation=\"relu\",input_shape=(28,28,1)))\n#practice model.add(Conv2D(8,(2,2),padding=\"valid\",strides=1,name=\"Conv2\"))\nmodel.add(MaxPool2D(pool_size=(2,2)))\nmodel.add(Conv2D(8,(5,5),padding=\"valid\",strides=1,name=\"Conv2\",activation=\"relu\"))\nmodel.add(BatchNormalization())\nmodel.add(Flatten())\nmodel.add(Dense(64,activation =\"relu\"))\nmodel.add(Dense(32,activation=\"relu\"))\nmodel.add(Dense(10,activation =\"softmax\"))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Model Compile"},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(loss = keras.losses.categorical_crossentropy,optimizer = RMSprop(),metrics =['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Model Fit"},{"metadata":{"trusted":true},"cell_type":"code","source":"History=model.fit(X_train,Y_train_cat,batch_size = 32,epochs =5,verbose= 1,validation_split = 0.2)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Model Evaluation"},{"metadata":{"trusted":true},"cell_type":"code","source":"model.evaluate(X_train,Y_train_cat)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Model Prediction"},{"metadata":{"trusted":true},"cell_type":"code","source":"predict=model.predict_classes(test)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Submission"},{"metadata":{"trusted":true},"cell_type":"code","source":"results = pd.Series(predict,name=\"Label\")\nsubmission = pd.concat([pd.Series(range(1,len(predict)+1),name = \"ImageId\"),results],axis = 1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission.to_csv(\"submission1.csv\", index = False)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"If you found this notebook helpful or you just liked it , some upvotes,Comments would be very much appreciated - That will keep me motivated to update it on a regular basis :-)"},{"metadata":{"trusted":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}