{"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\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.preprocessing import Normalizer\n\n\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 warnings\nwarnings.filterwarnings('ignore')\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":{"trusted":true},"cell_type":"code","source":"train.shape","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":"# Train a naive logistic regression model\n","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\nlr = LogisticRegression(solver='lbfgs')\nlr.fit(x_train, y_train)\n\ny_val_pred = lr.predict(x_val)\nprint(\"Model accuracy is %0.3f\" % (accuracy_score(y_val, y_val_pred)))\nprint(\"Confusion Matrix:\")\nprint(confusion_matrix(y_val, y_val_pred))\n\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Make prediction\n\nLet's just name the prediction as submission_naive.csv","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"preds = lr.predict(x_test)\nsample_submission['Label'] = preds\nsample_submission.to_csv('submission_naive.csv', index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\nlr_norm = LogisticRegression(solver='lbfgs')\n\n# create a normalizer\nscaler = Normalizer()\n\n# train the model with normalized data\n# we can use Normalizer().fit_transform() function to normalize the data for training purpose\nlr_norm = LogisticRegression(solver='lbfgs')\n\nlr_norm.fit(scaler.fit_transform(x_train), y_train)\n\n# We have to make sure the same transformation applied on training data is applied on validation and test data as well\n# For validation and test we can use Normalizer.transform()\n\ny_val_pred = lr_norm.predict(scaler.transform(x_val))\nprint(\"Model accuracy with normalization is %0.3f\" % (accuracy_score(y_val, y_val_pred)))\nprint(\"Confusion Matrix:\")\nprint(confusion_matrix(y_val, y_val_pred))\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"preds = lr_norm.predict(scaler.transform(x_test))\nsample_submission['Label'] = preds\nsample_submission.to_csv('submission_norm.csv', index=False)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Find optimal value for hypter parameter C\n\nC is the regulazrization for Logistic Regression, By defaul, it uses L2 (Ridge)","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n# create a normalizer\nscaler = Normalizer()\n\n# train the model with normalized data\n# we can use Normalizer().fit_transform() function to normalize the data for training purpose\nlr_norm = LogisticRegression(solver='lbfgs', C=20)\n\nlr_norm.fit(scaler.fit_transform(x_train), y_train)\n\n# We have to make sure the same transformation applied on training data is applied on validation and test data as well\n# For validation and test we can use Normalizer.transform()\n\ny_val_pred = lr_norm.predict(scaler.transform(x_val))\nprint(\"Model accuracy with normalization is %0.3f\" % (accuracy_score(y_val, y_val_pred)))\nprint(\"Confusion Matrix:\")\nprint(confusion_matrix(y_val, y_val_pred))\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"preds = lr_norm.predict(scaler.transform(x_test))\nsample_submission['Label'] = preds\nsample_submission.to_csv('submission_norm_l2_C20.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}