{"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_minor":4,"nbformat":4,"cells":[{"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","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-05-19T17:20:40.705983Z","iopub.execute_input":"2023-05-19T17:20:40.706434Z","iopub.status.idle":"2023-05-19T17:20:40.718065Z","shell.execute_reply.started":"2023-05-19T17:20:40.706394Z","shell.execute_reply":"2023-05-19T17:20:40.716240Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Importing important packages","metadata":{}},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport seaborn as sns\nimport tensorflow as tf","metadata":{"execution":{"iopub.status.busy":"2023-05-19T17:20:40.721453Z","iopub.execute_input":"2023-05-19T17:20:40.722071Z","iopub.status.idle":"2023-05-19T17:20:40.738545Z","shell.execute_reply.started":"2023-05-19T17:20:40.722018Z","shell.execute_reply":"2023-05-19T17:20:40.737223Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Read and Reshape the dataset","metadata":{}},{"cell_type":"code","source":"# Read training and test data files\ntrain = pd.read_csv(\"/kaggle/input/digit-recognizer/train.csv\")\ntest  = pd.read_csv(\"/kaggle/input/digit-recognizer/test.csv\")\ntrain.head()","metadata":{"execution":{"iopub.status.busy":"2023-05-19T17:20:40.740144Z","iopub.execute_input":"2023-05-19T17:20:40.741451Z","iopub.status.idle":"2023-05-19T17:20:46.190682Z","shell.execute_reply.started":"2023-05-19T17:20:40.741409Z","shell.execute_reply":"2023-05-19T17:20:46.189738Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(train.shape)\nprint(test.shape)","metadata":{"execution":{"iopub.status.busy":"2023-05-19T17:20:46.193831Z","iopub.execute_input":"2023-05-19T17:20:46.194201Z","iopub.status.idle":"2023-05-19T17:20:46.200819Z","shell.execute_reply.started":"2023-05-19T17:20:46.194171Z","shell.execute_reply":"2023-05-19T17:20:46.199634Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_y = train['label'].astype('float32')\ntrain_x = train.drop(['label'],axis = 1).astype('int32')\ntest_x = test.astype('float32')\ntrain_x.shape, train_y.shape, test_x.shape","metadata":{"execution":{"iopub.status.busy":"2023-05-19T17:20:46.202556Z","iopub.execute_input":"2023-05-19T17:20:46.203268Z","iopub.status.idle":"2023-05-19T17:20:46.448830Z","shell.execute_reply.started":"2023-05-19T17:20:46.203228Z","shell.execute_reply":"2023-05-19T17:20:46.447523Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_x = train_x.values.reshape(-1,28,28,1)\ntrain_x = train_x / 255.0\ntest_x = test_x.values.reshape(-1,28,28,1)\ntest_x = test_x / 255.0\ntrain_x.shape, test_x.shape","metadata":{"execution":{"iopub.status.busy":"2023-05-19T17:20:46.450204Z","iopub.execute_input":"2023-05-19T17:20:46.450774Z","iopub.status.idle":"2023-05-19T17:20:46.579340Z","shell.execute_reply.started":"2023-05-19T17:20:46.450736Z","shell.execute_reply":"2023-05-19T17:20:46.578170Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#One Hot Encoding\ntrain_y = tf.keras.utils.to_categorical(train_y,10)\ntrain_y.shape","metadata":{"execution":{"iopub.status.busy":"2023-05-19T17:20:46.580886Z","iopub.execute_input":"2023-05-19T17:20:46.581208Z","iopub.status.idle":"2023-05-19T17:20:46.589944Z","shell.execute_reply.started":"2023-05-19T17:20:46.581182Z","shell.execute_reply":"2023-05-19T17:20:46.588839Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Printing original labels of top 5 rows\nprint(train['label'].head())","metadata":{"execution":{"iopub.status.busy":"2023-05-19T17:20:46.591391Z","iopub.execute_input":"2023-05-19T17:20:46.591887Z","iopub.status.idle":"2023-05-19T17:20:46.602221Z","shell.execute_reply.started":"2023-05-19T17:20:46.591829Z","shell.execute_reply":"2023-05-19T17:20:46.601005Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#One hot encoding of the same labels\nprint(train_y[0:5,:])","metadata":{"execution":{"iopub.status.busy":"2023-05-19T17:20:46.603826Z","iopub.execute_input":"2023-05-19T17:20:46.604667Z","iopub.status.idle":"2023-05-19T17:20:46.617636Z","shell.execute_reply.started":"2023-05-19T17:20:46.604624Z","shell.execute_reply":"2023-05-19T17:20:46.616164Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### The Model","metadata":{}},{"cell_type":"code","source":"#Defining the model\nmodel = tf.keras.models.Sequential([\n  tf.keras.layers.Conv2D(32,(3,3),activation = 'relu', input_shape=(28,28,1)),\n  tf.keras.layers.Conv2D(32,(3,3),activation = 'relu'),\n  tf.keras.layers.MaxPooling2D(2,2),\n  tf.keras.layers.Conv2D(64,(3,3),activation = 'relu',padding = 'Same'),\n  tf.keras.layers.Conv2D(64,(3,3),activation = 'relu',padding = 'Same'),\n  tf.keras.layers.MaxPooling2D(pool_size = (2,2), strides = (2,2)),\n  tf.keras.layers.Dropout(0.25),\n  tf.keras.layers.Conv2D(64,(3,3),activation = 'relu',padding = 'Same'),\n  tf.keras.layers.Conv2D(64,(3,3),activation = 'relu',padding = 'Same'),\n  tf.keras.layers.MaxPooling2D(pool_size = (2,2), strides = (2,2)),\n  tf.keras.layers.Dropout(0.25),\n  tf.keras.layers.Flatten(),\n  tf.keras.layers.Dense(256, activation='relu'),\n  #tf.keras.layers.Dropout(0.50),\n  tf.keras.layers.Dense(256, activation='relu'),\n  tf.keras.layers.Dropout(0.50),\n  tf.keras.layers.Dense(10, activation='softmax')\n])\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2023-05-19T17:20:46.621681Z","iopub.execute_input":"2023-05-19T17:20:46.622212Z","iopub.status.idle":"2023-05-19T17:20:47.026339Z","shell.execute_reply.started":"2023-05-19T17:20:46.622178Z","shell.execute_reply":"2023-05-19T17:20:47.023556Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Defining the callback function to stop our training once the acceptable accuracy is reached\nclass myCallback(tf.keras.callbacks.Callback):\n        def on_epoch_end(self, epoch, logs={}):\n            if(logs.get('accuracy') > 0.999):\n                print(\"\\nReached 99.9% accuracy so cancelling training!\")\n                self.model.stop_training = True\n    \ncallbacks = myCallback()","metadata":{"execution":{"iopub.status.busy":"2023-05-19T17:20:47.028661Z","iopub.execute_input":"2023-05-19T17:20:47.029159Z","iopub.status.idle":"2023-05-19T17:20:47.037631Z","shell.execute_reply.started":"2023-05-19T17:20:47.029116Z","shell.execute_reply":"2023-05-19T17:20:47.036161Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Compiling and model training with batch size = 50, epochs = 20, and optimizer = adam\nOptimizer = tf.keras.optimizers.Adam(\n            learning_rate=0.0005, \n            beta_1=0.9, \n            beta_2=0.999, \n            epsilon=1e-07,\n            name='Adam'\n)\nmodel.compile(optimizer=Optimizer, loss='categorical_crossentropy', metrics=['accuracy'])\nmodel.fit(train_x, train_y, batch_size = 50, epochs = 20, callbacks=[callbacks])\n     ","metadata":{"execution":{"iopub.status.busy":"2023-05-19T17:20:47.039522Z","iopub.execute_input":"2023-05-19T17:20:47.040602Z","iopub.status.idle":"2023-05-19T17:47:55.256422Z","shell.execute_reply.started":"2023-05-19T17:20:47.040558Z","shell.execute_reply":"2023-05-19T17:47:55.255423Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"results = model.predict(test_x)\n\n# select the index with the maximum probability\nresults = np.argmax(results,axis = 1)\n\nresults = pd.Series(results,name=\"Label\")","metadata":{"execution":{"iopub.status.busy":"2023-05-19T17:47:55.257831Z","iopub.execute_input":"2023-05-19T17:47:55.258361Z","iopub.status.idle":"2023-05-19T17:48:16.094405Z","shell.execute_reply.started":"2023-05-19T17:47:55.258331Z","shell.execute_reply":"2023-05-19T17:48:16.093056Z"},"trusted":true},"execution_count":null,"outputs":[]}]}