{"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 20GB 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":"## Importing Necessary Libraries"},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator\nfrom keras.optimizers import RMSprop,Adam\nfrom keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D,AvgPool2D\nfrom keras.models import Sequential\nfrom keras.utils.np_utils import to_categorical  # convert to one-hot-encoding\nimport itertools\nfrom sklearn.model_selection import train_test_split\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Loading the Data"},{"metadata":{"trusted":true},"cell_type":"code","source":"train=pd.read_csv('/kaggle/input/digit-recognizer/train.csv')\ntest=pd.read_csv('/kaggle/input/digit-recognizer/test.csv')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Preparing the Data"},{"metadata":{"trusted":true},"cell_type":"code","source":"Y_train = train['label']\nX_train = train.drop(labels=['label'], axis=1)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Normalizing the Image Pixel Values"},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train=X_train/255.0\ntest=test/255.0","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Reshaping the Values"},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train = X_train.values.reshape(-1, 28, 28, 1)  # -1 all values *unlimited*\ntest = test.values.reshape(-1, 28, 28, 1)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## One Hot Encoding the Labels"},{"metadata":{"trusted":true},"cell_type":"code","source":"Y_train = to_categorical(Y_train, num_classes=10)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Splitting the Data into train and validation"},{"metadata":{"trusted":true},"cell_type":"code","source":"random_seed = 2\nX_train, X_val, Y_train, Y_val = train_test_split(\n    X_train, Y_train, test_size=0.1, random_state=random_seed)\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Creating the Lenet5 Architecture Model"},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential()\n\n# Adding a Convolution Layer C1\n# Input shape = N = (28 x 28)\n# No. of filters  = 6\n# Filter size = f = (5 x 5)\n# Padding = P = 0\n# Strides = S = 1\n# Size of each feature map in C1 is (N-f+2P)/S +1 = 28-5+1 = 24\n# No. of parameters between input layer and C1 = (5*5 + 1)*6 = 156\nmodel.add(Conv2D(filters=6, kernel_size=(5,5), padding='valid', input_shape=(28,28,1), activation='tanh'))\n\n# Adding an Average Pooling Layer S2\n# Input shape = N = (24 x 24)\n# No. of filters = 6\n# Filter size = f = (2 x 2)\n# Padding = P = 0\n# Strides = S = 2\n# Size of each feature map in S2 is (N-f+2P)/S +1 = (24-2+0)/2+1 = 11+1 = 12\n# No. of parameters between C1 and S2 = (1+1)*6 = 12\nmodel.add(AvgPool2D(pool_size=(2,2)))\n\n# Adding a Convolution Layer C3\n# Input shape = N = (12 x 12)\n# No. of filters  = 16\n# Filter size = f = (5 x 5)\n# Padding = P = 0\n# Strides = S = 1\n# Size of each feature map in C3 is (N-f+2P)/S +1 = 12-5+1 = 8\n# No. of parameters between S2 and C3 = (5*5*6*16 + 16) + 16 = 2416\nmodel.add(Conv2D(filters=16, kernel_size=(5,5), padding='valid', activation='tanh'))\n\n# Adding an Average Pooling Layer S4\n# Input shape = N = (8 x 8)\n# No. of filters = 16\n# Filter size = f = (2 x 2)\n# Padding = P = 0\n# Strides = S = 2\n# Size of each feature map in S4 is (N-f+2P)/S +1 = (8-2+0)/2+1 = 3+1 = 4\n# No. of parameters between C3 and S4 = (1+1)*16 = 32\nmodel.add(AvgPool2D(pool_size=(2,2)))\n\n# As compared to LeNet-5 architecture there was one more application of convolution but in our code  further application of \n# convolution with (5 x 5) filter would result in a negative dimension which is not possible. So we aren't applying any more\n# convolution here.\n\n# Flattening the layer S4\n# There would be 16*(4*4) = 256 neurons\nmodel.add(Flatten())\n\n# Adding a Dense layer with `tanh` activation+# \n# No. of inputs = 256\n# No. of outputs = 120\n# No. of parameters = 256*120 + 120 = 30,840\nmodel.add(Dense(120, activation='tanh'))\n\n# Adding a Dense layer with `tanh` activation\n# No. of inputs = 120\n# No. of outputs = 84\n# No. of parameters = 120*84 + 84 = 10,164\nmodel.add(Dense(84, activation='tanh'))\n\n# Adding a Dense layer with `softmax` activation\n# No. of inputs = 84\n# No. of outputs = 10\n# No. of parameters = 84*10 + 10 = 850\nmodel.add(Dense(10, activation='softmax'))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Model Details"},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Compile the model"},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(optimizer=\"Adam\",\n              loss=\"categorical_crossentropy\", metrics=[\"accuracy\"])\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Fitting the model"},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit(X_train, Y_train, batch_size=128, epochs=30,\n                    validation_data=(X_val, Y_val), verbose=2)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Model Performance"},{"metadata":{"trusted":true},"cell_type":"code","source":"score = model.evaluate(X_val,Y_val)\ntrainscore=model.evaluate(X_train,Y_train)\nprint('Test Loss:', score[0])\nprint('Test accuracy:', score[1])\nprint(\"Train Loss\",trainscore[0])\nprint(\"Train accuracy\",trainscore[1])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Predictions on Unseen Data"},{"metadata":{"trusted":true},"cell_type":"code","source":"y_result = model.predict(test)\nprint('Prediction Shape is {}'.format(y_result.shape))\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"results = np.argmax(y_result,axis = 1)\nresults = pd.Series(results,name=\"Label\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"image_ids=pd.Series(range(1,28001),name = \"ImageId\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"My_submission = pd.concat([image_ids,results],axis = 1)\nMy_submission.to_csv(\"submission.csv\",index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"My_submission.head()\n","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}