{"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\nimport matplotlib.pyplot as plt\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.linear_model import LogisticRegression\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 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# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Load data\n\nWe are going to load the data from files into dataframes using Pandas.\n","execution_count":null},{"metadata":{"_cell_guid":"","_uuid":"","trusted":true},"cell_type":"code","source":"import pandas as pd\nsample_submission = pd.read_csv(\"../input/digit-recognizer/sample_submission.csv\")\ntest = pd.read_csv(\"../input/digit-recognizer/test.csv\")\ntrain = pd.read_csv(\"../input/digit-recognizer/train.csv\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Take a look at the data.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"The first columns is the label of the data indicating the actual digit. Pixel0 to pixel783 are the values of the flattened 784 pixels.","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"# Train/validation splitting\n\nIn Machine Learning, it's extremely important to validate the trained model against a dataset that has never been \"seen\" by the model. Here we will randomly split the train dataset into two sets: one for training and one for validation using a 80:20 ratio.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"x_test = test.values\nx_train, x_val, y_train, y_val = train_test_split(\n    train.values[:,1:], train.values[:,0], test_size=0.2)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Visualize some images","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, ax = plt.subplots(4, 4, figsize=(8,8))\nfor i in range(4):\n    for j in range(4):\n        ax[i, j].imshow(x_train[i*4+j*4].reshape(28,28), cmap='gray')\n        ax[i, j].set_title('label = %s' % (y_train[i*4 + j*4]))\n        ax[i, j].set_xticks([])\n        ax[i, j].set_yticks([])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Create a Logistic Regression model","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"lr = LogisticRegression()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Train it","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"lr.fit(x_train, y_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"markdown","source":"# Make predictions on validation dataset","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.metrics import accuracy_score\ny_val_pred = lr.predict(x_val)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Show validation results\n\nWe will be using two tools to show the validation results.\n\nA ** confusion matrix ** is a table that is often used to describe the performance of a classification model (or \"classifier\") on a set of test data for which the true values are known. The confusion matrix itself is relatively simple to understand, but the related terminology can be confusing.\n\n** Classification accuracy ** is defined as the correctely predicted images / total images.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Model accuracy is %0.3f\" % (accuracy_score(y_val, y_val_pred)))\nprint(\"Confusion Matrix:\")\nprint(confusion_matrix(y_val, y_val_pred))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Show correctly classified images","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Correctly predicted images:\")\nx_val_correct = x_val[y_val==y_val_pred,:]\ny_val_correct = y_val[y_val==y_val_pred]\ny_val_pred_correct = y_val_pred[y_val==y_val_pred]\n\nfig, ax = plt.subplots(4, 4, figsize=(10,10))\nfor i in range(4):\n    for j in range(4):\n        ax[i, j].imshow(x_val_correct[i*4+j*4].reshape(28,28), cmap='gray')\n        ax[i, j].set_title('Label:%s, pred:%s' % (y_val_correct[i*4+j*4], y_val_pred_correct[i*4+j*4]))\n        ax[i, j].set_xticks([])\n        ax[i, j].set_yticks([])\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Show incorrectly classified images","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Incorrectly predicted images:\")\nx_val_incorrect = x_val[y_val!=y_val_pred,:]\ny_val_incorrect = y_val[y_val!=y_val_pred]\ny_val_pred_incorrect = y_val_pred[y_val!=y_val_pred]\n\nfig, ax = plt.subplots(4, 4, figsize=(10,10))\nfor i in range(4):\n    for j in range(4):\n        ax[i, j].imshow(x_val_incorrect[i*4+j*4].reshape(28,28), cmap='gray')\n        ax[i, j].set_title('Label:%s, pred:%s' % (y_val_incorrect[i*4+j*4], y_val_pred_incorrect[i*4+j*4]))\n        ax[i, j].set_xticks([])\n        ax[i, j].set_yticks([])\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Make predictions on test dataset","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"preds = lr.predict(x_test)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Make your very first Kaggle submission","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_submission['Label'] = preds\nsample_submission.to_csv('submission.csv', index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"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":4,"nbformat_minor":4}