{"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 sklearn.model_selection import train_test_split, GridSearchCV, cross_val_score\nfrom sklearn.metrics import classification_report\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, SGD, Adam,TFOptimizer\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import ReduceLROnPlateau\nfrom keras.wrappers.scikit_learn import KerasClassifier\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-10-28T05:58:52.275439Z","iopub.execute_input":"2023-10-28T05:58:52.275794Z","iopub.status.idle":"2023-10-28T05:59:03.688651Z","shell.execute_reply.started":"2023-10-28T05:58:52.275764Z","shell.execute_reply":"2023-10-28T05:59:03.687756Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = pd.read_csv(\"/kaggle/input/digit-recognizer/train.csv\")\ntest = pd.read_csv(\"/kaggle/input/digit-recognizer/test.csv\")","metadata":{"execution":{"iopub.status.busy":"2023-10-28T05:59:03.690685Z","iopub.execute_input":"2023-10-28T05:59:03.691366Z","iopub.status.idle":"2023-10-28T05:59:07.804551Z","shell.execute_reply.started":"2023-10-28T05:59:03.691332Z","shell.execute_reply":"2023-10-28T05:59:07.802795Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"target = train[\"label\"]\nfeatures = train.drop(labels = [\"label\"],axis = 1) ","metadata":{"execution":{"iopub.status.busy":"2023-10-28T05:59:07.806071Z","iopub.execute_input":"2023-10-28T05:59:07.806465Z","iopub.status.idle":"2023-10-28T05:59:07.884928Z","shell.execute_reply.started":"2023-10-28T05:59:07.806434Z","shell.execute_reply":"2023-10-28T05:59:07.882900Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"features = features / 255.0\ntest = test / 255.0","metadata":{"execution":{"iopub.status.busy":"2023-10-28T05:59:07.886051Z","iopub.execute_input":"2023-10-28T05:59:07.886453Z","iopub.status.idle":"2023-10-28T05:59:07.964701Z","shell.execute_reply.started":"2023-10-28T05:59:07.886355Z","shell.execute_reply":"2023-10-28T05:59:07.963728Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"features = features.values.reshape(-1,28,28,1)\ntest = test.values.reshape(-1,28,28,1)","metadata":{"execution":{"iopub.status.busy":"2023-10-28T05:59:07.967320Z","iopub.execute_input":"2023-10-28T05:59:07.967655Z","iopub.status.idle":"2023-10-28T05:59:07.973840Z","shell.execute_reply.started":"2023-10-28T05:59:07.967628Z","shell.execute_reply":"2023-10-28T05:59:07.972033Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"target = to_categorical(target, num_classes = 10)","metadata":{"execution":{"iopub.status.busy":"2023-10-28T05:59:07.974891Z","iopub.execute_input":"2023-10-28T05:59:07.975209Z","iopub.status.idle":"2023-10-28T05:59:07.989300Z","shell.execute_reply.started":"2023-10-28T05:59:07.975184Z","shell.execute_reply":"2023-10-28T05:59:07.987841Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train, X_val, Y_train, Y_val = train_test_split(features, target, test_size = 0.1)","metadata":{"execution":{"iopub.status.busy":"2023-10-28T05:59:07.990697Z","iopub.execute_input":"2023-10-28T05:59:07.991037Z","iopub.status.idle":"2023-10-28T05:59:08.228127Z","shell.execute_reply.started":"2023-10-28T05:59:07.990960Z","shell.execute_reply":"2023-10-28T05:59:08.226979Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"clf = Sequential()\nclf.add(Conv2D(filters = 64, kernel_size = (5,5),padding = 'Same', \n                     activation ='relu', input_shape = (28,28,1)))\nclf.add(Conv2D(filters = 64, kernel_size = (5,5),padding = 'Same', \n                     activation ='relu'))\nclf.add(MaxPool2D(pool_size=(2,2)))\nclf.add(Dropout(0.25))\n\nclf.add(Conv2D(filters = 128, kernel_size = (3,3),padding = 'Same', \n                     activation ='relu'))\nclf.add(Conv2D(filters = 128, kernel_size = (3,3),padding = 'Same', \n                     activation ='relu'))\nclf.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))\nclf.add(Dropout(0.3))\n\nclf.add(Flatten())\nclf.add(Dense(512, activation = \"relu\", use_bias= True))\nclf.add(Dropout(0.5))\nclf.add(Dense(10, activation = \"softmax\"))\n\nclf.compile(optimizer = 'adam' , loss = \"categorical_crossentropy\", metrics=[\"accuracy\"])","metadata":{"execution":{"iopub.status.busy":"2023-10-28T05:59:08.229403Z","iopub.execute_input":"2023-10-28T05:59:08.229675Z","iopub.status.idle":"2023-10-28T05:59:08.499608Z","shell.execute_reply.started":"2023-10-28T05:59:08.229652Z","shell.execute_reply":"2023-10-28T05:59:08.498084Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"learning_rate_reduction = ReduceLROnPlateau(monitor='val_acc', \n                                            patience=5, \n                                            verbose=1, \n                                            factor=0.5, \n                                            min_lr=0.00001)","metadata":{"execution":{"iopub.status.busy":"2023-10-28T05:59:08.500758Z","iopub.execute_input":"2023-10-28T05:59:08.501105Z","iopub.status.idle":"2023-10-28T05:59:08.506428Z","shell.execute_reply.started":"2023-10-28T05:59:08.501074Z","shell.execute_reply":"2023-10-28T05:59:08.505178Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"datagen = ImageDataGenerator(\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,  # randomly flip images\n        vertical_flip=False)  # randomly flip images\n\n\ndatagen.fit(X_train)","metadata":{"execution":{"iopub.status.busy":"2023-10-28T05:59:08.507876Z","iopub.execute_input":"2023-10-28T05:59:08.508193Z","iopub.status.idle":"2023-10-28T05:59:08.581103Z","shell.execute_reply.started":"2023-10-28T05:59:08.508164Z","shell.execute_reply":"2023-10-28T05:59:08.580111Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"clf.fit(datagen.flow(X_train,Y_train, batch_size= 82),\n                              epochs = 10, validation_data = (X_val,Y_val),\n                              verbose = 2, steps_per_epoch=50\n                              , callbacks=[learning_rate_reduction])","metadata":{"execution":{"iopub.status.busy":"2023-10-28T05:59:08.582345Z","iopub.execute_input":"2023-10-28T05:59:08.582699Z","iopub.status.idle":"2023-10-28T06:10:11.425514Z","shell.execute_reply.started":"2023-10-28T05:59:08.582671Z","shell.execute_reply":"2023-10-28T06:10:11.424374Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"results = clf.predict(test)\n\nresults = np.argmax(results,axis = 1)\n\nresults = pd.Series(results,name=\"Label\")","metadata":{"execution":{"iopub.status.busy":"2023-10-28T06:32:03.173554Z","iopub.execute_input":"2023-10-28T06:32:03.173921Z","iopub.status.idle":"2023-10-28T06:32:55.954711Z","shell.execute_reply.started":"2023-10-28T06:32:03.173894Z","shell.execute_reply":"2023-10-28T06:32:55.953338Z"},"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(\"cnnmodel.csv\",index=False)","metadata":{"execution":{"iopub.status.busy":"2023-10-28T06:32:55.956197Z","iopub.execute_input":"2023-10-28T06:32:55.956499Z","iopub.status.idle":"2023-10-28T06:32:55.991482Z","shell.execute_reply.started":"2023-10-28T06:32:55.956474Z","shell.execute_reply":"2023-10-28T06:32:55.990291Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}