{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"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 in \nimport matplotlib.pyplot as plt\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nfrom keras.models import Sequential\nfrom keras.layers import Dropout, Conv2D, MaxPooling2D, Flatten, Dense\nfrom keras.losses import categorical_crossentropy\nfrom keras.optimizers import adam, Adadelta\n\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"../input\"))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"train_df = pd.read_csv(\"../input/train.csv\")\ntest_df = pd.read_csv(\"../input/test.csv\")\nprint(\"Shape of train data\", train_df.shape)\nprint(\"Shape of test data\", test_df.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"77e7ede4f1f1d754716a33bce659d2605d728d13"},"cell_type":"code","source":"X = train_df.drop(\"label\", axis = 1)\ny = train_df[\"label\"]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"4392d8c500a93dc9d7ffdfe85d0518030c4ff540"},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nx_train, x_val, y_train, y_val = train_test_split(X, y, test_size = 0.1, shuffle = True)\nprint(x_train.shape, x_val.shape, y_train.shape, y_val.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"dca1071044efde86756db341b82816bc7b47694e"},"cell_type":"code","source":"# Model parameter which we will use in training\n#input_dim = 784\noutput_dim = 10\nbatch_size = 128\nepoch = 13\nn_row, n_col = 28, 28","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"c058eb71b58a47f59d4909b90f2fb9eb80890dcc"},"cell_type":"code","source":"# Normalization\nx_train = x_train/255\nx_val = x_val/255\nprint(\"X train shape\", x_train.shape)\nprint(\"X test shape\", x_val.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"0f61a79a74412567a05ccb65befa6fa6e33836ed"},"cell_type":"code","source":"from keras import backend as k\nif k.image_data_format() == \"channels_first\":\n    x_train = x_train.values.reshape(x_train.shape[0], 1, n_row, n_col)\n    x_val = x_val.values.reshape(x_val.shape[0], 1, n_row, n_col)\n    test_df = test_df.values.reshape(test_df.shape[0], 1, n_row, n_col)\n    input_shape = (1, n_row, n_col)\nelse:\n    x_train = x_train.values.reshape(x_train.shape[0], n_row, n_col, 1)\n    x_val = x_val.values.reshape(x_val.shape[0], n_row, n_col, 1)\n    test_df = test_df.values.reshape(test_df.shape[0], n_row, n_col, 1)\n    input_shape = (n_row, n_col, 1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"db3fb31e5118f68462d3e54c0d79ab57b1611e47"},"cell_type":"code","source":"# Converts into binary class problem\nfrom keras.utils import to_categorical\ny_train = to_categorical(y_train, 10)\ny_val = to_categorical(y_val, 10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"c90c1e4bbd89a8f05ffef46ab0c1bfc3737858f9"},"cell_type":"code","source":"# Conv2D Model\nmodel = Sequential()\nmodel.add(Conv2D(16, kernel_size = (2, 2), input_shape = input_shape, activation = \"relu\"))\nmodel.add(Conv2D(32, kernel_size = (3, 3), activation = \"relu\"))\nmodel.add(MaxPooling2D(pool_size = (3, 3)))\n\nmodel.add(Conv2D(64, kernel_size = (3, 3), activation = \"relu\"))\nmodel.add(MaxPooling2D(pool_size = (3, 3)))\nmodel.add(Dropout(0.5))\n\nmodel.add(Flatten())\nmodel.add(Dense(234, activation = \"relu\"))\nmodel.add(Dense(output_dim, activation = \"softmax\"))\nmodel.compile(loss = categorical_crossentropy, metrics = [\"accuracy\"], optimizer = \"adam\")\nhistory = model.fit(x_train, y_train, batch_size, epochs = epoch, verbose = 1, validation_data = (x_val, y_val))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"c3abb649c69bdf66163a29baad9136f9d39b790f"},"cell_type":"code","source":"# Accuracy on validation data\nscore = model.evaluate(x_val, y_val, verbose = 0)\nprint(\"Validation Score:\", score[0])\nprint(\"Validation Accuracy\", score[1])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"89f42dea60dcb11504f1f6e72c57380f45927ff2"},"cell_type":"code","source":"# Plot validataion and train loss\nx = range(1, epoch + 1)\nval_loss = history.history[\"val_loss\"]\ntrain_loss = history.history[\"loss\"]\nplt.plot(x, val_loss, \"b\", label = \"Validation loss\")\nplt.plot(x, train_loss, \"r\", label = \"Train loss\")\nplt.xlabel(\"Epoch\")\nplt.ylabel(\"Categorical Crossentropy loss\")\nplt.legend()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"301a8d70c8329beeb96477c3fc831013691286e5"},"cell_type":"code","source":"# predict results\npred = model.predict(test_df)\nidx_max = np.argmax(pred,axis = 1)\nidx_max = pd.Series(idx_max, name = \"Label\")\nsample_submission = pd.concat([pd.Series(list(range(1,len(pred) + 1)),name = \"ImageId\"),idx_max],axis = 1)\nsample_submission.to_csv(\"sample_submission.csv\", index = False)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"6e3e153e8d3bf7c9a44c95a3d6057ae59154ec93"},"cell_type":"markdown","source":"**NOTE:** This is just a very basic model but will update it slightely when I have time, to get more accurate prediction. If you like it please upvote and if you have any question please feel free to ask in comment box."}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}