{"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":"Read The Data from Train & Test csv"},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import pandas as pd\n\ntrain_df = pd.read_csv('/kaggle/input/digit-recognizer/train.csv')\ntest_df = pd.read_csv('/kaggle/input/digit-recognizer/test.csv')\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.shape","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Prepare Training & Test Data "},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train = train_df.drop([\"label\"],axis = 1)\nY_train = train_df[\"label\"]\nX_test=test_df","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"raw","source":"X_train = X_train/255.0\nX_test = X_test/255.0"},{"metadata":{},"cell_type":"markdown","source":"Reshape the Input Data for CNN in format(Img_height,Img_width, channel)"},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train = X_train.values.reshape(len(X_train), 28, 28,1)\nX_test = X_test.values.reshape(len(X_test), 28, 28,1)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"One-Hot Encoding for Output Label"},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.utils.np_utils import to_categorical\nY_train = to_categorical(Y_train, num_classes = 10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Initialize the random number generator\nimport random\nrandom.seed(0)\n\n# Ignore the warnings\nimport warnings\nwarnings.filterwarnings(\"ignore\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Split the training & test data "},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n# Set the random seed\nrandom_seed = 0\n# Split the train and the validation set for the fitting\nX_train, X_val, Y_train, Y_val = train_test_split(X_train, Y_train, test_size = 0.2, random_state=random_seed)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Create Model"},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.layers import Conv2D\n\nfrom keras.models import Sequential\nfrom keras.layers import  Flatten,Activation\nfrom keras.layers import Dense,Conv2D, MaxPooling2D,BatchNormalization,GlobalAveragePooling2D,Dropout\n\nmodel = Sequential()\nmodel.add(Conv2D(filters=32, kernel_size=3, activation=\"relu\", input_shape=(28, 28, 1))) #26\nmodel.add(BatchNormalization())\n\nmodel.add(Conv2D(filters=16,dilation_rate=(3, 3), kernel_size=3, activation=\"relu\")) # 24\nmodel.add(BatchNormalization())\n\nmodel.add(Conv2D(filters=64, kernel_size=3, activation=\"relu\"))#22\nmodel.add(BatchNormalization())\n\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.1))\n\nmodel.add(Conv2D(filters=64, dilation_rate=(3, 3), kernel_size=3, activation=\"relu\"))# 8\nmodel.add(BatchNormalization())\n\nmodel.add(Conv2D(filters=32, kernel_size=2, activation=\"relu\"))# 7\nmodel.add(BatchNormalization())\n\nmodel.add(Conv2D(filters=10, kernel_size=1, activation=\"relu\"))# 7\nmodel.add(BatchNormalization())\n\n\n# model.add(Flatten())\nmodel.add(GlobalAveragePooling2D())\n\nmodel.add(Dense(16, activation=\"relu\"))\nmodel.add(Dropout(0.1))\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":"Compile the model\n1. Set the Metrics\n2. Set the optimizer(need for backtracking for convergence of loss)\n3. Set the loss function"},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(loss=\"categorical_crossentropy\", metrics=[\"accuracy\"], optimizer=\"adam\")\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\nimport tensorflow as tf\nbatch_size=32\ncallback = tf.keras.callbacks.EarlyStopping(monitor='val_accuracy', patience=5, min_delta=0.01)\nlr_reduction = tf.keras.callbacks.ReduceLROnPlateau(monitor='val_loss', \n                                 patience=10, \n                                 verbose=2, \n                                 factor=.75)\nhistory = model.fit(X_train, Y_train, epochs=35,verbose=1,validation_data = (X_val,Y_val),batch_size=batch_size,callbacks=[lr_reduction])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Print Validation Accuracy"},{"metadata":{"trusted":true},"cell_type":"code","source":"val_loss, val_accuracy= model.evaluate(X_train,Y_train)\nprint(\"Validation Accuracy:\",val_accuracy)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Plot Training Accuracy vs Validation Accuracy"},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\n%matplotlib inline\n\nacc_train = history.history['accuracy']\n# print(len(acc_train))\nacc_val = history.history['val_accuracy']\n# print(len(acc_val))\n\nepochs = range(1,36)\nplt.plot(epochs, acc_train, 'g', label='Training accuracy')\nplt.plot(epochs, acc_val, 'b', label='validation accuracy')\nplt.title('Training and Validation accuracy Model')\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.legend()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Plot Training & Validation Loss"},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\n%matplotlib inline\n\nloss_train = history.history['loss']\nloss_val = history.history['val_loss']\n\nepochs = range(1,36)\nplt.plot(epochs, loss_train, 'g', label='Training loss')\nplt.plot(epochs, loss_val, 'b', label='validation loss')\nplt.title('Training and Validation loss for Model')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.legend()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# predict results\nresults = model.predict(X_test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_results = np.argmax(results,axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"results = pd.Series(test_results,name=\"Label\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Save the Results to CSV File for Submission"},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = pd.concat([pd.Series(range(1,28001),name = \"ImageId\"),results],axis = 1)\n\nsubmission.to_csv(\"predictions_cnn_dilated_3.csv\",index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"results","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":4}