{"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":"2022-05-18T11:26:36.723645Z","iopub.execute_input":"2022-05-18T11:26:36.723974Z","iopub.status.idle":"2022-05-18T11:26:36.755344Z","shell.execute_reply.started":"2022-05-18T11:26:36.723939Z","shell.execute_reply":"2022-05-18T11:26:36.754355Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Importing Libraries","metadata":{}},{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom tensorflow.keras import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout,Flatten, Conv2D, MaxPool2D, Conv2D,BatchNormalization\nfrom keras.callbacks import ReduceLROnPlateau","metadata":{"execution":{"iopub.status.busy":"2022-05-18T11:26:36.757607Z","iopub.execute_input":"2022-05-18T11:26:36.7586Z","iopub.status.idle":"2022-05-18T11:26:36.76539Z","shell.execute_reply.started":"2022-05-18T11:26:36.758547Z","shell.execute_reply":"2022-05-18T11:26:36.764203Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Reading Train and Test CSV","metadata":{}},{"cell_type":"code","source":"X_train = pd.read_csv('/kaggle/input/digit-recognizer/train.csv')\nX_test = pd.read_csv('/kaggle/input/digit-recognizer/test.csv')\n\ny_train = X_train.pop('label')","metadata":{"execution":{"iopub.status.busy":"2022-05-18T11:26:36.766568Z","iopub.execute_input":"2022-05-18T11:26:36.767544Z","iopub.status.idle":"2022-05-18T11:26:41.543137Z","shell.execute_reply.started":"2022-05-18T11:26:36.767497Z","shell.execute_reply":"2022-05-18T11:26:41.542491Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(X_train.shape)\nprint(y_train.shape)","metadata":{"execution":{"iopub.status.busy":"2022-05-18T11:26:41.545142Z","iopub.execute_input":"2022-05-18T11:26:41.546147Z","iopub.status.idle":"2022-05-18T11:26:41.552093Z","shell.execute_reply.started":"2022-05-18T11:26:41.546091Z","shell.execute_reply":"2022-05-18T11:26:41.55107Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train = np.array(X_train)\ny_train = np.array(y_train)\nX_test = np.array(X_test)","metadata":{"execution":{"iopub.status.busy":"2022-05-18T11:26:41.553208Z","iopub.execute_input":"2022-05-18T11:26:41.553815Z","iopub.status.idle":"2022-05-18T11:26:41.954618Z","shell.execute_reply.started":"2022-05-18T11:26:41.553768Z","shell.execute_reply":"2022-05-18T11:26:41.953704Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img_rows,img_cols=28,28\ninput_shape = (img_rows,img_cols,1)\nbatch_size=128\nnum_classes =10\nepochs = 25","metadata":{"execution":{"iopub.status.busy":"2022-05-18T11:26:41.956214Z","iopub.execute_input":"2022-05-18T11:26:41.956721Z","iopub.status.idle":"2022-05-18T11:26:41.961731Z","shell.execute_reply.started":"2022-05-18T11:26:41.956675Z","shell.execute_reply":"2022-05-18T11:26:41.960701Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Reshaping to Single Channel","metadata":{}},{"cell_type":"code","source":"X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, 1)\nX_test = X_test.reshape(X_test.shape[0], img_rows, img_cols, 1)","metadata":{"execution":{"iopub.status.busy":"2022-05-18T11:26:41.962949Z","iopub.execute_input":"2022-05-18T11:26:41.963182Z","iopub.status.idle":"2022-05-18T11:26:41.976812Z","shell.execute_reply.started":"2022-05-18T11:26:41.963154Z","shell.execute_reply":"2022-05-18T11:26:41.975829Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"index  = 10\nk = X_train[index,:]\nk = k.reshape((28, 28))\nplt.imshow(k, cmap='gray')","metadata":{"execution":{"iopub.status.busy":"2022-05-18T11:26:41.978345Z","iopub.execute_input":"2022-05-18T11:26:41.978665Z","iopub.status.idle":"2022-05-18T11:26:42.191149Z","shell.execute_reply.started":"2022-05-18T11:26:41.978634Z","shell.execute_reply":"2022-05-18T11:26:42.190064Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig, axis=plt.subplots(3, 3, figsize=(10, 10))\ny_train1 = y_train.reshape(1, len(y_train))\nfor index, ax in enumerate(axis.flat):\n        ax.imshow(X_train[index],cmap=plt.cm.binary)\n        ax.set(title = f\"Number is {y_train1[0,index]}\")","metadata":{"execution":{"iopub.status.busy":"2022-05-18T11:26:42.193706Z","iopub.execute_input":"2022-05-18T11:26:42.194068Z","iopub.status.idle":"2022-05-18T11:26:43.259349Z","shell.execute_reply.started":"2022-05-18T11:26:42.194032Z","shell.execute_reply":"2022-05-18T11:26:43.258468Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Comverting Class Labels to One Hot Encoded Vectors","metadata":{}},{"cell_type":"code","source":"# convert class labels (from digits) to one-hot encoded vectors\ny_train = tf.keras.utils.to_categorical(y_train, num_classes)\nprint(y_train.shape)","metadata":{"execution":{"iopub.status.busy":"2022-05-18T11:26:43.260753Z","iopub.execute_input":"2022-05-18T11:26:43.261019Z","iopub.status.idle":"2022-05-18T11:26:43.267988Z","shell.execute_reply.started":"2022-05-18T11:26:43.260987Z","shell.execute_reply":"2022-05-18T11:26:43.266861Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train.dtype","metadata":{"execution":{"iopub.status.busy":"2022-05-18T11:26:43.269675Z","iopub.execute_input":"2022-05-18T11:26:43.270026Z","iopub.status.idle":"2022-05-18T11:26:43.281421Z","shell.execute_reply.started":"2022-05-18T11:26:43.26998Z","shell.execute_reply":"2022-05-18T11:26:43.28044Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# convert int to float\nX_train = X_train.astype('float32')\nX_test = X_test.astype('float32')\n\n# normalise\nX_train /= 255\nX_test /= 255","metadata":{"execution":{"iopub.status.busy":"2022-05-18T11:26:43.28293Z","iopub.execute_input":"2022-05-18T11:26:43.283202Z","iopub.status.idle":"2022-05-18T11:26:43.42261Z","shell.execute_reply.started":"2022-05-18T11:26:43.283167Z","shell.execute_reply":"2022-05-18T11:26:43.421503Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Training Model","metadata":{}},{"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Conv2D(64, kernel_size=(3, 3), padding='same',input_shape=(img_rows, img_cols, 1),activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(64, kernel_size=(3, 3), padding = 'same',activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPool2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))\n\n\nmodel.add(Conv2D(32, kernel_size=(3, 3), padding = 'same',activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.25))\n\nmodel.add(Flatten())\n\nmodel.add(Dense(256,activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.25))\nmodel.add(Dense(128,activation='relu'))\nmodel.add(Dense(num_classes, activation='softmax'))\n\nmodel.summary()\n\n\n          ","metadata":{"execution":{"iopub.status.busy":"2022-05-18T11:26:43.423966Z","iopub.execute_input":"2022-05-18T11:26:43.424233Z","iopub.status.idle":"2022-05-18T11:26:43.683526Z","shell.execute_reply.started":"2022-05-18T11:26:43.4242Z","shell.execute_reply":"2022-05-18T11:26:43.682282Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"lr_reduction = ReduceLROnPlateau(monitor='val_loss',patience=4, verbose=1,  factor=0.4, min_lr=0.0001)\n\nmodel.compile(loss=tf.keras.losses.categorical_crossentropy,\n             optimizer = 'adam',\n             metrics = ['accuracy'])\n","metadata":{"execution":{"iopub.status.busy":"2022-05-18T11:26:43.684963Z","iopub.execute_input":"2022-05-18T11:26:43.685246Z","iopub.status.idle":"2022-05-18T11:26:43.702396Z","shell.execute_reply.started":"2022-05-18T11:26:43.685211Z","shell.execute_reply":"2022-05-18T11:26:43.701657Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.fit(X_train, y_train,\n          batch_size=batch_size,\n          epochs=epochs,\n          verbose=1,callbacks=[lr_reduction])","metadata":{"execution":{"iopub.status.busy":"2022-05-18T11:26:43.703943Z","iopub.execute_input":"2022-05-18T11:26:43.704758Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Model Prediction","metadata":{}},{"cell_type":"code","source":"X_test_pred = model.predict(X_test)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_test_pred.shape","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"output = pd.DataFrame({\"Label\": X_test_pred.argmax(axis=1)}, index=range(1, 28001))\noutput.index.name = \"ImageId\"\noutput.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"output.to_csv(\"submission.csv\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}