{"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\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nfrom keras.models import  Sequential\nfrom keras.layers.core import  Reshape , Dense, Flatten, Dropout\nfrom keras.callbacks import EarlyStopping\nfrom keras.layers import BatchNormalization, Convolution2D , MaxPooling2D\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":"2021-11-29T13:38:00.167372Z","iopub.execute_input":"2021-11-29T13:38:00.167651Z","iopub.status.idle":"2021-11-29T13:38:00.184052Z","shell.execute_reply.started":"2021-11-29T13:38:00.167621Z","shell.execute_reply":"2021-11-29T13:38:00.183408Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = pd.read_csv(\"/kaggle/input/digit-recognizer/train.csv\")\n\nprint(train.shape)\nprint(train.info())\ntrain.head()","metadata":{"execution":{"iopub.status.busy":"2021-11-29T13:38:00.186027Z","iopub.execute_input":"2021-11-29T13:38:00.186357Z","iopub.status.idle":"2021-11-29T13:38:02.953696Z","shell.execute_reply.started":"2021-11-29T13:38:00.186313Z","shell.execute_reply":"2021-11-29T13:38:02.95257Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test = pd.read_csv(\"/kaggle/input/digit-recognizer/test.csv\")\n\nprint(test.shape)\nprint(test.info())\ntest.head()","metadata":{"execution":{"iopub.status.busy":"2021-11-29T13:38:02.95548Z","iopub.execute_input":"2021-11-29T13:38:02.955733Z","iopub.status.idle":"2021-11-29T13:38:04.573011Z","shell.execute_reply.started":"2021-11-29T13:38:02.955705Z","shell.execute_reply":"2021-11-29T13:38:04.572035Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## EDA\n\nBesides visualizing sone digits to get a feel what I work with, the main questions I have:\n* Is there any skew in the data (are all digits represented the same)?\n* Are there differences between the digits that could be grasped even before building the model?","metadata":{}},{"cell_type":"code","source":"sample_pix = train.iloc[:3, 1:].to_numpy()\nsample_lab = train.iloc[:3, 0]\nsample_pix = sample_pix.reshape((3, 28, 28))\n\nfig, axes = plt.subplots(ncols=3)\n\nfor i in range(3):\n    axes[i].imshow(sample_pix[i], cmap=plt.get_cmap(\"gray\"))\n    axes[i].title.set_text(sample_lab[i])","metadata":{"execution":{"iopub.status.busy":"2021-11-29T13:38:04.57554Z","iopub.execute_input":"2021-11-29T13:38:04.575784Z","iopub.status.idle":"2021-11-29T13:38:04.96154Z","shell.execute_reply.started":"2021-11-29T13:38:04.575754Z","shell.execute_reply":"2021-11-29T13:38:04.960584Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.label.value_counts().sort_index().plot(kind=\"bar\")","metadata":{"execution":{"iopub.status.busy":"2021-11-29T13:38:04.964181Z","iopub.execute_input":"2021-11-29T13:38:04.964519Z","iopub.status.idle":"2021-11-29T13:38:05.199533Z","shell.execute_reply.started":"2021-11-29T13:38:04.964473Z","shell.execute_reply":"2021-11-29T13:38:05.197733Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"added_pixels = pd.concat([train.label, train.iloc[:,1:].sum(axis=1)], axis=1, keys=[\"label\", \"p_sum\"])\nadded_pixels.groupby(\"label\").describe()","metadata":{"execution":{"iopub.status.busy":"2021-11-29T13:38:05.200732Z","iopub.execute_input":"2021-11-29T13:38:05.200925Z","iopub.status.idle":"2021-11-29T13:38:05.291554Z","shell.execute_reply.started":"2021-11-29T13:38:05.2009Z","shell.execute_reply":"2021-11-29T13:38:05.2907Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"added_pixels.groupby(\"label\").boxplot(subplots=False, rot=45, column=\"p_sum\", figsize=(12,10))","metadata":{"execution":{"iopub.status.busy":"2021-11-29T13:38:05.293059Z","iopub.execute_input":"2021-11-29T13:38:05.293301Z","iopub.status.idle":"2021-11-29T13:38:05.784192Z","shell.execute_reply.started":"2021-11-29T13:38:05.293273Z","shell.execute_reply":"2021-11-29T13:38:05.78322Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Is it worth adding some summary statistics of the pixels as features? The summary and the boxplot above might suggest so, but let's see what an ANOVA test tells about this.\n\nH0: The mean added pixel values for all the digits are basically the same.\n\nHA: There is at least one digit whose mean is significantly different.","metadata":{}},{"cell_type":"code","source":"import scipy.stats as stats\n\npivoted = pd.pivot_table(train, columns=\"label\")\n\nfvalue, pvalue = stats.f_oneway(pivoted[0], pivoted[1], pivoted[2], pivoted[3], pivoted[4], pivoted[5],\n                               pivoted[6], pivoted[7], pivoted[8], pivoted[9])\nprint(fvalue, pvalue)","metadata":{"execution":{"iopub.status.busy":"2021-11-29T13:38:05.785651Z","iopub.execute_input":"2021-11-29T13:38:05.785984Z","iopub.status.idle":"2021-11-29T13:38:06.632392Z","shell.execute_reply.started":"2021-11-29T13:38:05.785954Z","shell.execute_reply":"2021-11-29T13:38:06.63129Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"So the probability that all the digits have the same added mean pixel value (and the seemingly present differences in the training set are there only by chance) is very small. It looks like it's worth adding this feature to the model.","metadata":{}},{"cell_type":"markdown","source":"## Simple Sequential Model","metadata":{}},{"cell_type":"code","source":"X = train.iloc[:, 1:].values\ny = train.iloc[:, 0].values\nX_test = test.values","metadata":{"execution":{"iopub.status.busy":"2021-11-29T13:38:06.6343Z","iopub.execute_input":"2021-11-29T13:38:06.634626Z","iopub.status.idle":"2021-11-29T13:38:06.641228Z","shell.execute_reply.started":"2021-11-29T13:38:06.63458Z","shell.execute_reply":"2021-11-29T13:38:06.640085Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.utils.np_utils import to_categorical\ny = to_categorical(y)\ny.shape","metadata":{"execution":{"iopub.status.busy":"2021-11-29T13:38:06.644457Z","iopub.execute_input":"2021-11-29T13:38:06.644697Z","iopub.status.idle":"2021-11-29T13:38:06.658468Z","shell.execute_reply.started":"2021-11-29T13:38:06.64467Z","shell.execute_reply":"2021-11-29T13:38:06.657489Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n\nX_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.10, random_state=42)\n","metadata":{"execution":{"iopub.status.busy":"2021-11-29T13:38:06.659714Z","iopub.execute_input":"2021-11-29T13:38:06.660652Z","iopub.status.idle":"2021-11-29T13:38:07.098469Z","shell.execute_reply.started":"2021-11-29T13:38:06.660601Z","shell.execute_reply":"2021-11-29T13:38:07.097468Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = Sequential([\n    Dense(512, activation=\"relu\"),\n    Dense(10, activation=\"softmax\")\n])","metadata":{"execution":{"iopub.status.busy":"2021-11-29T13:38:07.099873Z","iopub.execute_input":"2021-11-29T13:38:07.100123Z","iopub.status.idle":"2021-11-29T13:38:07.110283Z","shell.execute_reply.started":"2021-11-29T13:38:07.100092Z","shell.execute_reply":"2021-11-29T13:38:07.109222Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(optimizer='Adam', loss='categorical_crossentropy',\n                  metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2021-11-29T13:38:07.112026Z","iopub.execute_input":"2021-11-29T13:38:07.112401Z","iopub.status.idle":"2021-11-29T13:38:07.126868Z","shell.execute_reply.started":"2021-11-29T13:38:07.11236Z","shell.execute_reply":"2021-11-29T13:38:07.125917Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"epochs = 10\nhistory = model.fit(x=X_train, y=y_train, batch_size=64, validation_split=0.1, epochs=epochs)","metadata":{"execution":{"iopub.status.busy":"2021-11-29T13:38:07.128318Z","iopub.execute_input":"2021-11-29T13:38:07.128957Z","iopub.status.idle":"2021-11-29T13:38:32.540413Z","shell.execute_reply.started":"2021-11-29T13:38:07.128904Z","shell.execute_reply":"2021-11-29T13:38:32.539495Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pd.DataFrame(history.history).loc[:, [\"loss\", \"val_loss\"]].plot()\nplt.xticks(range(epochs))\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"Loss\")\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2021-11-29T13:38:32.541877Z","iopub.execute_input":"2021-11-29T13:38:32.542121Z","iopub.status.idle":"2021-11-29T13:38:32.724933Z","shell.execute_reply.started":"2021-11-29T13:38:32.542091Z","shell.execute_reply":"2021-11-29T13:38:32.723916Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2021-11-29T13:38:32.726323Z","iopub.execute_input":"2021-11-29T13:38:32.726627Z","iopub.status.idle":"2021-11-29T13:38:32.734108Z","shell.execute_reply.started":"2021-11-29T13:38:32.726585Z","shell.execute_reply":"2021-11-29T13:38:32.733217Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.evaluate(x=X_val, y=y_val, batch_size=64)","metadata":{"execution":{"iopub.status.busy":"2021-11-29T13:38:32.735884Z","iopub.execute_input":"2021-11-29T13:38:32.73623Z","iopub.status.idle":"2021-11-29T13:38:32.968611Z","shell.execute_reply.started":"2021-11-29T13:38:32.736184Z","shell.execute_reply":"2021-11-29T13:38:32.967939Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Convolutional Network","metadata":{}},{"cell_type":"code","source":"X_train = X_train.astype(\"float32\")\nX_test = X_test.astype(\"float32\")","metadata":{"execution":{"iopub.status.busy":"2021-11-29T13:38:32.971334Z","iopub.execute_input":"2021-11-29T13:38:32.972105Z","iopub.status.idle":"2021-11-29T13:38:33.077979Z","shell.execute_reply.started":"2021-11-29T13:38:32.972063Z","shell.execute_reply":"2021-11-29T13:38:33.076991Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = Sequential([\n    Reshape((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])","metadata":{"execution":{"iopub.status.busy":"2021-11-29T13:38:33.079355Z","iopub.execute_input":"2021-11-29T13:38:33.080249Z","iopub.status.idle":"2021-11-29T13:38:33.100688Z","shell.execute_reply.started":"2021-11-29T13:38:33.080204Z","shell.execute_reply":"2021-11-29T13:38:33.09961Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"earlystopping = EarlyStopping(patience=3)\nepochs = 10\nmodel.compile(optimizer=\"Adam\", loss=\"categorical_crossentropy\", metrics=[\"accuracy\"])\nhistory = model.fit(x=X_train, y=y_train, batch_size=64, validation_split=0.1, epochs=epochs, callbacks=earlystopping)","metadata":{"execution":{"iopub.status.busy":"2021-11-29T13:38:33.1042Z","iopub.execute_input":"2021-11-29T13:38:33.105315Z","iopub.status.idle":"2021-11-29T13:42:25.359283Z","shell.execute_reply.started":"2021-11-29T13:38:33.105264Z","shell.execute_reply":"2021-11-29T13:42:25.358361Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pd.DataFrame(history.history).loc[:, [\"loss\", \"val_loss\"]].plot()\nplt.xticks(range(epochs))\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"Loss\")\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2021-11-29T13:42:25.360799Z","iopub.execute_input":"2021-11-29T13:42:25.361069Z","iopub.status.idle":"2021-11-29T13:42:25.61556Z","shell.execute_reply.started":"2021-11-29T13:42:25.361036Z","shell.execute_reply":"2021-11-29T13:42:25.614601Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.evaluate(x=X_val, y=y_val, batch_size=64)","metadata":{"execution":{"iopub.status.busy":"2021-11-29T13:42:25.61696Z","iopub.execute_input":"2021-11-29T13:42:25.617876Z","iopub.status.idle":"2021-11-29T13:42:26.978304Z","shell.execute_reply.started":"2021-11-29T13:42:25.617829Z","shell.execute_reply":"2021-11-29T13:42:26.977403Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Batch Normalization","metadata":{}},{"cell_type":"code","source":"from keras.layers import BatchNormalization\n\nmodel = Sequential([\n    Reshape((28, 28, 1)),\n    Convolution2D(32,(3,3), activation='relu'),\n    BatchNormalization(),\n    Convolution2D(32,(3,3), activation='relu'),\n    MaxPooling2D(),\n    Convolution2D(64,(3,3), activation='relu'),\n    BatchNormalization(),\n    Convolution2D(64,(3,3), activation='relu'),\n    MaxPooling2D(),\n    Flatten(),\n    Dense(512, activation='relu'),\n    Dense(10, activation='softmax')\n])","metadata":{"execution":{"iopub.status.busy":"2021-11-29T13:42:26.979573Z","iopub.execute_input":"2021-11-29T13:42:26.980276Z","iopub.status.idle":"2021-11-29T13:42:27.002678Z","shell.execute_reply.started":"2021-11-29T13:42:26.980231Z","shell.execute_reply":"2021-11-29T13:42:27.001794Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(optimizer=\"Adam\", loss=\"categorical_crossentropy\", metrics=[\"accuracy\"])\nearlystopping = EarlyStopping(patience=3)\nepochs = 10\nhistory = model.fit(x=X_train, y=y_train, batch_size=64, validation_split=0.1, epochs=epochs, callbacks=earlystopping)","metadata":{"execution":{"iopub.status.busy":"2021-11-29T13:42:27.004213Z","iopub.execute_input":"2021-11-29T13:42:27.00472Z","iopub.status.idle":"2021-11-29T13:46:07.474063Z","shell.execute_reply.started":"2021-11-29T13:42:27.004675Z","shell.execute_reply":"2021-11-29T13:46:07.472887Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pd.DataFrame(history.history).loc[:, [\"loss\", \"val_loss\"]].plot()\nplt.xticks(range(epochs))\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"Loss\")\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2021-11-29T13:46:07.476101Z","iopub.execute_input":"2021-11-29T13:46:07.476439Z","iopub.status.idle":"2021-11-29T13:46:07.728374Z","shell.execute_reply.started":"2021-11-29T13:46:07.476396Z","shell.execute_reply":"2021-11-29T13:46:07.727546Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.evaluate(x=X_val, y=y_val, batch_size=64)","metadata":{"execution":{"iopub.status.busy":"2021-11-29T13:46:07.729665Z","iopub.execute_input":"2021-11-29T13:46:07.730109Z","iopub.status.idle":"2021-11-29T13:46:09.658643Z","shell.execute_reply.started":"2021-11-29T13:46:07.730078Z","shell.execute_reply":"2021-11-29T13:46:09.657668Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Add Mean Pixel Value as Feature with Functional API","metadata":{}},{"cell_type":"code","source":"from keras import Model, Input, layers\nimport tensorflow as tf\n\ninputs = Input(shape=(784,))\n\nx = Reshape((28, 28, 1))(inputs)\nx = Convolution2D(32,(3,3), activation='relu')(x)\nx = BatchNormalization()(x)\nx = Convolution2D(32,(3,3), activation='relu')(x)\nx = MaxPooling2D()(x)\nx = Convolution2D(64,(3,3), activation='relu')(x)\nx = BatchNormalization()(x)\nx = Convolution2D(64,(3,3), activation='relu')(x)\nx = MaxPooling2D()(x)\nx = Flatten()(x)\nx = Dense(512, activation='relu')(x)\nx = Dense(10, activation='softmax')(x)\n\ny = tf.math.reduce_mean(inputs, keepdims=True)\ny = Dense(10, activation='softmax')(y)\n\noutputs = layers.add([x, y])\n\nmodel = Model(inputs, outputs)","metadata":{"execution":{"iopub.status.busy":"2021-11-29T13:46:09.659857Z","iopub.execute_input":"2021-11-29T13:46:09.660072Z","iopub.status.idle":"2021-11-29T13:46:09.79491Z","shell.execute_reply.started":"2021-11-29T13:46:09.660047Z","shell.execute_reply":"2021-11-29T13:46:09.794234Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.utils.vis_utils import plot_model\n\nplot_model(model, \"mnist.png\", show_shapes=True)","metadata":{"execution":{"iopub.status.busy":"2021-11-29T13:46:09.79832Z","iopub.execute_input":"2021-11-29T13:46:09.798584Z","iopub.status.idle":"2021-11-29T13:46:10.080886Z","shell.execute_reply.started":"2021-11-29T13:46:09.798555Z","shell.execute_reply":"2021-11-29T13:46:10.079705Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(optimizer=\"Adam\", loss=\"categorical_crossentropy\", metrics=[\"accuracy\"])\nearlystopping = EarlyStopping(patience=3)\nepochs = 10\nhistory = model.fit(x=X_train, y=y_train, batch_size=64, validation_split=0.1, epochs=epochs, callbacks=earlystopping)","metadata":{"execution":{"iopub.status.busy":"2021-11-29T13:46:10.08294Z","iopub.execute_input":"2021-11-29T13:46:10.083858Z","iopub.status.idle":"2021-11-29T13:51:00.768177Z","shell.execute_reply.started":"2021-11-29T13:46:10.083803Z","shell.execute_reply":"2021-11-29T13:51:00.767139Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pd.DataFrame(history.history).loc[:, [\"loss\", \"val_loss\"]].plot()\nplt.xticks(range(epochs))\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"Loss\")\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2021-11-29T13:51:00.77064Z","iopub.execute_input":"2021-11-29T13:51:00.771078Z","iopub.status.idle":"2021-11-29T13:51:33.300047Z","shell.execute_reply.started":"2021-11-29T13:51:00.771036Z","shell.execute_reply":"2021-11-29T13:51:33.29935Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.evaluate(x=X_val, y=y_val, batch_size=64)","metadata":{"execution":{"iopub.status.busy":"2021-11-29T13:51:33.301455Z","iopub.execute_input":"2021-11-29T13:51:33.301725Z","iopub.status.idle":"2021-11-29T13:51:34.834779Z","shell.execute_reply.started":"2021-11-29T13:51:33.301698Z","shell.execute_reply":"2021-11-29T13:51:34.833668Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Predict on Test Data","metadata":{}},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"predictions = np.argmax(model.predict(X_test, verbose=0), axis=1)\n\nsubmissions=pd.DataFrame({\"ImageId\": list(range(1,len(predictions)+1)),\n                         \"Label\": predictions})\nsubmissions.to_csv(\"predictions.csv\", index=False, header=True)","metadata":{"execution":{"iopub.status.busy":"2021-11-29T13:51:34.836229Z","iopub.execute_input":"2021-11-29T13:51:34.836564Z","iopub.status.idle":"2021-11-29T13:51:44.769444Z","shell.execute_reply.started":"2021-11-29T13:51:34.83652Z","shell.execute_reply":"2021-11-29T13:51:44.768268Z"},"trusted":true},"execution_count":null,"outputs":[]}]}