{"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)\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":{"_uuid":"56020b396894fb20638cbaebaca6458274826c46"},"cell_type":"markdown","source":"Access our training and testing data"},{"metadata":{"trusted":true,"_uuid":"c180bc1c12bdd7da06afce204dafaf0f995aa214"},"cell_type":"code","source":"train_data = pd.read_csv('../input/train.csv')\ntest_data = pd.read_csv('../input/test.csv')","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"X_train = np.array(train_data.drop(['label'], axis = 1))\ny_train = np.array(train_data['label']).reshape(-1, 1)\n\nX_test = np.array(test_data)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"b57117683c45bd001334648dc12d1ad6676476e4"},"cell_type":"code","source":"print('X_train shape:', X_train.shape)\nprint('y_train shape:', y_train.shape)\nprint('X_test shape:', X_test.shape)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"fb6a615aa163f70bb9f0b2190deef4c6fd2fca88"},"cell_type":"markdown","source":"Normalize and reshape our training and testing data"},{"metadata":{"trusted":true,"_uuid":"9e8377f6c5f8c4ec2d0870e2a583b6772f3c8f73"},"cell_type":"code","source":"X_train = X_train.astype('float64')\nX_train /= 255\nX_train = X_train.reshape(X_train.shape[0], 28, 28, 1)\n\nX_test = X_test.astype('float64')\nX_test /= 255\nX_test = X_test.reshape(X_test.shape[0], 28, 28, 1)\n\nprint('X_train shape:', X_train.shape)\nprint('X_test shape:', X_test.shape)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"725e496dff5e49e0c4471ec983740c16b759a71b"},"cell_type":"markdown","source":"Convert our labels to categorical values"},{"metadata":{"trusted":true,"_uuid":"173827590f9acf43fa2598123c221274f4583513"},"cell_type":"code","source":"from keras.utils import to_categorical\n\ny_train = to_categorical(y_train)\n\nprint('y_train shape:', y_train.shape)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"137fe2cb5f4c4fc963a947ca2aa7c5bcdd555b4a"},"cell_type":"markdown","source":"Build our model"},{"metadata":{"trusted":true,"_uuid":"345f51c19aea70f2bd18cb01e8b06ec70e17d1b7"},"cell_type":"code","source":"from keras import models\nfrom keras import layers\nfrom keras import optimizers\n\ndef build_model(lr = 0.01):\n    model = models.Sequential()\n    model.add(layers.Conv2D(32, 3, activation = 'relu', input_shape = (X_train.shape[1], X_train.shape[2], X_train.shape[-1])))\n    model.add(layers.BatchNormalization())\n    model.add(layers.MaxPooling2D())\n    model.add(layers.Conv2D(64, 3, activation = 'relu'))\n    model.add(layers.BatchNormalization())\n    model.add(layers.MaxPooling2D())\n    model.add(layers.Flatten())\n    model.add(layers.Dense(64, activation = 'relu'))\n    model.add(layers.Dropout(0.5))\n    model.add(layers.Dense(10, activation = 'softmax'))\n    model.compile(optimizer = optimizers.RMSprop(lr = lr), loss = 'categorical_crossentropy', metrics = ['acc'])\n    \n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"2acf896e322f8d194f913e9153e2d1afcba543d5"},"cell_type":"code","source":"model = build_model(lr = 0.001)\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"a7482ca73ef3d686443fc15ab204245343ccd90b"},"cell_type":"markdown","source":"Create our callbacks"},{"metadata":{"trusted":true,"_uuid":"28bce5f2c04fbafedb71f0327a5e9d9d1cc7b4f2"},"cell_type":"code","source":"from keras import callbacks\n\ncallbacks = [callbacks.EarlyStopping(monitor = 'val_loss', patience = 5, restore_best_weights = True)]","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"1cd5ca502afb2cb6eff369234ce9a33355d00cfa"},"cell_type":"markdown","source":"Train our model"},{"metadata":{"trusted":true,"_uuid":"a1ff80c3ad8b7f4bf3aee04f4346a9618071e4f2"},"cell_type":"code","source":"history = model.fit(X_train, y_train,\n                    epochs = 25,\n                    batch_size = 64,\n                    validation_split = 0.2,\n                    callbacks = callbacks)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"2423530c2988c11d150d249873c7c18907c426fe"},"cell_type":"code","source":"import matplotlib.pyplot as plt\n\ndef plot_history(history):\n    acc = history.history['acc']\n    val_acc = history.history['val_acc']\n    loss = history.history['loss']\n    val_loss = history.history['val_loss']\n    \n    epochs = range(1, len(acc) + 1)\n    \n    plt.figure(figsize = (25, 5))\n    \n    plt.subplot(1,2,1)\n    plt.plot(epochs, acc, c = 'b', label = 'train acc')\n    plt.plot(epochs, val_acc, c = 'g', label = 'val acc')\n    plt.title('Train vs Val Acc')\n    plt.legend()\n    \n    plt.subplot(1,2,2)\n    plt.plot(epochs, loss, c = 'b', label = 'train loss')\n    plt.plot(epochs, val_loss, c = 'g', label = 'val loss')\n    plt.title('Train vs Val Loss')\n    plt.legend()\n    \n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a7d4ea8c2fd0f361a11fa513882a61b2d103dafd"},"cell_type":"code","source":"plot_history(history)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"15369bfec60d34b271709a53a019ace3a918e0bc"},"cell_type":"markdown","source":"Make predictions with our model"},{"metadata":{"trusted":true,"_uuid":"d0aac181820ddf963c4e98903c8c0c9f4c09a400"},"cell_type":"code","source":"predictions = model.predict(X_test)\npredictions = predictions.argmax(axis = 1)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"e7cf287f1a8bb59268f860260a67101813272c88"},"cell_type":"markdown","source":"Output results to file"},{"metadata":{"trusted":true,"_uuid":"8a63854e890745d7d450d3beea527fc38f2d9fec"},"cell_type":"code","source":"image_ids = pd.DataFrame(np.arange(1, len(X_test) + 1))\npreds = pd.DataFrame(predictions)\n\noutput = pd.DataFrame(np.concatenate([image_ids, preds], axis = 1))\noutput.columns = ['ImageId', 'Label']\n\noutput.to_csv('output.csv', encoding = 'utf-8')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"4a9cda1176be923cca38b49d44cc6071cf1de15c"},"cell_type":"code","source":"","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}