{"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 \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom keras.layers import Dense, Dropout, Flatten, Reshape\nfrom keras.optimizers import Adam\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom keras.utils import to_categorical\nimport matplotlib.pyplot as plt\n%matplotlib inline\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":{"trusted":true,"collapsed":true,"_uuid":"75b61e7343ed27a8bb390c7a32068ae6764a7c43"},"cell_type":"code","source":"# hyperparameters\nimg_side = 28\nnum_classes = 10\nbatch_size = 32\nepochs = 1","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"train_data = pd.read_csv(\"../input/train.csv\")\ntrain_data.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"72bc1cfa073c718f6a5b68592bb51ffae21ed51a"},"cell_type":"code","source":"test_data = pd.read_csv(\"../input/test.csv\")\ntest_data.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"20160aef4b08074836a8c149f21fe46975b40214"},"cell_type":"code","source":"train_data.describe()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"scrolled":true,"_uuid":"105b107d226ff5a08fe62f0de381874e8b9cc58c"},"cell_type":"code","source":"sparse_labels = train_data.loc[:, \"label\"].values\nprint(sparse_labels)\nlabels = to_categorical(sparse_labels, num_classes)\nprint(labels)\nprint(labels.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a26b48e3a015929879b368425870eee4b1879c6f"},"cell_type":"code","source":"x_data = train_data.iloc[:, 1:].values\nx_data = x_data / 255.0\nprint(x_data.shape)\nx_data = x_data.reshape(-1, img_side, img_side, 1)\nprint(x_data.shape)\n\nx_test = test_data.values\nx_test = x_test / 255.0\nx_test = x_test.reshape(-1, img_side, img_side, 1)\nprint(x_test.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"da2cd0d8479c1410e5d61d5a4f6a661b5f6ec0f3"},"cell_type":"code","source":"x_train = x_data[:len(x_data) * 9 // 10]\ny_train = labels[:len(x_data) * 9 // 10]\nx_val = x_data[-len(x_data) // 10:]\ny_val = labels[-len(x_data) // 10:]\n\nprint(x_train.shape)\nprint(x_val.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"fd5db665cff69706f13660e507e899c4dd445e66"},"cell_type":"code","source":"# build the model\nmlp = Sequential()\nmlp.add(Reshape((-1,), input_shape = (img_side, img_side, 1)))\nmlp.add(Dense(img_side * img_side, activation = \"relu\"))\nmlp.add(Dense(500, activation = \"relu\"))\nmlp.add(Dense(10, activation = \"softmax\"))\n\nprint(mlp.input_shape)\nprint(mlp.output_shape)\n\nmlp.compile(optimizer = Adam(),\n           loss = \"categorical_crossentropy\",\n           metrics = [\"accuracy\"])\n\ndata_gen = ImageDataGenerator()\ndata_gen.fit(x_train)\ntrain_batches = data_gen.flow(x_train, y_train, batch_size = batch_size)\nval_batches = data_gen.flow(x_val, y_val, batch_size = batch_size)\n\ntrain_res = mlp.fit_generator(generator = train_batches, steps_per_epoch = train_batches.n,\n                  epochs = epochs, validation_data = val_batches, validation_steps = val_batches.n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"447808e43fd73ccb819154f2f4b1738e972d3693"},"cell_type":"code","source":"print(\"Training loss: %.3f\" % train_res.history[\"acc\"][-1])\nprint(\"Validation loss: %.3f\" % train_res.history[\"val_acc\"][-1])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"8a3a28ccf8d8c3885d6e3a908350d974128d41e9"},"cell_type":"code","source":"test_batches = data_gen.flow(x_test, batch_size = len(x_test), shuffle = False)\nprobs = mlp.predict_generator(test_batches, steps = 1)\nsparse_preds = np.argmax(probs, axis = 1)\nprint(sparse_preds)\n\nres = pd.DataFrame(sparse_preds, index = np.arange(len(sparse_preds)) + 1, columns = [\"Label\"])\nres.to_csv(\"submission.csv\", index_label = \"ImageId\")\n\ntest = pd.read_csv(\"submission.csv\")\ntest.head()","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.4","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}