{"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)\nfrom keras.utils import to_categorical\n\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":"2021-09-07T12:27:07.929083Z","iopub.execute_input":"2021-09-07T12:27:07.929414Z","iopub.status.idle":"2021-09-07T12:27:11.888780Z","shell.execute_reply.started":"2021-09-07T12:27:07.929341Z","shell.execute_reply":"2021-09-07T12:27:11.887360Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data = pd.read_csv(\"../input/digit-recognizer/train.csv\")\ntest_data = pd.read_csv(\"../input/digit-recognizer/test.csv\")","metadata":{"execution":{"iopub.status.busy":"2021-09-07T12:27:11.891772Z","iopub.execute_input":"2021-09-07T12:27:11.892069Z","iopub.status.idle":"2021-09-07T12:27:17.222245Z","shell.execute_reply.started":"2021-09-07T12:27:11.892042Z","shell.execute_reply":"2021-09-07T12:27:17.221332Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train = train_data.iloc[:,1:]\ny_train = train_data['label'].values.reshape(-1, 1)\n\nx_test = test_data\n\nx_train /= 255\nx_test /= 255\n\nx_train = x_train.values.reshape(-1,28,28,1)\nx_test = x_test.values.reshape(-1,28,28,1)\n\ny_train = to_categorical(y_train, num_classes = 10)\n","metadata":{"execution":{"iopub.status.busy":"2021-09-07T12:27:17.225309Z","iopub.execute_input":"2021-09-07T12:27:17.225633Z","iopub.status.idle":"2021-09-07T12:27:17.424610Z","shell.execute_reply.started":"2021-09-07T12:27:17.225600Z","shell.execute_reply":"2021-09-07T12:27:17.423754Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(x_train.shape)\nprint(x_test.shape)\nprint(y_train.shape)\n","metadata":{"execution":{"iopub.status.busy":"2021-09-07T12:27:17.427894Z","iopub.execute_input":"2021-09-07T12:27:17.428179Z","iopub.status.idle":"2021-09-07T12:27:17.435506Z","shell.execute_reply.started":"2021-09-07T12:27:17.428151Z","shell.execute_reply":"2021-09-07T12:27:17.434719Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\nimport itertools\n\nfrom keras.utils.np_utils import to_categorical # convert to one-hot-encoding\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D\nfrom keras.optimizers import RMSprop\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import ReduceLROnPlateau\n\n\nmodel = Sequential()\nmodel.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', activation ='relu', input_shape = (28,28,1)))\nmodel.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', activation ='relu'))\nmodel.add(MaxPool2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))\nmodel.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same', activation ='relu'))\nmodel.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same', activation ='relu'))\nmodel.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))\nmodel.add(Dropout(0.25))\nmodel.add(Flatten())\nmodel.add(Dense(256, activation = \"relu\"))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(10, activation = \"softmax\"))","metadata":{"execution":{"iopub.status.busy":"2021-09-07T12:27:17.436992Z","iopub.execute_input":"2021-09-07T12:27:17.437543Z","iopub.status.idle":"2021-09-07T12:27:19.676566Z","shell.execute_reply.started":"2021-09-07T12:27:17.437503Z","shell.execute_reply":"2021-09-07T12:27:19.675743Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"optimizer = RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0)\nmodel.compile(optimizer = optimizer , loss = \"categorical_crossentropy\", metrics=[\"accuracy\"])\n","metadata":{"execution":{"iopub.status.busy":"2021-09-07T12:27:19.678782Z","iopub.execute_input":"2021-09-07T12:27:19.679279Z","iopub.status.idle":"2021-09-07T12:27:19.692850Z","shell.execute_reply.started":"2021-09-07T12:27:19.679242Z","shell.execute_reply":"2021-09-07T12:27:19.692059Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"learning_rate_reduction = ReduceLROnPlateau(monitor='val_acc', \n                                            patience=3, \n                                            verbose=1, \n                                            factor=0.5, \n                                            min_lr=0.00001)\nepochs = 30 # Turn epochs to 30 to get 0.9967 accuracy\nbatch_size = 16\n\n","metadata":{"execution":{"iopub.status.busy":"2021-09-07T12:27:19.694955Z","iopub.execute_input":"2021-09-07T12:27:19.695506Z","iopub.status.idle":"2021-09-07T12:27:19.700827Z","shell.execute_reply.started":"2021-09-07T12:27:19.695470Z","shell.execute_reply":"2021-09-07T12:27:19.699960Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit(x=x_train, y=y_train, epochs=3, shuffle=True)\n","metadata":{"execution":{"iopub.status.busy":"2021-09-07T12:27:19.703184Z","iopub.execute_input":"2021-09-07T12:27:19.703530Z","iopub.status.idle":"2021-09-07T12:27:44.604771Z","shell.execute_reply.started":"2021-09-07T12:27:19.703496Z","shell.execute_reply":"2021-09-07T12:27:44.603882Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"preds = model.predict(x_test)\n","metadata":{"execution":{"iopub.status.busy":"2021-09-07T12:27:44.606760Z","iopub.execute_input":"2021-09-07T12:27:44.607143Z","iopub.status.idle":"2021-09-07T12:27:45.757623Z","shell.execute_reply.started":"2021-09-07T12:27:44.607101Z","shell.execute_reply":"2021-09-07T12:27:45.756699Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"result = []\nfor i in range(len(preds)):\n    #print(i, np.argmax(preds[i]))\n    result.append(np.argmax(preds[i]))\n    ","metadata":{"execution":{"iopub.status.busy":"2021-09-07T12:27:45.758854Z","iopub.execute_input":"2021-09-07T12:27:45.759204Z","iopub.status.idle":"2021-09-07T12:27:45.847169Z","shell.execute_reply.started":"2021-09-07T12:27:45.759171Z","shell.execute_reply":"2021-09-07T12:27:45.846422Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport seaborn as sns\n\nprint(result[27])\ng = plt.imshow(x_test[27][:,:,0])\n","metadata":{"execution":{"iopub.status.busy":"2021-09-07T12:27:45.848292Z","iopub.execute_input":"2021-09-07T12:27:45.848771Z","iopub.status.idle":"2021-09-07T12:27:46.144308Z","shell.execute_reply.started":"2021-09-07T12:27:45.848732Z","shell.execute_reply":"2021-09-07T12:27:46.143330Z"},"trusted":true},"execution_count":null,"outputs":[]}]}