{"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":"\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","scrolled":true,"execution":{"iopub.status.busy":"2023-09-23T08:42:06.870855Z","iopub.execute_input":"2023-09-23T08:42:06.871459Z","iopub.status.idle":"2023-09-23T08:42:06.880268Z","shell.execute_reply.started":"2023-09-23T08:42:06.871411Z","shell.execute_reply":"2023-09-23T08:42:06.878925Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"execution":{"iopub.status.busy":"2023-09-23T07:16:56.938083Z","iopub.execute_input":"2023-09-23T07:16:56.938598Z","iopub.status.idle":"2023-09-23T07:17:01.476350Z","shell.execute_reply.started":"2023-09-23T07:16:56.938569Z","shell.execute_reply":"2023-09-23T07:17:01.474289Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Import packages \nimport tensorflow as tf\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport seaborn as sns\nimport tensorflow as tf\nfrom subprocess import check_output","metadata":{"execution":{"iopub.status.busy":"2023-09-23T07:19:19.274594Z","iopub.execute_input":"2023-09-23T07:19:19.275809Z","iopub.status.idle":"2023-09-23T07:19:29.738718Z","shell.execute_reply.started":"2023-09-23T07:19:19.275760Z","shell.execute_reply":"2023-09-23T07:19:29.737171Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Read and reshape the dataset\ntrain_df=pd.read_csv('/kaggle/input/digit-recognizer/train.csv')\ntrain_df","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df=pd.read_csv('/kaggle/input/digit-recognizer/test.csv')\ntest_df","metadata":{"execution":{"iopub.status.busy":"2023-09-23T07:20:58.598792Z","iopub.execute_input":"2023-09-23T07:20:58.599216Z","iopub.status.idle":"2023-09-23T07:21:01.226908Z","shell.execute_reply.started":"2023-09-23T07:20:58.599183Z","shell.execute_reply":"2023-09-23T07:21:01.225606Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(train_df.shape)\nprint(test_df.shape)","metadata":{"execution":{"iopub.status.busy":"2023-09-23T07:22:00.821944Z","iopub.execute_input":"2023-09-23T07:22:00.822363Z","iopub.status.idle":"2023-09-23T07:22:00.829302Z","shell.execute_reply.started":"2023-09-23T07:22:00.822334Z","shell.execute_reply":"2023-09-23T07:22:00.827944Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\ntrain_y = train_df['label'].astype('float32')\ntrain_x = train_df.drop(['label'],axis = 1).astype('int32')\ntest_x = test_df.astype('float32')\ntrain_x.shape, train_y.shape, test_x.shape","metadata":{"execution":{"iopub.status.busy":"2023-09-23T07:22:52.753321Z","iopub.execute_input":"2023-09-23T07:22:52.753772Z","iopub.status.idle":"2023-09-23T07:22:53.017434Z","shell.execute_reply.started":"2023-09-23T07:22:52.753739Z","shell.execute_reply":"2023-09-23T07:22:53.015981Z"},"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-09-23T07:25:18.279172Z","iopub.execute_input":"2023-09-23T07:25:18.279701Z","iopub.status.idle":"2023-09-23T07:25:18.494008Z","shell.execute_reply.started":"2023-09-23T07:25:18.279664Z","shell.execute_reply":"2023-09-23T07:25:18.492576Z"},"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-09-23T07:25:53.128308Z","iopub.execute_input":"2023-09-23T07:25:53.128744Z","iopub.status.idle":"2023-09-23T07:25:53.139329Z","shell.execute_reply.started":"2023-09-23T07:25:53.128712Z","shell.execute_reply":"2023-09-23T07:25:53.137916Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# original labels of top 5 rows\nprint(train_df['label'].head())","metadata":{"execution":{"iopub.status.busy":"2023-09-23T07:27:49.071382Z","iopub.execute_input":"2023-09-23T07:27:49.071785Z","iopub.status.idle":"2023-09-23T07:27:49.080345Z","shell.execute_reply.started":"2023-09-23T07:27:49.071754Z","shell.execute_reply":"2023-09-23T07:27:49.078822Z"},"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-09-23T07:28:29.882731Z","iopub.execute_input":"2023-09-23T07:28:29.883193Z","iopub.status.idle":"2023-09-23T07:28:29.891376Z","shell.execute_reply.started":"2023-09-23T07:28:29.883162Z","shell.execute_reply":"2023-09-23T07:28:29.889458Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n#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-09-23T07:29:42.697767Z","iopub.execute_input":"2023-09-23T07:29:42.698222Z","iopub.status.idle":"2023-09-23T07:29:43.423317Z","shell.execute_reply.started":"2023-09-23T07:29:42.698191Z","shell.execute_reply":"2023-09-23T07:29:43.421800Z"},"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-09-23T07:30:59.163116Z","iopub.execute_input":"2023-09-23T07:30:59.163633Z","iopub.status.idle":"2023-09-23T07:30:59.173298Z","shell.execute_reply.started":"2023-09-23T07:30:59.163596Z","shell.execute_reply":"2023-09-23T07:30:59.171965Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n#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])","metadata":{"execution":{"iopub.status.busy":"2023-09-23T07:31:27.042108Z","iopub.execute_input":"2023-09-23T07:31:27.042609Z","iopub.status.idle":"2023-09-23T07:58:36.172545Z","shell.execute_reply.started":"2023-09-23T07:31:27.042576Z","shell.execute_reply":"2023-09-23T07:58:36.171306Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nresults = 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-09-23T08:02:07.241557Z","iopub.execute_input":"2023-09-23T08:02:07.242085Z","iopub.status.idle":"2023-09-23T08:02:27.994878Z","shell.execute_reply.started":"2023-09-23T08:02:07.242051Z","shell.execute_reply":"2023-09-23T08:02:27.993619Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission = pd.concat([pd.Series(range(1,28001),name = \"ImageId\"),results],axis = 1)\n\nsubmission.to_csv(\"digitrecog.csv\",index=False)","metadata":{"execution":{"iopub.status.busy":"2023-09-23T08:02:40.015915Z","iopub.execute_input":"2023-09-23T08:02:40.016763Z","iopub.status.idle":"2023-09-23T08:02:40.109506Z","shell.execute_reply.started":"2023-09-23T08:02:40.016718Z","shell.execute_reply":"2023-09-23T08:02:40.108158Z"},"trusted":true},"execution_count":null,"outputs":[]}]}