{"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 in \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 \"../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":"## Reading the Data"},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"# Reading the data\ntest = pd.read_csv(\"/kaggle/input/digit-recognizer/test.csv\")\ntrain = pd.read_csv(\"/kaggle/input/digit-recognizer/train.csv\")\nx_train = train.iloc[:,1:]\ny_train = train.iloc[:,:1]","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Normalizing and Formatting the Data"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Normalizing the pixels values\nx_train = x_train/255.0\ntest = test/255.0\n\n# Bringing dimensions in Keras expected form (examples, hx, hy, channels)\nx_train = x_train.to_numpy().reshape(x_train.shape[0],28,28,1)\ntest = test.to_numpy().reshape(test.shape[0],28,28,1)\n\nprint(\"Train Data Shape is \", x_train.shape)\nprint(\"Train Label data Shape is \", y_train.shape)\nprint(\"Test Data Shape is \", test.shape)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Defining the Model Architecture"},{"metadata":{"trusted":true},"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow import keras\n\nmodel = keras.Sequential([\n    keras.layers.Conv2D(input_shape =(28,28,1), filters=16, kernel_size=(3,3), activation = 'relu',\n                        strides=(1,1), data_format = \"channels_last\",),\n    \n    keras.layers.Conv2D(filters=32, kernel_size=(3,3), activation = 'relu',\n                        strides=(1,1), data_format = \"channels_last\"),\n    keras.layers.MaxPool2D(2,2),\n    \n    keras.layers.Conv2D(filters=64, kernel_size=(3,3), padding = 'same', activation = 'relu',\n                        strides=(1,1), data_format = \"channels_last\"),\n    keras.layers.Dropout(0.2),\n    \n    keras.layers.Conv2D(filters=128, kernel_size=(3,3), padding = 'same', activation = 'relu',\n                        strides=(1,1), data_format = \"channels_last\"),\n    keras.layers.MaxPool2D(2,2),\n    keras.layers.Dropout(0.3),\n    \n    keras.layers.Conv2D(filters=256, kernel_size=(3,3), activation = 'relu',\n                        strides=(1,1), data_format = \"channels_last\"),\n    keras.layers.Dropout(0.3),\n    keras.layers.BatchNormalization(),\n    \n#     keras.layers.Conv2D(filters=256, kernel_size=(3,3), \n#                         strides=(1,1), data_format = \"channels_last\"),\n#     keras.layers.BatchNormalization(),\n    \n    keras.layers.Flatten(),\n    \n    keras.layers.Dense(128, activation=\"relu\"),\n    keras.layers.Dense(10, activation=\"softmax\")\n])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Compiling the Model"},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.optimizers import Adam\nadm = Adam(learning_rate = 0.002)\nmodel.compile(optimizer='adam',\n              loss='sparse_categorical_crossentropy',\n              metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Data Augmentation\ncreating ImageDataGenerator Object and fitting this to the original data to augment it."},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator\ndata_gen = ImageDataGenerator(\n    rotation_range=20,\n    zoom_range = 0.1,  \n    width_shift_range=0.1, \n    height_shift_range=0.1\n)\n\ndata_gen.fit(x_train)\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"len(x_train)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Reducing Learning rate on Plateau"},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.callbacks import ReduceLROnPlateau\nreduce_LR = ReduceLROnPlateau(monitor='acc', \n                                            patience=2, \n                                            verbose=1, \n                                            factor=0.5, \n                                            min_lr=0.00005)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Fitting the Model on Generator"},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit_generator(data_gen.flow(x_train,y_train, batch_size=64),\n                    epochs = 50, \n                    verbose = 1,\n                    callbacks = [reduce_LR])\n# model.fit(x_train, y_train, epochs=10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n# Plot training & validation accuracy values\nplt.plot(history.history['acc'])\nplt.title('Model accuracy')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Test'], loc='upper left')\nplt.show()\n\n# Plot training & validation loss values\nplt.plot(history.history['loss'])\nplt.title('Model loss')\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Test'], loc='upper left')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predictions = model.predict(test)\n\n# select the indix with the maximum probability\npredictions = np.argmax(predictions,axis = 1)\n\npredictions = pd.Series(predictions,name=\"Label\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = pd.concat([pd.Series(range(1,28001),name = \"ImageId\"), predictions],axis = 1)\n\nsubmission.to_csv(\"cnn_mnist.csv\",index=False)","execution_count":null,"outputs":[]},{"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":1}