{"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)\nimport tensorflow as tf\n\nfrom tensorflow import keras\nfrom keras import Sequential\nfrom keras.layers import Dense, Conv2D, Flatten, BatchNormalization, Activation, MaxPooling2D\nfrom keras.utils.np_utils import to_categorical\nfrom keras.callbacks import ReduceLROnPlateau\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom sklearn.model_selection import train_test_split\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-05T04:55:28.210314Z","iopub.execute_input":"2022-05-05T04:55:28.211121Z","iopub.status.idle":"2022-05-05T04:55:34.759286Z","shell.execute_reply.started":"2022-05-05T04:55:28.211032Z","shell.execute_reply":"2022-05-05T04:55:34.758258Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train_full=pd.read_csv('/kaggle/input/digit-recognizer/train.csv', header='infer').values\nX_test=pd.read_csv('/kaggle/input/digit-recognizer/test.csv', header='infer').values","metadata":{"execution":{"iopub.status.busy":"2022-05-05T04:55:34.762603Z","iopub.execute_input":"2022-05-05T04:55:34.762971Z","iopub.status.idle":"2022-05-05T04:55:42.174527Z","shell.execute_reply.started":"2022-05-05T04:55:34.762915Z","shell.execute_reply":"2022-05-05T04:55:42.173577Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train=X_train_full[:,1:]\ny_train=X_train_full[:,0]","metadata":{"execution":{"iopub.status.busy":"2022-05-05T04:55:42.176770Z","iopub.execute_input":"2022-05-05T04:55:42.177542Z","iopub.status.idle":"2022-05-05T04:55:42.183966Z","shell.execute_reply.started":"2022-05-05T04:55:42.177496Z","shell.execute_reply":"2022-05-05T04:55:42.182744Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train = (X_train.astype(np.float32) - 127.5)/127.5\nX_test = (X_test.astype(np.float32) - 127.5)/127.5","metadata":{"execution":{"iopub.status.busy":"2022-05-05T04:55:42.186992Z","iopub.execute_input":"2022-05-05T04:55:42.187402Z","iopub.status.idle":"2022-05-05T04:55:42.372310Z","shell.execute_reply.started":"2022-05-05T04:55:42.187358Z","shell.execute_reply":"2022-05-05T04:55:42.371254Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train=X_train.reshape(-1,28,28,1)\nX_test=X_test.reshape(-1,28,28,1)","metadata":{"execution":{"iopub.status.busy":"2022-05-05T04:55:42.375287Z","iopub.execute_input":"2022-05-05T04:55:42.375817Z","iopub.status.idle":"2022-05-05T04:55:42.382345Z","shell.execute_reply.started":"2022-05-05T04:55:42.375769Z","shell.execute_reply":"2022-05-05T04:55:42.381069Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_train_vectors=to_categorical(y_train)","metadata":{"execution":{"iopub.status.busy":"2022-05-05T04:55:42.384302Z","iopub.execute_input":"2022-05-05T04:55:42.384691Z","iopub.status.idle":"2022-05-05T04:55:42.396325Z","shell.execute_reply.started":"2022-05-05T04:55:42.384642Z","shell.execute_reply":"2022-05-05T04:55:42.395090Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train, X_val, y_train, y_val= train_test_split(X_train, y_train_vectors, test_size=0.2, random_state=2)","metadata":{"execution":{"iopub.status.busy":"2022-05-05T04:55:42.398881Z","iopub.execute_input":"2022-05-05T04:55:42.399199Z","iopub.status.idle":"2022-05-05T04:55:42.799707Z","shell.execute_reply.started":"2022-05-05T04:55:42.399168Z","shell.execute_reply":"2022-05-05T04:55:42.798674Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cnn=Sequential()\n\ncnn.add(Conv2D(filters=32, kernel_size=(3,3), strides=(1,1), padding='valid', activation=None, use_bias=False, input_shape=(X_train.shape[1:])))\ncnn.add(BatchNormalization())\ncnn.add(Activation('relu'))\ncnn.add(Conv2D(filters=64, kernel_size=(3,3), strides=(1,1), padding='valid', activation=None, use_bias=False))\ncnn.add(BatchNormalization())\ncnn.add(Activation('relu'))\ncnn.add(MaxPooling2D(pool_size=(2,2)))\n\ncnn.add(Conv2D(filters=96, kernel_size=(3,3), strides=(1,1), padding='valid', activation=None, use_bias=False))\ncnn.add(BatchNormalization())\ncnn.add(Activation('relu'))\ncnn.add(Conv2D(filters=128, kernel_size=(3,3), strides=(1,1), padding='valid', activation=None, use_bias=False))\ncnn.add(BatchNormalization())\ncnn.add(Activation('relu'))\n\ncnn.add(Flatten())\n    \ncnn.add(Dense(units=10))\ncnn.add(BatchNormalization())\ncnn.add(Activation('softmax'))\n\ncnn.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2022-05-05T04:55:42.801580Z","iopub.execute_input":"2022-05-05T04:55:42.801929Z","iopub.status.idle":"2022-05-05T04:55:45.721819Z","shell.execute_reply.started":"2022-05-05T04:55:42.801864Z","shell.execute_reply":"2022-05-05T04:55:45.719532Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_datagen = ImageDataGenerator(featurewise_center=False,\n                             samplewise_center=False,\n                             featurewise_std_normalization=False,\n                             samplewise_std_normalization=False,\n                             zca_whitening=False,\n                             rotation_range=10,\n                             zoom_range=0.1,\n                             width_shift_range=0.1,\n                             height_shift_range=0.1,\n                             horizontal_flip=False,\n                             vertical_flip=False\n                            )\n\ntrain_generator = train_datagen.flow(X_train, y_train,\n                                     batch_size=120,\n                                     shuffle=True)\n\nval_datagen = ImageDataGenerator()\nval_generator = val_datagen.flow(X_val, y_val,\n                                 batch_size=120,\n                                 shuffle=True)","metadata":{"execution":{"iopub.status.busy":"2022-05-05T04:55:45.723704Z","iopub.execute_input":"2022-05-05T04:55:45.724032Z","iopub.status.idle":"2022-05-05T04:55:46.111065Z","shell.execute_reply.started":"2022-05-05T04:55:45.723986Z","shell.execute_reply":"2022-05-05T04:55:46.110144Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"reduceLROnPlateau = ReduceLROnPlateau(monitor='val_acc', \n                                patience=3,\n                                verbose=1, \n                                factor=0.1,\n                                min_lr=0.00001)","metadata":{"execution":{"iopub.status.busy":"2022-05-05T04:55:46.115352Z","iopub.execute_input":"2022-05-05T04:55:46.115595Z","iopub.status.idle":"2022-05-05T04:55:46.120401Z","shell.execute_reply.started":"2022-05-05T04:55:46.115562Z","shell.execute_reply":"2022-05-05T04:55:46.119532Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cnn.summary()\n\ntf.keras.utils.plot_model(cnn)","metadata":{"execution":{"iopub.status.busy":"2022-05-05T04:55:46.121374Z","iopub.execute_input":"2022-05-05T04:55:46.121677Z","iopub.status.idle":"2022-05-05T04:55:47.053615Z","shell.execute_reply.started":"2022-05-05T04:55:46.121630Z","shell.execute_reply":"2022-05-05T04:55:47.052542Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cnn.fit(train_generator, epochs=150, callbacks=[reduceLROnPlateau], validation_data=val_generator)","metadata":{"execution":{"iopub.status.busy":"2022-05-05T04:55:47.055749Z","iopub.execute_input":"2022-05-05T04:55:47.056234Z","iopub.status.idle":"2022-05-05T05:27:54.531820Z","shell.execute_reply.started":"2022-05-05T04:55:47.056168Z","shell.execute_reply":"2022-05-05T05:27:54.530830Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"prediction_vectors=cnn.predict(X_test)\n\npredictions_final=np.argmax(prediction_vectors, axis=1)","metadata":{"execution":{"iopub.status.busy":"2022-05-05T05:27:54.533543Z","iopub.execute_input":"2022-05-05T05:27:54.533999Z","iopub.status.idle":"2022-05-05T05:27:56.451533Z","shell.execute_reply.started":"2022-05-05T05:27:54.533936Z","shell.execute_reply":"2022-05-05T05:27:56.450517Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub = pd.read_csv('/kaggle/input/digit-recognizer/sample_submission.csv')\n\nsub[\"Label\"] = predictions_final\n\nsub.to_csv('submission.csv',index=False)","metadata":{"execution":{"iopub.status.busy":"2022-05-05T05:27:56.453242Z","iopub.execute_input":"2022-05-05T05:27:56.453539Z","iopub.status.idle":"2022-05-05T05:27:56.546171Z","shell.execute_reply.started":"2022-05-05T05:27:56.453486Z","shell.execute_reply":"2022-05-05T05:27:56.544082Z"},"trusted":true},"execution_count":null,"outputs":[]}]}