{"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":"2023-03-11T09:25:16.556626Z","iopub.execute_input":"2023-03-11T09:25:16.557348Z","iopub.status.idle":"2023-03-11T09:25:16.566533Z","shell.execute_reply.started":"2023-03-11T09:25:16.557311Z","shell.execute_reply":"2023-03-11T09:25:16.565146Z"},"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')\ny_train=train['label']\nX_train=train.drop('label',axis=1)\n","metadata":{"execution":{"iopub.status.busy":"2023-03-11T09:25:16.572536Z","iopub.execute_input":"2023-03-11T09:25:16.573432Z","iopub.status.idle":"2023-03-11T09:25:20.768165Z","shell.execute_reply.started":"2023-03-11T09:25:16.573387Z","shell.execute_reply":"2023-03-11T09:25:20.766903Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train.iloc[0].shape\n#This will be reshaped to (28,28,1) in order to apply a CNN ","metadata":{"execution":{"iopub.status.busy":"2023-03-11T09:25:20.770373Z","iopub.execute_input":"2023-03-11T09:25:20.770854Z","iopub.status.idle":"2023-03-11T09:25:20.780007Z","shell.execute_reply.started":"2023-03-11T09:25:20.770815Z","shell.execute_reply":"2023-03-11T09:25:20.778844Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nplt.imshow(np.array(X_train.iloc[17]).reshape(28,28))","metadata":{"execution":{"iopub.status.busy":"2023-03-11T09:25:20.781368Z","iopub.execute_input":"2023-03-11T09:25:20.781976Z","iopub.status.idle":"2023-03-11T09:25:20.994455Z","shell.execute_reply.started":"2023-03-11T09:25:20.781937Z","shell.execute_reply":"2023-03-11T09:25:20.993492Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train.max().max()\n#I will normalize the values to be between 0 and 255\nX_train/=255\ntest/=255","metadata":{"execution":{"iopub.status.busy":"2023-03-11T09:25:20.996923Z","iopub.execute_input":"2023-03-11T09:25:20.997195Z","iopub.status.idle":"2023-03-11T09:25:21.222334Z","shell.execute_reply.started":"2023-03-11T09:25:20.997169Z","shell.execute_reply":"2023-03-11T09:25:21.221270Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train=X_train.values.reshape(-1,28,28,1)\ntest=test.values.reshape(-1,28,28,1)","metadata":{"execution":{"iopub.status.busy":"2023-03-11T09:25:21.223841Z","iopub.execute_input":"2023-03-11T09:25:21.224217Z","iopub.status.idle":"2023-03-11T09:25:21.229913Z","shell.execute_reply.started":"2023-03-11T09:25:21.224178Z","shell.execute_reply":"2023-03-11T09:25:21.228599Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\ny_cat_train=tf.keras.utils.to_categorical(y_train,num_classes=10)","metadata":{"execution":{"iopub.status.busy":"2023-03-11T09:25:21.232025Z","iopub.execute_input":"2023-03-11T09:25:21.232814Z","iopub.status.idle":"2023-03-11T09:25:21.240432Z","shell.execute_reply.started":"2023-03-11T09:25:21.232767Z","shell.execute_reply":"2023-03-11T09:25:21.239388Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nrandom_seed=42\nX_train,X_val,y_cat_train,y_cat_val=train=train_test_split(X_train,y_cat_train, test_size=0.2,random_state=random_seed)","metadata":{"execution":{"iopub.status.busy":"2023-03-11T09:25:21.242273Z","iopub.execute_input":"2023-03-11T09:25:21.243228Z","iopub.status.idle":"2023-03-11T09:25:21.634028Z","shell.execute_reply.started":"2023-03-11T09:25:21.243199Z","shell.execute_reply":"2023-03-11T09:25:21.632850Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D,MaxPool2D,Flatten,Dense\n\n\nmodel=Sequential()\nmodel.add(Conv2D(filters=32,kernel_size=(4,4),input_shape=(28,28,1),padding='same',activation='relu'))\nmodel.add(MaxPool2D(pool_size=(2, 2)))\nmodel.add(Flatten())\nmodel.add(Dense(128,activation='relu'))\nmodel.add(Dense(10,activation='softmax'))\nmodel.compile(loss='categorical_crossentropy',\n             optimizer='adam',\n             metrics=['accuracy'])\n","metadata":{"execution":{"iopub.status.busy":"2023-03-11T09:25:21.635843Z","iopub.execute_input":"2023-03-11T09:25:21.636256Z","iopub.status.idle":"2023-03-11T09:25:21.694775Z","shell.execute_reply.started":"2023-03-11T09:25:21.636212Z","shell.execute_reply":"2023-03-11T09:25:21.693706Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Adding early stopping to prevent overfitting\nfrom tensorflow.keras.callbacks import EarlyStopping\nearly_stop = EarlyStopping(monitor='val_loss',patience=2)\n","metadata":{"execution":{"iopub.status.busy":"2023-03-11T09:25:21.696604Z","iopub.execute_input":"2023-03-11T09:25:21.697003Z","iopub.status.idle":"2023-03-11T09:25:21.703029Z","shell.execute_reply.started":"2023-03-11T09:25:21.696955Z","shell.execute_reply":"2023-03-11T09:25:21.701841Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.fit(X_train,y_cat_train,epochs=10,validation_data=(X_val,y_cat_val),callbacks=[early_stop])","metadata":{"execution":{"iopub.status.busy":"2023-03-11T09:25:21.707573Z","iopub.execute_input":"2023-03-11T09:25:21.708353Z","iopub.status.idle":"2023-03-11T09:25:55.009472Z","shell.execute_reply.started":"2023-03-11T09:25:21.708321Z","shell.execute_reply":"2023-03-11T09:25:55.008715Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history=pd.DataFrame(model.history.history)","metadata":{"execution":{"iopub.status.busy":"2023-03-11T09:25:55.010927Z","iopub.execute_input":"2023-03-11T09:25:55.011559Z","iopub.status.idle":"2023-03-11T09:25:55.017042Z","shell.execute_reply.started":"2023-03-11T09:25:55.011521Z","shell.execute_reply":"2023-03-11T09:25:55.016292Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history[['loss','val_loss']].plot()","metadata":{"execution":{"iopub.status.busy":"2023-03-11T09:25:55.018552Z","iopub.execute_input":"2023-03-11T09:25:55.019293Z","iopub.status.idle":"2023-03-11T09:25:55.274605Z","shell.execute_reply.started":"2023-03-11T09:25:55.019255Z","shell.execute_reply":"2023-03-11T09:25:55.273620Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history[['accuracy','val_accuracy']].plot()\n#Why the model stopped at only 7 epochs: The validation set performance was beginning to suffer","metadata":{"execution":{"iopub.status.busy":"2023-03-11T09:25:55.276205Z","iopub.execute_input":"2023-03-11T09:25:55.276598Z","iopub.status.idle":"2023-03-11T09:25:55.505565Z","shell.execute_reply.started":"2023-03-11T09:25:55.276560Z","shell.execute_reply":"2023-03-11T09:25:55.504577Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions=model.predict(test)\n","metadata":{"execution":{"iopub.status.busy":"2023-03-11T09:25:55.507098Z","iopub.execute_input":"2023-03-11T09:25:55.508162Z","iopub.status.idle":"2023-03-11T09:25:57.500353Z","shell.execute_reply.started":"2023-03-11T09:25:55.508124Z","shell.execute_reply":"2023-03-11T09:25:57.499335Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions=np.argmax(predictions,axis=1)","metadata":{"execution":{"iopub.status.busy":"2023-03-11T09:25:57.502121Z","iopub.execute_input":"2023-03-11T09:25:57.502489Z","iopub.status.idle":"2023-03-11T09:25:57.509333Z","shell.execute_reply.started":"2023-03-11T09:25:57.502452Z","shell.execute_reply":"2023-03-11T09:25:57.507640Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions=pd.Series(predictions,name=\"Label\")\nsubmission = pd.concat([pd.Series(range(1,28001),name = \"ImageId\"),predictions],axis = 1)\n\nsubmission.to_csv(\"submission.csv\",index=False)","metadata":{"execution":{"iopub.status.busy":"2023-03-11T09:25:57.510477Z","iopub.execute_input":"2023-03-11T09:25:57.511049Z","iopub.status.idle":"2023-03-11T09:25:57.545017Z","shell.execute_reply.started":"2023-03-11T09:25:57.510991Z","shell.execute_reply":"2023-03-11T09:25:57.544143Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#To get better performance, more data might be needed. Luckily, the digits will maintain the same class \n#if we rotate, shear or scale an image (to a reasonable extent), so we can get more data by applying these\n#transformations to the original set\nfrom keras.preprocessing.image import ImageDataGenerator \ndatagen = ImageDataGenerator(rotation_range=10, # Rotating randomly the images up to 25°\n                             width_shift_range=0.05, # Moving the images from left to right\n                             height_shift_range=0.05, # Then from top to bottom\n                             shear_range=0.10, \n                             zoom_range=0.05, # Zooming randomly up to 20%\n                             zca_whitening=False,\n                             horizontal_flip=False, \n                             vertical_flip=False,\n                            fill_mode = 'nearest')\ndatagen.fit(X_train)","metadata":{"execution":{"iopub.status.busy":"2023-03-11T09:54:07.269324Z","iopub.execute_input":"2023-03-11T09:54:07.269719Z","iopub.status.idle":"2023-03-11T09:54:07.356497Z","shell.execute_reply.started":"2023-03-11T09:54:07.269682Z","shell.execute_reply":"2023-03-11T09:54:07.355466Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.fit(datagen.flow(X_train,y_cat_train, batch_size=32),\n                              epochs = 20, \n                              validation_data = (X_val,y_cat_val),\n                              verbose = 2,\n                              callbacks=[early_stop])","metadata":{"execution":{"iopub.status.busy":"2023-03-11T10:00:56.902209Z","iopub.execute_input":"2023-03-11T10:00:56.902812Z","iopub.status.idle":"2023-03-11T10:02:20.926368Z","shell.execute_reply.started":"2023-03-11T10:00:56.902774Z","shell.execute_reply":"2023-03-11T10:02:20.925414Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#The accuracy has improved. I'll also try tweaking the network architecture a little to see if I can \n#squeeze a bit more out of the model\nfrom tensorflow.keras.layers import Dropout\n\nmodel=Sequential()\n\nmodel.add(Conv2D(filters=32,kernel_size=(4,4),input_shape=(28,28,1),padding='same',activation='relu'))\nmodel.add(MaxPool2D(pool_size=(2, 2)))\n\nmodel.add(Conv2D(filters=64,kernel_size=(4,4),padding='same',activation='relu'))\nmodel.add(MaxPool2D(pool_size=(2, 2)))\n\nmodel.add(Flatten())\nmodel.add(Dense(128,activation='relu'))\nmodel.add(Dropout(0.5))\n\nmodel.add(Dense(10,activation='softmax'))\n\nmodel.compile(loss='categorical_crossentropy',\n             optimizer='adam',\n             metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2023-03-11T10:07:44.827689Z","iopub.execute_input":"2023-03-11T10:07:44.828400Z","iopub.status.idle":"2023-03-11T10:07:44.900711Z","shell.execute_reply.started":"2023-03-11T10:07:44.828360Z","shell.execute_reply":"2023-03-11T10:07:44.899714Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.fit(datagen.flow(X_train,y_cat_train, batch_size=32),\n                              epochs = 20, \n                              validation_data = (X_val,y_cat_val),\n                              verbose = 2,\n                              callbacks=[early_stop])\n","metadata":{"execution":{"iopub.status.busy":"2023-03-11T10:07:47.067500Z","iopub.execute_input":"2023-03-11T10:07:47.068454Z","iopub.status.idle":"2023-03-11T10:10:14.726551Z","shell.execute_reply.started":"2023-03-11T10:07:47.068398Z","shell.execute_reply":"2023-03-11T10:10:14.725410Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history=pd.DataFrame(model.history.history)\nhistory[['accuracy','val_accuracy']].plot()\nhistory[['loss','val_loss']].plot()\n","metadata":{"execution":{"iopub.status.busy":"2023-03-11T10:10:58.099180Z","iopub.execute_input":"2023-03-11T10:10:58.099549Z","iopub.status.idle":"2023-03-11T10:10:58.511923Z","shell.execute_reply.started":"2023-03-11T10:10:58.099509Z","shell.execute_reply":"2023-03-11T10:10:58.510977Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Adding a dropout layer seems to have prevented overfitting to some extent: The model trained for more \n#epochs before stopping. \npredictions=np.argmax(model.predict(test),axis=1)\npredictions=pd.Series(predictions,name=\"Label\")\nsubmission = pd.concat([pd.Series(range(1,28001),name = \"ImageId\"),predictions],axis = 1)\n\nsubmission.to_csv(\"submission2.csv\",index=False)","metadata":{"execution":{"iopub.status.busy":"2023-03-11T10:12:49.567172Z","iopub.execute_input":"2023-03-11T10:12:49.567806Z","iopub.status.idle":"2023-03-11T10:12:51.707063Z","shell.execute_reply.started":"2023-03-11T10:12:49.567767Z","shell.execute_reply":"2023-03-11T10:12:51.706023Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}