{"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-03-23T05:27:22.741470Z","iopub.execute_input":"2022-03-23T05:27:22.743283Z","iopub.status.idle":"2022-03-23T05:27:22.759035Z","shell.execute_reply.started":"2022-03-23T05:27:22.743201Z","shell.execute_reply":"2022-03-23T05:27:22.758082Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Import all required libraries**\n=","metadata":{}},{"cell_type":"code","source":"from keras.models import Sequential\nfrom keras.layers import Lambda, Dense, Flatten, Dropout\n\nimport matplotlib.pyplot as plt","metadata":{"execution":{"iopub.status.busy":"2022-03-23T05:27:22.760861Z","iopub.execute_input":"2022-03-23T05:27:22.761261Z","iopub.status.idle":"2022-03-23T05:27:22.770106Z","shell.execute_reply.started":"2022-03-23T05:27:22.761227Z","shell.execute_reply":"2022-03-23T05:27:22.769302Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%config Completer.use_jedi = False","metadata":{"execution":{"iopub.status.busy":"2022-03-23T05:27:22.771545Z","iopub.execute_input":"2022-03-23T05:27:22.771887Z","iopub.status.idle":"2022-03-23T05:27:22.798968Z","shell.execute_reply.started":"2022-03-23T05:27:22.771851Z","shell.execute_reply":"2022-03-23T05:27:22.797900Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Load the data**\n=","metadata":{}},{"cell_type":"code","source":"train = pd.read_csv(\"/kaggle/input/digit-recognizer/train.csv\")\nprint(train.shape)\ntrain.head()","metadata":{"execution":{"iopub.status.busy":"2022-03-23T05:27:22.801014Z","iopub.execute_input":"2022-03-23T05:27:22.801630Z","iopub.status.idle":"2022-03-23T05:27:25.990496Z","shell.execute_reply.started":"2022-03-23T05:27:22.801581Z","shell.execute_reply":"2022-03-23T05:27:25.989604Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test = pd.read_csv(\"/kaggle/input/digit-recognizer/test.csv\")\nprint(test.shape)\ntest.head()","metadata":{"execution":{"iopub.status.busy":"2022-03-23T05:27:25.992738Z","iopub.execute_input":"2022-03-23T05:27:25.992970Z","iopub.status.idle":"2022-03-23T05:27:27.702051Z","shell.execute_reply.started":"2022-03-23T05:27:25.992941Z","shell.execute_reply":"2022-03-23T05:27:27.701041Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train = train.iloc[:,1:].values\ny_train = train.iloc[:,0].values\nx_test = test.values","metadata":{"execution":{"iopub.status.busy":"2022-03-23T05:27:27.703137Z","iopub.execute_input":"2022-03-23T05:27:27.703363Z","iopub.status.idle":"2022-03-23T05:27:27.710096Z","shell.execute_reply.started":"2022-03-23T05:27:27.703318Z","shell.execute_reply":"2022-03-23T05:27:27.708989Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train","metadata":{"execution":{"iopub.status.busy":"2022-03-23T05:27:27.711743Z","iopub.execute_input":"2022-03-23T05:27:27.711995Z","iopub.status.idle":"2022-03-23T05:27:27.732754Z","shell.execute_reply.started":"2022-03-23T05:27:27.711965Z","shell.execute_reply":"2022-03-23T05:27:27.732065Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_train","metadata":{"execution":{"iopub.status.busy":"2022-03-23T05:27:27.733582Z","iopub.execute_input":"2022-03-23T05:27:27.733781Z","iopub.status.idle":"2022-03-23T05:27:27.745932Z","shell.execute_reply.started":"2022-03-23T05:27:27.733756Z","shell.execute_reply":"2022-03-23T05:27:27.745347Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Data visualisation**\n=","metadata":{}},{"cell_type":"code","source":"x_train = x_train.reshape(x_train.shape[0], 28, 28)\nprint(x_train.shape)\nfor i in range(0, 3):\n    plt.subplot(1,3, i + 1)\n    plt.imshow(x_train[i], cmap = 'gray')\n    plt.title(y_train[i])","metadata":{"execution":{"iopub.status.busy":"2022-03-23T05:27:27.747264Z","iopub.execute_input":"2022-03-23T05:27:27.747678Z","iopub.status.idle":"2022-03-23T05:27:28.122497Z","shell.execute_reply.started":"2022-03-23T05:27:27.747648Z","shell.execute_reply":"2022-03-23T05:27:28.120624Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)\nx_train.shape","metadata":{"execution":{"iopub.status.busy":"2022-03-23T05:27:28.123668Z","iopub.execute_input":"2022-03-23T05:27:28.123880Z","iopub.status.idle":"2022-03-23T05:27:28.131760Z","shell.execute_reply.started":"2022-03-23T05:27:28.123854Z","shell.execute_reply":"2022-03-23T05:27:28.130836Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_test = x_test.reshape(x_test.shape[0], 28, 28, 1)\nx_test.shape","metadata":{"execution":{"iopub.status.busy":"2022-03-23T05:27:28.132923Z","iopub.execute_input":"2022-03-23T05:27:28.133154Z","iopub.status.idle":"2022-03-23T05:27:28.145814Z","shell.execute_reply.started":"2022-03-23T05:27:28.133124Z","shell.execute_reply":"2022-03-23T05:27:28.145192Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Preprocessing the image data**\n=","metadata":{}},{"cell_type":"markdown","source":"**Feature Standardisation**\n-","metadata":{}},{"cell_type":"code","source":"mean_px = x_train.mean()\nstd_px = x_train.std()\n\ndef standardise(x):\n    return (x - mean_px)/std_px","metadata":{"execution":{"iopub.status.busy":"2022-03-23T05:27:28.146939Z","iopub.execute_input":"2022-03-23T05:27:28.147154Z","iopub.status.idle":"2022-03-23T05:27:28.402179Z","shell.execute_reply.started":"2022-03-23T05:27:28.147114Z","shell.execute_reply":"2022-03-23T05:27:28.401227Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**One-hot encoding**\n-","metadata":{}},{"cell_type":"code","source":"from keras.utils.np_utils import to_categorical\ny_train = to_categorical(y_train)\nnum_classes = y_train.shape[1]\nnum_classes","metadata":{"execution":{"iopub.status.busy":"2022-03-23T05:27:28.403624Z","iopub.execute_input":"2022-03-23T05:27:28.403870Z","iopub.status.idle":"2022-03-23T05:27:28.411814Z","shell.execute_reply.started":"2022-03-23T05:27:28.403839Z","shell.execute_reply":"2022-03-23T05:27:28.410475Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#plt.title(y_train[9])\n#plt.plot(y_train[9])\n#plt.xticks(range(10));","metadata":{"execution":{"iopub.status.busy":"2022-03-23T06:19:37.340279Z","iopub.execute_input":"2022-03-23T06:19:37.340701Z","iopub.status.idle":"2022-03-23T06:19:37.344906Z","shell.execute_reply.started":"2022-03-23T06:19:37.340663Z","shell.execute_reply":"2022-03-23T06:19:37.343725Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Designing Neural Network Architecture**\n=","metadata":{}},{"cell_type":"code","source":"#fix random seed\nnp.random.seed(43)","metadata":{"execution":{"iopub.status.busy":"2022-03-23T05:27:28.642305Z","iopub.execute_input":"2022-03-23T05:27:28.642902Z","iopub.status.idle":"2022-03-23T05:27:28.648505Z","shell.execute_reply.started":"2022-03-23T05:27:28.642853Z","shell.execute_reply":"2022-03-23T05:27:28.647025Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"*Linear Model*\n-","metadata":{}},{"cell_type":"code","source":"model = Sequential()\nmodel.add(Lambda(standardise, input_shape = (28,28,1)))\nmodel.add(Flatten())\nmodel.add(Dense(10, activation = 'softmax'))\nprint(\"model input shape\", model.input_shape)\nprint(\"model output shape\", model.output_shape)","metadata":{"execution":{"iopub.status.busy":"2022-03-23T05:27:28.649807Z","iopub.execute_input":"2022-03-23T05:27:28.650026Z","iopub.status.idle":"2022-03-23T05:27:28.694121Z","shell.execute_reply.started":"2022-03-23T05:27:28.649999Z","shell.execute_reply":"2022-03-23T05:27:28.693122Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"*Compile Network*\n-","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.optimizers import RMSprop\nmodel.compile(optimizer=RMSprop(learning_rate=0.001), \n              loss='categorical_crossentropy',\n              metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2022-03-23T06:19:21.770035Z","iopub.execute_input":"2022-03-23T06:19:21.770439Z","iopub.status.idle":"2022-03-23T06:19:21.785372Z","shell.execute_reply.started":"2022-03-23T06:19:21.770402Z","shell.execute_reply":"2022-03-23T06:19:21.784311Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.preprocessing import image\ngen = image.ImageDataGenerator()","metadata":{"execution":{"iopub.status.busy":"2022-03-23T05:27:28.710998Z","iopub.execute_input":"2022-03-23T05:27:28.711381Z","iopub.status.idle":"2022-03-23T05:27:28.718456Z","shell.execute_reply.started":"2022-03-23T05:27:28.711310Z","shell.execute_reply":"2022-03-23T05:27:28.717483Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nx = x_train\ny = y_train\nx_train, x_val, y_train, y_val = train_test_split(x_train, y_train, test_size=0.10, random_state=42)\n#batches = gen.flow(x_train, y_train, batch_size = 64)\n#val_batches = gen.flow(x_val, y_val, batch_size = 64)\nprint(x_train.shape, x_test.shape, y_val.shape, y_val.shape)\n","metadata":{"execution":{"iopub.status.busy":"2022-03-23T05:27:28.719522Z","iopub.execute_input":"2022-03-23T05:27:28.720165Z","iopub.status.idle":"2022-03-23T05:27:29.196007Z","shell.execute_reply.started":"2022-03-23T05:27:28.720123Z","shell.execute_reply":"2022-03-23T05:27:29.195097Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2022-03-23T05:27:29.197146Z","iopub.execute_input":"2022-03-23T05:27:29.197403Z","iopub.status.idle":"2022-03-23T05:27:29.205224Z","shell.execute_reply.started":"2022-03-23T05:27:29.197371Z","shell.execute_reply":"2022-03-23T05:27:29.204209Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nhistory = model.fit(x_train, y_train, epochs=3,validation_split=0.1)","metadata":{"execution":{"iopub.status.busy":"2022-03-23T05:27:29.206868Z","iopub.execute_input":"2022-03-23T05:27:29.207166Z","iopub.status.idle":"2022-03-23T05:27:36.697981Z","shell.execute_reply.started":"2022-03-23T05:27:29.207136Z","shell.execute_reply":"2022-03-23T05:27:36.697236Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history_dict = history.history\nhistory_dict.keys()","metadata":{"execution":{"iopub.status.busy":"2022-03-23T05:27:36.699420Z","iopub.execute_input":"2022-03-23T05:27:36.700461Z","iopub.status.idle":"2022-03-23T05:27:36.706864Z","shell.execute_reply.started":"2022-03-23T05:27:36.700420Z","shell.execute_reply":"2022-03-23T05:27:36.706181Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\nloss_values = history_dict['loss']\nval_loss_values = history_dict['val_loss']\nepochs = range(1, len(loss_values)+1)\nplt.plot(epochs,loss_values)\nplt.plot(epochs,val_loss_values,'r-')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-03-23T05:27:36.708248Z","iopub.execute_input":"2022-03-23T05:27:36.708741Z","iopub.status.idle":"2022-03-23T05:27:36.871285Z","shell.execute_reply.started":"2022-03-23T05:27:36.708701Z","shell.execute_reply":"2022-03-23T05:27:36.870419Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"acc_values = history_dict['accuracy']\nval_acc_values = history_dict['val_accuracy']\nepochs = range(1, len(loss_values)+1)\nplt.plot(epochs,acc_values)\nplt.plot(epochs,val_acc_values,'r-')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-03-23T05:27:36.872869Z","iopub.execute_input":"2022-03-23T05:27:36.873390Z","iopub.status.idle":"2022-03-23T05:27:37.065417Z","shell.execute_reply.started":"2022-03-23T05:27:36.873320Z","shell.execute_reply":"2022-03-23T05:27:37.064496Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_fc_model():\n    model = Sequential([\n        Lambda(standardise, input_shape=(28,28,1)),\n        Flatten(),\n        Dense(512, activation='relu'),\n        Dense(10, activation='softmax')      \n        ])\n        \n    model.compile(optimizer='Adam', loss='categorical_crossentropy', metrics=['accuracy'])\n    \n    return model","metadata":{"execution":{"iopub.status.busy":"2022-03-23T05:27:37.067108Z","iopub.execute_input":"2022-03-23T05:27:37.067441Z","iopub.status.idle":"2022-03-23T05:27:37.073503Z","shell.execute_reply.started":"2022-03-23T05:27:37.067397Z","shell.execute_reply":"2022-03-23T05:27:37.072657Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fc = get_fc_model()\nfc.optimizer.lr = 0.001","metadata":{"execution":{"iopub.status.busy":"2022-03-23T05:29:10.478710Z","iopub.execute_input":"2022-03-23T05:29:10.479558Z","iopub.status.idle":"2022-03-23T05:29:10.519438Z","shell.execute_reply.started":"2022-03-23T05:29:10.479516Z","shell.execute_reply":"2022-03-23T05:29:10.518246Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fc.summary()","metadata":{"execution":{"iopub.status.busy":"2022-03-23T05:27:37.124619Z","iopub.execute_input":"2022-03-23T05:27:37.124920Z","iopub.status.idle":"2022-03-23T05:27:37.132022Z","shell.execute_reply.started":"2022-03-23T05:27:37.124888Z","shell.execute_reply":"2022-03-23T05:27:37.131377Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history2 = fc.fit(x_train, y_train, epochs=3,validation_split=0.1)","metadata":{"execution":{"iopub.status.busy":"2022-03-23T05:29:13.453813Z","iopub.execute_input":"2022-03-23T05:29:13.454206Z","iopub.status.idle":"2022-03-23T05:29:26.174575Z","shell.execute_reply.started":"2022-03-23T05:29:13.454152Z","shell.execute_reply":"2022-03-23T05:29:26.173624Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"*Convolutional NN*\n-","metadata":{}},{"cell_type":"code","source":"from keras.layers import Convolution2D, MaxPooling2D\nfrom tensorflow.keras.optimizers import Adam\nmodel3 = Sequential([\n        Lambda(standardise, input_shape=(28,28,1)),\n        Convolution2D(32,(3,3), activation='relu'),\n        Convolution2D(32,(3,3), activation='relu'),\n        MaxPooling2D(),\n        Convolution2D(64,(3,3), activation='relu'),\n        Convolution2D(64,(3,3), activation='relu'),\n        MaxPooling2D(),\n        Flatten(),\n        Dense(512, activation='relu'),\n        Dense(10, activation='softmax')\n        ])\n\nmodel3.compile(Adam(), loss='categorical_crossentropy',\n              metrics=['accuracy'])\nmodel3.optimizer.lr = 0.01\n        ","metadata":{"execution":{"iopub.status.busy":"2022-03-23T05:29:59.275892Z","iopub.execute_input":"2022-03-23T05:29:59.276242Z","iopub.status.idle":"2022-03-23T05:29:59.388367Z","shell.execute_reply.started":"2022-03-23T05:29:59.276204Z","shell.execute_reply":"2022-03-23T05:29:59.387550Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model3.summary()","metadata":{"execution":{"iopub.status.busy":"2022-03-23T05:30:24.388516Z","iopub.execute_input":"2022-03-23T05:30:24.388916Z","iopub.status.idle":"2022-03-23T05:30:24.400533Z","shell.execute_reply.started":"2022-03-23T05:30:24.388865Z","shell.execute_reply":"2022-03-23T05:30:24.399327Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history3 = model3.fit(x_train, y_train, epochs=3,validation_split=0.1)","metadata":{"execution":{"iopub.status.busy":"2022-03-23T05:30:47.663494Z","iopub.execute_input":"2022-03-23T05:30:47.663829Z","iopub.status.idle":"2022-03-23T05:32:30.055105Z","shell.execute_reply.started":"2022-03-23T05:30:47.663794Z","shell.execute_reply":"2022-03-23T05:32:30.054205Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.layers import BatchNormalization\n\nmodel4 = Sequential([\n        Lambda(standardise, input_shape=(28,28,1)),\n        Convolution2D(32,(3,3), activation='relu'),\n        BatchNormalization(axis=1),\n        Convolution2D(32,(3,3), activation='relu'),\n        MaxPooling2D(),\n        BatchNormalization(axis=1),\n        Convolution2D(64,(3,3), activation='relu'),\n        BatchNormalization(axis=1),\n        Convolution2D(64,(3,3), activation='relu'),\n        MaxPooling2D(),\n        Flatten(),\n        BatchNormalization(),\n        Dense(512, activation='relu'),\n        BatchNormalization(),\n        Dense(10, activation='softmax')\n        ])\n    \nmodel4.compile(Adam(), loss='categorical_crossentropy', metrics=['accuracy'])\nmodel4.optimizer.lr = 0.01\n","metadata":{"execution":{"iopub.status.busy":"2022-03-23T05:57:41.763922Z","iopub.execute_input":"2022-03-23T05:57:41.764253Z","iopub.status.idle":"2022-03-23T05:57:41.919274Z","shell.execute_reply.started":"2022-03-23T05:57:41.764217Z","shell.execute_reply":"2022-03-23T05:57:41.918395Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model4.summary()","metadata":{"execution":{"iopub.status.busy":"2022-03-23T05:59:40.370978Z","iopub.execute_input":"2022-03-23T05:59:40.371371Z","iopub.status.idle":"2022-03-23T05:59:40.384519Z","shell.execute_reply.started":"2022-03-23T05:59:40.371318Z","shell.execute_reply":"2022-03-23T05:59:40.383625Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history4 = model3.fit(x_train, y_train, epochs=3,validation_split=0.1)","metadata":{"execution":{"iopub.status.busy":"2022-03-23T05:57:59.246577Z","iopub.execute_input":"2022-03-23T05:57:59.246938Z","iopub.status.idle":"2022-03-23T05:59:40.369321Z","shell.execute_reply.started":"2022-03-23T05:57:59.246898Z","shell.execute_reply":"2022-03-23T05:59:40.368627Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"*Submitting the predections*\n-","metadata":{}},{"cell_type":"code","source":"\npredict_x=model.predict(x_test,verbose=1) \nclasses_x=np.argmax(predict_x,axis=1)\n\nsubmissions=pd.DataFrame({\"ImageId\": list(range(1,len(classes_x)+1)),\n                         \"Label\": classes_x})\nsubmissions.to_csv(\"submission.csv\", index=False, header=True)","metadata":{"execution":{"iopub.status.busy":"2022-03-23T06:11:19.534270Z","iopub.execute_input":"2022-03-23T06:11:19.534687Z","iopub.status.idle":"2022-03-23T06:11:21.049386Z","shell.execute_reply.started":"2022-03-23T06:11:19.534650Z","shell.execute_reply":"2022-03-23T06:11:21.048178Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}