{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Data Scientist Nanodegree\n",
    "## Supervised Learning\n",
    "## Project: Finding Donors for *CharityML*"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Welcome to the first project of the Data Scientist Nanodegree! In this notebook, some template code has already been provided for you, and it will be your job to implement the additional functionality necessary to successfully complete this project. Sections that begin with **'Implementation'** in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section and the specifics of the implementation are marked in the code block with a `'TODO'` statement. Please be sure to read the instructions carefully!\n",
    "\n",
    "In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a **'Question X'** header. Carefully read each question and provide thorough answers in the following text boxes that begin with **'Answer:'**. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.  \n",
    "\n",
    ">**Note:** Please specify WHICH VERSION OF PYTHON you are using when submitting this notebook. Code and Markdown cells can be executed using the **Shift + Enter** keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Getting Started\n",
    "\n",
    "In this project, you will employ several supervised algorithms of your choice to accurately model individuals' income using data collected from the 1994 U.S. Census. You will then choose the best candidate algorithm from preliminary results and further optimize this algorithm to best model the data. Your goal with this implementation is to construct a model that accurately predicts whether an individual makes more than $50,000. This sort of task can arise in a non-profit setting, where organizations survive on donations.  Understanding an individual's income can help a non-profit better understand how large of a donation to request, or whether or not they should reach out to begin with.  While it can be difficult to determine an individual's general income bracket directly from public sources, we can (as we will see) infer this value from other publically available features. \n",
    "\n",
    "The dataset for this project originates from the [UCI Machine Learning Repository](https://archive.ics.uci.edu/ml/datasets/Census+Income). The datset was donated by Ron Kohavi and Barry Becker, after being published in the article _\"Scaling Up the Accuracy of Naive-Bayes Classifiers: A Decision-Tree Hybrid\"_. You can find the article by Ron Kohavi [online](https://www.aaai.org/Papers/KDD/1996/KDD96-033.pdf). The data we investigate here consists of small changes to the original dataset, such as removing the `'fnlwgt'` feature and records with missing or ill-formatted entries."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "----\n",
    "## Exploring the Data\n",
    "Run the code cell below to load necessary Python libraries and load the census data. Note that the last column from this dataset, `'income'`, will be our target label (whether an individual makes more than, or at most, $50,000 annually). All other columns are features about each individual in the census database."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>age</th>\n",
       "      <th>workclass</th>\n",
       "      <th>education_level</th>\n",
       "      <th>education-num</th>\n",
       "      <th>marital-status</th>\n",
       "      <th>occupation</th>\n",
       "      <th>relationship</th>\n",
       "      <th>race</th>\n",
       "      <th>sex</th>\n",
       "      <th>capital-gain</th>\n",
       "      <th>capital-loss</th>\n",
       "      <th>hours-per-week</th>\n",
       "      <th>native-country</th>\n",
       "      <th>income</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>39</td>\n",
       "      <td>State-gov</td>\n",
       "      <td>Bachelors</td>\n",
       "      <td>13.0</td>\n",
       "      <td>Never-married</td>\n",
       "      <td>Adm-clerical</td>\n",
       "      <td>Not-in-family</td>\n",
       "      <td>White</td>\n",
       "      <td>Male</td>\n",
       "      <td>2174.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>40.0</td>\n",
       "      <td>United-States</td>\n",
       "      <td>&lt;=50K</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   age   workclass education_level  education-num  marital-status  \\\n",
       "0   39   State-gov       Bachelors           13.0   Never-married   \n",
       "\n",
       "      occupation    relationship    race    sex  capital-gain  capital-loss  \\\n",
       "0   Adm-clerical   Not-in-family   White   Male        2174.0           0.0   \n",
       "\n",
       "   hours-per-week  native-country income  \n",
       "0            40.0   United-States  <=50K  "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Import libraries necessary for this project\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from time import time\n",
    "from IPython.display import display # Allows the use of display() for DataFrames\n",
    "import seaborn as sns\n",
    "import matplotlib as plt\n",
    "\n",
    "# Import supplementary visualization code visuals.py\n",
    "import visuals as vs\n",
    "\n",
    "# Pretty display for notebooks\n",
    "%matplotlib inline\n",
    "\n",
    "# Load the Census dataset\n",
    "data = pd.read_csv(\"census.csv\")\n",
    "\n",
    "# Success - Display the first record\n",
    "display(data.head(1))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Implementation: Data Exploration\n",
    "A cursory investigation of the dataset will determine how many individuals fit into either group, and will tell us about the percentage of these individuals making more than \\$50,000. In the code cell below, you will need to compute the following:\n",
    "- The total number of records, `'n_records'`\n",
    "- The number of individuals making more than \\$50,000 annually, `'n_greater_50k'`.\n",
    "- The number of individuals making at most \\$50,000 annually, `'n_at_most_50k'`.\n",
    "- The percentage of individuals making more than \\$50,000 annually, `'greater_percent'`.\n",
    "\n",
    "** HINT: ** You may need to look at the table above to understand how the `'income'` entries are formatted. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Check for missing data\n",
    "To check for missing data we need to see if any rows are missing:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "                age  education-num  capital-gain  capital-loss  hours-per-week\n",
      "count  45222.000000   45222.000000  45222.000000  45222.000000    45222.000000\n",
      "mean      38.547941      10.118460   1101.430344     88.595418       40.938017\n",
      "std       13.217870       2.552881   7506.430084    404.956092       12.007508\n",
      "min       17.000000       1.000000      0.000000      0.000000        1.000000\n",
      "25%       28.000000       9.000000      0.000000      0.000000       40.000000\n",
      "50%       37.000000      10.000000      0.000000      0.000000       40.000000\n",
      "75%       47.000000      13.000000      0.000000      0.000000       45.000000\n",
      "max       90.000000      16.000000  99999.000000   4356.000000       99.000000\n",
      "Total number of rows for income = 45222\n",
      "\n",
      "No missing data\n"
     ]
    }
   ],
   "source": [
    "print(data.describe())\n",
    "print('Total number of rows for income = {}\\n'.format(data['income'].shape[0]))\n",
    "if (data.isnull().values.any()) == False:\n",
    "    print('No missing data')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<=50K    34014\n",
      ">50K     11208\n",
      "dtype: int64\n"
     ]
    }
   ],
   "source": [
    "from collections import Counter\n",
    "income_values = pd.Series(data['income'].str.replace('[\\[\\]\\']','').str.split(',').map(Counter).sum())\n",
    "print(income_values)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Total number of records: 45222\n",
      "Individuals making more than $50,000: 11208\n",
      "Individuals making at most $50,000: 34014\n",
      "Percentage of individuals making more than $50,000: 24.78%\n"
     ]
    }
   ],
   "source": [
    "# TODO: Total number of records\n",
    "n_records = income_values.sum()\n",
    "\n",
    "# TODO: Number of records where individual's income is more than $50,000\n",
    "n_greater_50k = income_values[1]\n",
    "\n",
    "# TODO: Number of records where individual's income is at most $50,000\n",
    "n_at_most_50k = income_values[0]\n",
    "\n",
    "# TODO: Percentage of individuals whose income is more than $50,000\n",
    "greater_percent = 100 * (n_greater_50k/n_records)\n",
    "\n",
    "# Print the results\n",
    "print(\"Total number of records: {}\".format(n_records))\n",
    "print(\"Individuals making more than $50,000: {}\".format(n_greater_50k))\n",
    "print(\"Individuals making at most $50,000: {}\".format(n_at_most_50k))\n",
    "print(\"Percentage of individuals making more than $50,000: {:.2f}%\".format(greater_percent))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "** Featureset Exploration **\n",
    "\n",
    "* **age**: continuous. \n",
    "* **workclass**: Private, Self-emp-not-inc, Self-emp-inc, Federal-gov, Local-gov, State-gov, Without-pay, Never-worked. \n",
    "* **education**: Bachelors, Some-college, 11th, HS-grad, Prof-school, Assoc-acdm, Assoc-voc, 9th, 7th-8th, 12th, Masters, 1st-4th, 10th, Doctorate, 5th-6th, Preschool. \n",
    "* **education-num**: continuous. \n",
    "* **marital-status**: Married-civ-spouse, Divorced, Never-married, Separated, Widowed, Married-spouse-absent, Married-AF-spouse. \n",
    "* **occupation**: Tech-support, Craft-repair, Other-service, Sales, Exec-managerial, Prof-specialty, Handlers-cleaners, Machine-op-inspct, Adm-clerical, Farming-fishing, Transport-moving, Priv-house-serv, Protective-serv, Armed-Forces. \n",
    "* **relationship**: Wife, Own-child, Husband, Not-in-family, Other-relative, Unmarried. \n",
    "* **race**: Black, White, Asian-Pac-Islander, Amer-Indian-Eskimo, Other. \n",
    "* **sex**: Female, Male. \n",
    "* **capital-gain**: continuous. \n",
    "* **capital-loss**: continuous. \n",
    "* **hours-per-week**: continuous. \n",
    "* **native-country**: United-States, Cambodia, England, Puerto-Rico, Canada, Germany, Outlying-US(Guam-USVI-etc), India, Japan, Greece, South, China, Cuba, Iran, Honduras, Philippines, Italy, Poland, Jamaica, Vietnam, Mexico, Portugal, Ireland, France, Dominican-Republic, Laos, Ecuador, Taiwan, Haiti, Columbia, Hungary, Guatemala, Nicaragua, Scotland, Thailand, Yugoslavia, El-Salvador, Trinadad&Tobago, Peru, Hong, Holand-Netherlands."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "----\n",
    "## Preparing the Data\n",
    "Before data can be used as input for machine learning algorithms, it often must be cleaned, formatted, and restructured — this is typically known as **preprocessing**. Fortunately, for this dataset, there are no invalid or missing entries we must deal with, however, there are some qualities about certain features that must be adjusted. This preprocessing can help tremendously with the outcome and predictive power of nearly all learning algorithms."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Transforming Skewed Continuous Features\n",
    "A dataset may sometimes contain at least one feature whose values tend to lie near a single number, but will also have a non-trivial number of vastly larger or smaller values than that single number.  Algorithms can be sensitive to such distributions of values and can underperform if the range is not properly normalized. With the census dataset two features fit this description: '`capital-gain'` and `'capital-loss'`. \n",
    "\n",
    "Run the code cell below to plot a histogram of these two features. Note the range of the values present and how they are distributed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "import warnings\n",
    "warnings.filterwarnings(\"ignore\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<seaborn.axisgrid.PairGrid at 0x23cfcdb3ba8>"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 311164 characters]\n",
      "text/plain": [
       "<Figure size 900x900 with 30 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "sns.pairplot(data, diag_kind='hist')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Using seaborn distplot we can use rug=True to see where the values lie. We can then adjust the y axis and the number of bins to get a better view."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(0, 1500)"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 7864 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "hist0 = sns.distplot(data['capital-loss'], kde=False, rug=True, bins=10)\n",
    "axes0 = hist0.axes\n",
    "axes0.set_ylim(0,1500)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(0, 1000)"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 6924 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "hist1 = sns.distplot(data['capital-gain'], kde=False, rug=True, bins=10)\n",
    "axes1 = hist1.axes\n",
    "axes1.set_ylim(0,1000)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 22228 characters]\n",
      "text/plain": [
       "<Figure size 792x360 with 2 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Split the data into features and target label\n",
    "income_raw = data['income']\n",
    "features_raw = data.drop('income', axis = 1)\n",
    "\n",
    "# Visualize skewed continuous features of original data\n",
    "vs.distribution(data)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For highly-skewed feature distributions such as `'capital-gain'` and `'capital-loss'`, it is common practice to apply a <a href=\"https://en.wikipedia.org/wiki/Data_transformation_(statistics)\">logarithmic transformation</a> on the data so that the very large and very small values do not negatively affect the performance of a learning algorithm. Using a logarithmic transformation significantly reduces the range of values caused by outliers. Care must be taken when applying this transformation however: The logarithm of `0` is undefined, so we must translate the values by a small amount above `0` to apply the the logarithm successfully.\n",
    "\n",
    "Run the code cell below to perform a transformation on the data and visualize the results. Again, note the range of values and how they are distributed. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 21772 characters]\n",
      "text/plain": [
       "<Figure size 792x360 with 2 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Log-transform the skewed features\n",
    "skewed = ['capital-gain', 'capital-loss']\n",
    "features_log_transformed = pd.DataFrame(data = features_raw)\n",
    "features_log_transformed[skewed] = features_raw[skewed].apply(lambda x: np.log(x + 1))\n",
    "\n",
    "# Visualize the new log distributions\n",
    "vs.distribution(features_log_transformed, transformed = True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(0, 1500)"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 7500 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "hist2 = sns.distplot(features_log_transformed['capital-gain'], kde=False, rug=True, bins=10)\n",
    "axes2 = hist2.axes\n",
    "axes2.set_ylim(0,1500)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(0, 1500)"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 7248 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "hist3 = sns.distplot(features_log_transformed['capital-loss'], kde=False, rug=True, bins=10)\n",
    "axes3 = hist3.axes\n",
    "axes3.set_ylim(0,1500)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Normalizing Numerical Features\n",
    "In addition to performing transformations on features that are highly skewed, it is often good practice to perform some type of scaling on numerical features. Applying a scaling to the data does not change the shape of each feature's distribution (such as `'capital-gain'` or `'capital-loss'` above); however, normalization ensures that each feature is treated equally when applying supervised learners. Note that once scaling is applied, observing the data in its raw form will no longer have the same original meaning, as exampled below.\n",
    "\n",
    "Run the code cell below to normalize each numerical feature. We will use [`sklearn.preprocessing.MinMaxScaler`](http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MinMaxScaler.html) for this."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>age</th>\n",
       "      <th>workclass</th>\n",
       "      <th>education_level</th>\n",
       "      <th>education-num</th>\n",
       "      <th>marital-status</th>\n",
       "      <th>occupation</th>\n",
       "      <th>relationship</th>\n",
       "      <th>race</th>\n",
       "      <th>sex</th>\n",
       "      <th>capital-gain</th>\n",
       "      <th>capital-loss</th>\n",
       "      <th>hours-per-week</th>\n",
       "      <th>native-country</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>0.301370</td>\n",
       "      <td>State-gov</td>\n",
       "      <td>Bachelors</td>\n",
       "      <td>0.800000</td>\n",
       "      <td>Never-married</td>\n",
       "      <td>Adm-clerical</td>\n",
       "      <td>Not-in-family</td>\n",
       "      <td>White</td>\n",
       "      <td>Male</td>\n",
       "      <td>0.667492</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.397959</td>\n",
       "      <td>United-States</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>0.452055</td>\n",
       "      <td>Self-emp-not-inc</td>\n",
       "      <td>Bachelors</td>\n",
       "      <td>0.800000</td>\n",
       "      <td>Married-civ-spouse</td>\n",
       "      <td>Exec-managerial</td>\n",
       "      <td>Husband</td>\n",
       "      <td>White</td>\n",
       "      <td>Male</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.122449</td>\n",
       "      <td>United-States</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>0.287671</td>\n",
       "      <td>Private</td>\n",
       "      <td>HS-grad</td>\n",
       "      <td>0.533333</td>\n",
       "      <td>Divorced</td>\n",
       "      <td>Handlers-cleaners</td>\n",
       "      <td>Not-in-family</td>\n",
       "      <td>White</td>\n",
       "      <td>Male</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.397959</td>\n",
       "      <td>United-States</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>0.493151</td>\n",
       "      <td>Private</td>\n",
       "      <td>11th</td>\n",
       "      <td>0.400000</td>\n",
       "      <td>Married-civ-spouse</td>\n",
       "      <td>Handlers-cleaners</td>\n",
       "      <td>Husband</td>\n",
       "      <td>Black</td>\n",
       "      <td>Male</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.397959</td>\n",
       "      <td>United-States</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>0.150685</td>\n",
       "      <td>Private</td>\n",
       "      <td>Bachelors</td>\n",
       "      <td>0.800000</td>\n",
       "      <td>Married-civ-spouse</td>\n",
       "      <td>Prof-specialty</td>\n",
       "      <td>Wife</td>\n",
       "      <td>Black</td>\n",
       "      <td>Female</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.397959</td>\n",
       "      <td>Cuba</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "        age          workclass education_level  education-num  \\\n",
       "0  0.301370          State-gov       Bachelors       0.800000   \n",
       "1  0.452055   Self-emp-not-inc       Bachelors       0.800000   \n",
       "2  0.287671            Private         HS-grad       0.533333   \n",
       "3  0.493151            Private            11th       0.400000   \n",
       "4  0.150685            Private       Bachelors       0.800000   \n",
       "\n",
       "        marital-status          occupation    relationship    race      sex  \\\n",
       "0        Never-married        Adm-clerical   Not-in-family   White     Male   \n",
       "1   Married-civ-spouse     Exec-managerial         Husband   White     Male   \n",
       "2             Divorced   Handlers-cleaners   Not-in-family   White     Male   \n",
       "3   Married-civ-spouse   Handlers-cleaners         Husband   Black     Male   \n",
       "4   Married-civ-spouse      Prof-specialty            Wife   Black   Female   \n",
       "\n",
       "   capital-gain  capital-loss  hours-per-week  native-country  \n",
       "0      0.667492           0.0        0.397959   United-States  \n",
       "1      0.000000           0.0        0.122449   United-States  \n",
       "2      0.000000           0.0        0.397959   United-States  \n",
       "3      0.000000           0.0        0.397959   United-States  \n",
       "4      0.000000           0.0        0.397959            Cuba  "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Import sklearn.preprocessing.StandardScaler\n",
    "from sklearn.preprocessing import MinMaxScaler\n",
    "\n",
    "# Initialize a scaler, then apply it to the features\n",
    "scaler = MinMaxScaler() # default=(0, 1)\n",
    "numerical = ['age', 'education-num', 'capital-gain', 'capital-loss', 'hours-per-week']\n",
    "\n",
    "features_log_minmax_transform = pd.DataFrame(data = features_log_transformed)\n",
    "features_log_minmax_transform[numerical] = scaler.fit_transform(features_log_transformed[numerical])\n",
    "\n",
    "# Show an example of a record with scaling applied\n",
    "display(features_log_minmax_transform.head(n = 5))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Implementation: Data Preprocessing\n",
    "\n",
    "From the table in **Exploring the Data** above, we can see there are several features for each record that are non-numeric. Typically, learning algorithms expect input to be numeric, which requires that non-numeric features (called *categorical variables*) be converted. One popular way to convert categorical variables is by using the **one-hot encoding** scheme. One-hot encoding creates a _\"dummy\"_ variable for each possible category of each non-numeric feature. For example, assume `someFeature` has three possible entries: `A`, `B`, or `C`. We then encode this feature into `someFeature_A`, `someFeature_B` and `someFeature_C`.\n",
    "\n",
    "|   | someFeature |                    | someFeature_A | someFeature_B | someFeature_C |\n",
    "| :-: | :-: |                            | :-: | :-: | :-: |\n",
    "| 0 |  B  |  | 0 | 1 | 0 |\n",
    "| 1 |  C  | ----> one-hot encode ----> | 0 | 0 | 1 |\n",
    "| 2 |  A  |  | 1 | 0 | 0 |\n",
    "\n",
    "Additionally, as with the non-numeric features, we need to convert the non-numeric target label, `'income'` to numerical values for the learning algorithm to work. Since there are only two possible categories for this label (\"<=50K\" and \">50K\"), we can avoid using one-hot encoding and simply encode these two categories as `0` and `1`, respectively. In code cell below, you will need to implement the following:\n",
    " - Use [`pandas.get_dummies()`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html?highlight=get_dummies#pandas.get_dummies) to perform one-hot encoding on the `'features_log_minmax_transform'` data.\n",
    " - Convert the target label `'income_raw'` to numerical entries.\n",
    "   - Set records with \"<=50K\" to `0` and records with \">50K\" to `1`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>age</th>\n",
       "      <th>workclass</th>\n",
       "      <th>education_level</th>\n",
       "      <th>education-num</th>\n",
       "      <th>marital-status</th>\n",
       "      <th>occupation</th>\n",
       "      <th>relationship</th>\n",
       "      <th>race</th>\n",
       "      <th>sex</th>\n",
       "      <th>capital-gain</th>\n",
       "      <th>capital-loss</th>\n",
       "      <th>hours-per-week</th>\n",
       "      <th>native-country</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>22625</th>\n",
       "      <td>0.479452</td>\n",
       "      <td>Private</td>\n",
       "      <td>Some-college</td>\n",
       "      <td>0.600000</td>\n",
       "      <td>Married-civ-spouse</td>\n",
       "      <td>Craft-repair</td>\n",
       "      <td>Husband</td>\n",
       "      <td>White</td>\n",
       "      <td>Male</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>0.397959</td>\n",
       "      <td>United-States</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>40382</th>\n",
       "      <td>0.315068</td>\n",
       "      <td>Federal-gov</td>\n",
       "      <td>Bachelors</td>\n",
       "      <td>0.800000</td>\n",
       "      <td>Married-civ-spouse</td>\n",
       "      <td>Adm-clerical</td>\n",
       "      <td>Husband</td>\n",
       "      <td>White</td>\n",
       "      <td>Male</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.905759</td>\n",
       "      <td>0.397959</td>\n",
       "      <td>United-States</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10195</th>\n",
       "      <td>0.424658</td>\n",
       "      <td>Local-gov</td>\n",
       "      <td>Some-college</td>\n",
       "      <td>0.600000</td>\n",
       "      <td>Married-civ-spouse</td>\n",
       "      <td>Exec-managerial</td>\n",
       "      <td>Husband</td>\n",
       "      <td>White</td>\n",
       "      <td>Male</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>0.397959</td>\n",
       "      <td>United-States</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3225</th>\n",
       "      <td>0.123288</td>\n",
       "      <td>Private</td>\n",
       "      <td>HS-grad</td>\n",
       "      <td>0.533333</td>\n",
       "      <td>Never-married</td>\n",
       "      <td>Adm-clerical</td>\n",
       "      <td>Own-child</td>\n",
       "      <td>White</td>\n",
       "      <td>Female</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>0.397959</td>\n",
       "      <td>United-States</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>31195</th>\n",
       "      <td>0.219178</td>\n",
       "      <td>Private</td>\n",
       "      <td>Bachelors</td>\n",
       "      <td>0.800000</td>\n",
       "      <td>Never-married</td>\n",
       "      <td>Prof-specialty</td>\n",
       "      <td>Not-in-family</td>\n",
       "      <td>White</td>\n",
       "      <td>Female</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>0.397959</td>\n",
       "      <td>Canada</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "            age     workclass education_level  education-num  \\\n",
       "22625  0.479452       Private    Some-college       0.600000   \n",
       "40382  0.315068   Federal-gov       Bachelors       0.800000   \n",
       "10195  0.424658     Local-gov    Some-college       0.600000   \n",
       "3225   0.123288       Private         HS-grad       0.533333   \n",
       "31195  0.219178       Private       Bachelors       0.800000   \n",
       "\n",
       "            marital-status        occupation    relationship    race      sex  \\\n",
       "22625   Married-civ-spouse      Craft-repair         Husband   White     Male   \n",
       "40382   Married-civ-spouse      Adm-clerical         Husband   White     Male   \n",
       "10195   Married-civ-spouse   Exec-managerial         Husband   White     Male   \n",
       "3225         Never-married      Adm-clerical       Own-child   White   Female   \n",
       "31195        Never-married    Prof-specialty   Not-in-family   White   Female   \n",
       "\n",
       "       capital-gain  capital-loss  hours-per-week  native-country  \n",
       "22625           0.0      0.000000        0.397959   United-States  \n",
       "40382           0.0      0.905759        0.397959   United-States  \n",
       "10195           0.0      0.000000        0.397959   United-States  \n",
       "3225            0.0      0.000000        0.397959   United-States  \n",
       "31195           0.0      0.000000        0.397959          Canada  "
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# non_numeric_features = features_log_minmax_transform.drop(numerical, axis=1)\n",
    "features_log_minmax_transform.sample(frac=1).head(5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "103 total features after one-hot encoding.\n",
      "\n",
      "Encoded feature names are:\n",
      "['age', 'education-num', 'capital-gain', 'capital-loss', 'hours-per-week', 'workclass_ Federal-gov', 'workclass_ Local-gov', 'workclass_ Private', 'workclass_ Self-emp-inc', 'workclass_ Self-emp-not-inc', 'workclass_ State-gov', 'workclass_ Without-pay', 'education_level_ 10th', 'education_level_ 11th', 'education_level_ 12th', 'education_level_ 1st-4th', 'education_level_ 5th-6th', 'education_level_ 7th-8th', 'education_level_ 9th', 'education_level_ Assoc-acdm', 'education_level_ Assoc-voc', 'education_level_ Bachelors', 'education_level_ Doctorate', 'education_level_ HS-grad', 'education_level_ Masters', 'education_level_ Preschool', 'education_level_ Prof-school', 'education_level_ Some-college', 'marital-status_ Divorced', 'marital-status_ Married-AF-spouse', 'marital-status_ Married-civ-spouse', 'marital-status_ Married-spouse-absent', 'marital-status_ Never-married', 'marital-status_ Separated', 'marital-status_ Widowed', 'occupation_ Adm-clerical', 'occupation_ Armed-Forces', 'occupation_ Craft-repair', 'occupation_ Exec-managerial', 'occupation_ Farming-fishing', 'occupation_ Handlers-cleaners', 'occupation_ Machine-op-inspct', 'occupation_ Other-service', 'occupation_ Priv-house-serv', 'occupation_ Prof-specialty', 'occupation_ Protective-serv', 'occupation_ Sales', 'occupation_ Tech-support', 'occupation_ Transport-moving', 'relationship_ Husband', 'relationship_ Not-in-family', 'relationship_ Other-relative', 'relationship_ Own-child', 'relationship_ Unmarried', 'relationship_ Wife', 'race_ Amer-Indian-Eskimo', 'race_ Asian-Pac-Islander', 'race_ Black', 'race_ Other', 'race_ White', 'sex_ Female', 'sex_ Male', 'native-country_ Cambodia', 'native-country_ Canada', 'native-country_ China', 'native-country_ Columbia', 'native-country_ Cuba', 'native-country_ Dominican-Republic', 'native-country_ Ecuador', 'native-country_ El-Salvador', 'native-country_ England', 'native-country_ France', 'native-country_ Germany', 'native-country_ Greece', 'native-country_ Guatemala', 'native-country_ Haiti', 'native-country_ Holand-Netherlands', 'native-country_ Honduras', 'native-country_ Hong', 'native-country_ Hungary', 'native-country_ India', 'native-country_ Iran', 'native-country_ Ireland', 'native-country_ Italy', 'native-country_ Jamaica', 'native-country_ Japan', 'native-country_ Laos', 'native-country_ Mexico', 'native-country_ Nicaragua', 'native-country_ Outlying-US(Guam-USVI-etc)', 'native-country_ Peru', 'native-country_ Philippines', 'native-country_ Poland', 'native-country_ Portugal', 'native-country_ Puerto-Rico', 'native-country_ Scotland', 'native-country_ South', 'native-country_ Taiwan', 'native-country_ Thailand', 'native-country_ Trinadad&Tobago', 'native-country_ United-States', 'native-country_ Vietnam', 'native-country_ Yugoslavia']\n",
      "\n",
      "The income col now looks like:\n",
      "14023    0\n",
      "41062    0\n",
      "38718    1\n",
      "36016    0\n",
      "22478    0\n",
      "Name: income, dtype: object\n"
     ]
    }
   ],
   "source": [
    "# TODO: One-hot encode the 'features_log_minmax_transform' data using pandas.get_dummies()\n",
    "features_final = pd.get_dummies(features_log_minmax_transform)\n",
    "\n",
    "# TODO: Encode the 'income_raw' data to numerical values\n",
    "income_raw.iloc[::-1][income_raw.iloc[::-1] == '<=50K'] = 0\n",
    "income_raw.iloc[::-1][income_raw.iloc[::-1] == '>50K'] = 1\n",
    "\n",
    "# Print the number of features after one-hot encoding\n",
    "encoded = list(features_final.columns)\n",
    "print(\"{} total features after one-hot encoding.\\n\".format(len(encoded)))\n",
    "\n",
    "# Uncomment the following line to see the encoded feature names\n",
    "print(f'Encoded feature names are:\\n{encoded}\\n')\n",
    "print(f'The income col now looks like:\\n{income_raw.sample(frac=1).head(5)}')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Convert income raw to dtype of int32"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0    0\n",
       "1    0\n",
       "2    0\n",
       "Name: income, dtype: int32"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "income_raw = pd.Series(income_raw, dtype='int32')\n",
    "income_raw.head(3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Shuffle and Split Data\n",
    "Now all _categorical variables_ have been converted into numerical features, and all numerical features have been normalized. As always, we will now split the data (both features and their labels) into training and test sets. 80% of the data will be used for training and 20% for testing.\n",
    "\n",
    "Run the code cell below to perform this split."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Correcting a few things here:\n",
    "sklearn v0.21.2 uses model_selection for train_test_split\n",
    "\n",
    "'income_raw' is our data - not 'income'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>age</th>\n",
       "      <th>education-num</th>\n",
       "      <th>capital-gain</th>\n",
       "      <th>capital-loss</th>\n",
       "      <th>hours-per-week</th>\n",
       "      <th>workclass_ Federal-gov</th>\n",
       "      <th>workclass_ Local-gov</th>\n",
       "      <th>workclass_ Private</th>\n",
       "      <th>workclass_ Self-emp-inc</th>\n",
       "      <th>workclass_ Self-emp-not-inc</th>\n",
       "      <th>...</th>\n",
       "      <th>native-country_ Portugal</th>\n",
       "      <th>native-country_ Puerto-Rico</th>\n",
       "      <th>native-country_ Scotland</th>\n",
       "      <th>native-country_ South</th>\n",
       "      <th>native-country_ Taiwan</th>\n",
       "      <th>native-country_ Thailand</th>\n",
       "      <th>native-country_ Trinadad&amp;Tobago</th>\n",
       "      <th>native-country_ United-States</th>\n",
       "      <th>native-country_ Vietnam</th>\n",
       "      <th>native-country_ Yugoslavia</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>27005</th>\n",
       "      <td>0.493151</td>\n",
       "      <td>0.266667</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.397959</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>...</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6482</th>\n",
       "      <td>0.369863</td>\n",
       "      <td>0.800000</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.397959</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>...</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>16984</th>\n",
       "      <td>0.465753</td>\n",
       "      <td>0.400000</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.448980</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>...</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>25450</th>\n",
       "      <td>0.287671</td>\n",
       "      <td>0.600000</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.244898</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>...</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>666</th>\n",
       "      <td>0.452055</td>\n",
       "      <td>0.533333</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.418367</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>...</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>5 rows × 103 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "            age  education-num  capital-gain  capital-loss  hours-per-week  \\\n",
       "27005  0.493151       0.266667           0.0           0.0        0.397959   \n",
       "6482   0.369863       0.800000           0.0           0.0        0.397959   \n",
       "16984  0.465753       0.400000           0.0           0.0        0.448980   \n",
       "25450  0.287671       0.600000           0.0           0.0        0.244898   \n",
       "666    0.452055       0.533333           0.0           0.0        0.418367   \n",
       "\n",
       "       workclass_ Federal-gov  workclass_ Local-gov  workclass_ Private  \\\n",
       "27005                       0                     0                   1   \n",
       "6482                        0                     0                   1   \n",
       "16984                       0                     0                   0   \n",
       "25450                       0                     0                   1   \n",
       "666                         0                     1                   0   \n",
       "\n",
       "       workclass_ Self-emp-inc  workclass_ Self-emp-not-inc  ...  \\\n",
       "27005                        0                            0  ...   \n",
       "6482                         0                            0  ...   \n",
       "16984                        0                            1  ...   \n",
       "25450                        0                            0  ...   \n",
       "666                          0                            0  ...   \n",
       "\n",
       "       native-country_ Portugal  native-country_ Puerto-Rico  \\\n",
       "27005                         0                            0   \n",
       "6482                          0                            0   \n",
       "16984                         0                            0   \n",
       "25450                         0                            0   \n",
       "666                           0                            0   \n",
       "\n",
       "       native-country_ Scotland  native-country_ South  \\\n",
       "27005                         0                      0   \n",
       "6482                          0                      0   \n",
       "16984                         0                      0   \n",
       "25450                         0                      0   \n",
       "666                           0                      0   \n",
       "\n",
       "       native-country_ Taiwan  native-country_ Thailand  \\\n",
       "27005                       0                         0   \n",
       "6482                        0                         0   \n",
       "16984                       0                         0   \n",
       "25450                       0                         0   \n",
       "666                         0                         0   \n",
       "\n",
       "       native-country_ Trinadad&Tobago  native-country_ United-States  \\\n",
       "27005                                0                              1   \n",
       "6482                                 0                              1   \n",
       "16984                                0                              1   \n",
       "25450                                0                              1   \n",
       "666                                  0                              1   \n",
       "\n",
       "       native-country_ Vietnam  native-country_ Yugoslavia  \n",
       "27005                        0                           0  \n",
       "6482                         0                           0  \n",
       "16984                        0                           0  \n",
       "25450                        0                           0  \n",
       "666                          0                           0  \n",
       "\n",
       "[5 rows x 103 columns]"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "features_final.sample(frac=1).head(5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Training set has 36177 samples.\n",
      "Testing set has 9045 samples.\n"
     ]
    }
   ],
   "source": [
    "# Import train_test_split\n",
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "# Split the 'features' and 'income' data into training and testing sets\n",
    "X_train, X_test, y_train, y_test = train_test_split(features_final, \n",
    "                                                    income_raw, \n",
    "                                                    test_size = 0.2, \n",
    "                                                    random_state = 0)\n",
    "\n",
    "# Show the results of the split\n",
    "print(\"Training set has {} samples.\".format(X_train.shape[0]))\n",
    "print(\"Testing set has {} samples.\".format(X_test.shape[0]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "----\n",
    "## Evaluating Model Performance\n",
    "In this section, we will investigate four different algorithms, and determine which is best at modeling the data. Three of these algorithms will be supervised learners of your choice, and the fourth algorithm is known as a *naive predictor*."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Metrics and the Naive Predictor\n",
    "*CharityML*, equipped with their research, knows individuals that make more than \\$50,000 are most likely to donate to their charity. Because of this, *CharityML* is particularly interested in predicting who makes more than \\$50,000 accurately. It would seem that using **accuracy** as a metric for evaluating a particular model's performace would be appropriate. Additionally, identifying someone that *does not* make more than \\$50,000 as someone who does would be detrimental to *CharityML*, since they are looking to find individuals willing to donate. Therefore, a model's ability to precisely predict those that make more than \\$50,000 is *more important* than the model's ability to **recall** those individuals. We can use **F-beta score** as a metric that considers both precision and recall:\n",
    "\n",
    "$$ F_{\\beta} = (1 + \\beta^2) \\cdot \\frac{precision \\cdot recall}{\\left( \\beta^2 \\cdot precision \\right) + recall} $$\n",
    "\n",
    "In particular, when $\\beta = 0.5$, more emphasis is placed on precision. This is called the **F$_{0.5}$ score** (or F-score for simplicity).\n",
    "\n",
    "Looking at the distribution of classes (those who make at most \\$50,000, and those who make more), it's clear most individuals do not make more than \\$50,000. This can greatly affect **accuracy**, since we could simply say *\"this person does not make more than \\$50,000\"* and generally be right, without ever looking at the data! Making such a statement would be called **naive**, since we have not considered any information to substantiate the claim. It is always important to consider the *naive prediction* for your data, to help establish a benchmark for whether a model is performing well. That been said, using that prediction would be pointless: If we predicted all people made less than \\$50,000, *CharityML* would identify no one as donors. \n",
    "\n",
    "\n",
    "#### Note: Recap of accuracy, precision, recall\n",
    "\n",
    "** Accuracy ** measures how often the classifier makes the correct prediction. It’s the ratio of the number of correct predictions to the total number of predictions (the number of test data points).\n",
    "\n",
    "** Precision ** tells us what proportion of messages we classified as spam, actually were spam.\n",
    "It is a ratio of true positives(words classified as spam, and which are actually spam) to all positives(all words classified as spam, irrespective of whether that was the correct classificatio), in other words it is the ratio of\n",
    "\n",
    "`[True Positives/(True Positives + False Positives)]`\n",
    "\n",
    "** Recall(sensitivity)** tells us what proportion of messages that actually were spam were classified by us as spam.\n",
    "It is a ratio of true positives(words classified as spam, and which are actually spam) to all the words that were actually spam, in other words it is the ratio of\n",
    "\n",
    "`[True Positives/(True Positives + False Negatives)]`\n",
    "\n",
    "For classification problems that are skewed in their classification distributions like in our case, for example if we had a 100 text messages and only 2 were spam and the rest 98 weren't, accuracy by itself is not a very good metric. We could classify 90 messages as not spam(including the 2 that were spam but we classify them as not spam, hence they would be false negatives) and 10 as spam(all 10 false positives) and still get a reasonably good accuracy score. For such cases, precision and recall come in very handy. These two metrics can be combined to get the F1 score, which is weighted average(harmonic mean) of the precision and recall scores. This score can range from 0 to 1, with 1 being the best possible F1 score(we take the harmonic mean as we are dealing with ratios)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Question 1 - Naive Predictor Performace\n",
    "* If we chose a model that always predicted an individual made more than $50,000, what would  that model's accuracy and F-score be on this dataset? You must use the code cell below and assign your results to `'accuracy'` and `'fscore'` to be used later.\n",
    "\n",
    "** Please note ** that the the purpose of generating a naive predictor is simply to show what a base model without any intelligence would look like. In the real world, ideally your base model would be either the results of a previous model or could be based on a research paper upon which you are looking to improve. When there is no benchmark model set, getting a result better than random choice is a place you could start from.\n",
    "\n",
    "** HINT: ** \n",
    "\n",
    "* When we have a model that always predicts '1' (i.e. the individual makes more than 50k) then our model will have no True Negatives(TN) or False Negatives(FN) as we are not making any negative('0' value) predictions. Therefore our Accuracy in this case becomes the same as our Precision(True Positives/(True Positives + False Positives)) as every prediction that we have made with value '1' that should have '0' becomes a False Positive; therefore our denominator in this case is the total number of records we have in total. \n",
    "* Our Recall score(True Positives/(True Positives + False Negatives)) in this setting becomes 1 as we have no False Negatives."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "TP = np.sum(income_raw)\n",
    "FP = income_raw.count() - TP\n",
    "TN = 0\n",
    "FN = 0"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Naive Predictor: [Accuracy score: 0.2478, F-score: 0.2917]\n"
     ]
    }
   ],
   "source": [
    "'''\n",
    "TP = np.sum(income) # Counting the ones as this is the naive case. Note that 'income' is the 'income_raw' data \n",
    "encoded to numerical values done in the data preprocessing step.\n",
    "FP = income.count() - TP # Specific to the naive case\n",
    "\n",
    "TN = 0 # No predicted negatives in the naive case\n",
    "FN = 0 # No predicted negatives in the naive case\n",
    "'''\n",
    "# TODO: Calculate accuracy, precision and recall\n",
    "accuracy = (TP + TN) / (FP + FN + TP + TN)\n",
    "recall = TP / (TP + FN)\n",
    "precision = TP / (TP + FP)\n",
    "\n",
    "# TODO: Calculate F-score using the formula above for beta = 0.5 and correct values for precision and recall.\n",
    "fscore = (1 + (0.5) ** 2) * ((precision * recall) / (((0.5) ** 2 * precision) + recall))\n",
    "\n",
    "# Print the results \n",
    "print(\"Naive Predictor: [Accuracy score: {:.4f}, F-score: {:.4f}]\".format(accuracy, fscore))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###  Supervised Learning Models\n",
    "**The following are some of the supervised learning models that are currently available in** [`scikit-learn`](http://scikit-learn.org/stable/supervised_learning.html) **that you may choose from:**\n",
    "- Gaussian Naive Bayes (GaussianNB)\n",
    "- Decision Trees\n",
    "- Ensemble Methods (Bagging, AdaBoost, Random Forest, Gradient Boosting)\n",
    "- K-Nearest Neighbors (KNeighbors)\n",
    "- Stochastic Gradient Descent Classifier (SGDC)\n",
    "- Support Vector Machines (SVM)\n",
    "- Logistic Regression"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Question 2 - Model Application\n",
    "List three of the supervised learning models above that are appropriate for this problem that you will test on the census data. For each model chosen\n",
    "\n",
    "- Describe one real-world application in industry where the model can be applied. \n",
    "- What are the strengths of the model; when does it perform well?\n",
    "- What are the weaknesses of the model; when does it perform poorly?\n",
    "- What makes this model a good candidate for the problem, given what you know about the data?\n",
    "\n",
    "** HINT: **\n",
    "\n",
    "Structure your answer in the same format as above^, with 4 parts for each of the three models you pick. Please include references with your answer."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Naive Bayes (Gaussian)\n",
    "\n",
    "## Applications\n",
    "Naive Bayes has many applications in the real-world. It is very popular in the Medical industry - which itself is a huge area and has many applications where it can be applied.\n",
    "\n",
    "From my own research in my MSc, I used the results of [1]. Here Naive Bayes was used to categorically identify phage virion proteins from features such as amino acid composition and nucleo-capsid thickness. My own research was motivated in trying to understand the numerical mathematical dynamics of these features. The classifier had excellent results in this case - and this raised further questions about the dynamics of the features of viral proteins over time which were (and still) largely unknown. **This was an excellent use case of machine learning** to identify viral proteins from seemingly healthy ones - but mathematically was interesting as current numerical methods were slow, and the dyanmics of the equations were unknown. The classifier can be used to save a lot of time practically but mathematically raised more questions about what was happening to the current numerical models used. \n",
    "The model also has extensive usage in text classification (such as the Spam example used in this nano-degree), and can also be used for predicting and recommendations if someone or something will do something (assuming the features are largely independent).\n",
    "\n",
    "## Advantages\n",
    "The model performs very well in problems where the features are largely conditionally independent from each other. This means that we are assuming that features do not depend on each other (E.g if we considered height and weight we would exepct them to correlate, taller people would weigh more than shorter people, but weight could still be conditionally independent as there are other factors to consider in how heavy someone is).\n",
    "Because of this this means that the model will converge much quicker than other methods (such as linear regression) - in practice this means we can use less training data. We can use the model for both discrete and continuous data. [2]\n",
    "\n",
    "## Disadvatanges\n",
    "The model also has disadvantages. When the featurees are dependent the conditional independence does not hold: in such a case computing\n",
    "\n",
    "$P(X|C_i)$\n",
    "\n",
    "can be computationally expensive if we cannot leverage the conditional probability condition\n",
    "\n",
    "$P(X|C_i) = P(x_1 | C_i) * P(x_2 | C_i) * ... * P(x_N | C_i)$\n",
    "\n",
    "Interestingly, it has been shown that Naive Bayes (Gaussian) can be used and will even perform well even when this independence assumption does not hold. [3] accredits this to the underlying zero-loss function used in the algorithm - which calculates the error as the number of incorrect predictions. The zero-loss function does not penalise inaccurate probability estimates as long as the highest probability is assigned to the correct class [4]. In addition - special care must be taken if using this model **for non indpendent features** in the continuous case - as the model minimises the expected loss by maximising the posterior probability $P(C_i|X)$. Care must be taken when considering the zero-loss function, as integrating a discrete indicator over a probability density function (for a continuous case) would always be zero. Functions such as the Dirac delta function can be applied in this case [5]. There is much more research into why this model performs well when this condition does not hold and can be seen in [6].\n",
    "Although the model is a very good classifier - it does fall short on estimating. This means we can use the model to evaluate future people given their features - but the probability that someone belongs to either class is not a good indicator. This means that future modelling will require all our data to classify someone, using the probabilities that someone belongs in either class is not a practical use for this model.\n",
    "\n",
    "\n",
    "\n",
    "## Reasoning\n",
    "Based on the above I believe this model is a good candidate.\n",
    "* We have features that appear at face value to not closely depend on each other - by this I mean no features stand out as largely dependending on another. Age is largeley independent to Ethnicity. Although there could be some dependence on the Capital Gains or Loss with respect to the other features - further investigation would only be warrented in my opinion if the output of the model warrants it.\n",
    "* We want to know categorically if someone earns above or below \\$50k"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Decision Trees\n",
    "\n",
    "## Applications\n",
    "\n",
    "Decision trees have many applications in industry:\n",
    "* One example is in customer relations and reccomendations. Decision trees can be used to analyse how customers interact online and then analyse their usage to provide recomendations based on this information. [10] applied decision trees to investigate customers shopping habits online - by classing people into two categories, 1) Those who rarely used it and 2) Those who shopped online frequently. The result of the decision tree showed that the time it takes customers to complete a transaction and how urgently the item needed were the most important factors in whether a customer shopped online or not. \n",
    "\n",
    "## Advantages\n",
    "\n",
    "Decision trees have many advantages when being considered as a classifier\n",
    "\n",
    "* They perform well with missing data points. Other methods require the removal of data if any features are missing - which is inefficient and if not careful can affect the validity of your data. Decision trees work around this by classifying missing values as a seperate category - where other categories can be used to analyise the missing categories. Or you can build a decision tree to categorically predict the missing values based on the data as a preliminary step before using the model to obtain your results. [7]\n",
    "* They have excellent use in determining whether or not features are relatively important to one another. By using a decision tree you can find how important a feature is by removing it from the tree and validating the result against the feature included. This is a popular method employed to finding importance of features - I myself have used such methods when considering the importance of states in Markov Chains. By removing a state one by one - you can find the relative importance of a state relative to the other states. This can tell you lots of information about how important each state is. [8]\n",
    "* Unlike a Naive Bayes classifier, Decision Trees can be used to predict values. The resulting probabilites from the model can be used to predict whether or not someone will belong to a class without the need to run the model with the new data included each time. [7]\n",
    "* They are excellent when using categorical data. If you have a category that has many values under it a decision tree is a very good model in deciding how these categories can be split or grouped together. They can break the category down into a more manageable group. We can see in the cell below that the Occuption column has 14 values present. A decision tree can handle this (and much higher counts) with ease. [7]\n",
    "\n",
    "## Disadvantages\n",
    "* Although decision trees are excellent predictors - if the data changes or evolves over time (say the number of people belonging to a specific job goes up) then the model needs to be redrawn to account for this. This can be accounted for by using ensemble methods in tandem with a decision tree [9]\n",
    "* The hyperparamters for the model are very important - popular hyperparamters to consider are max_depth which can be used to control over-fitting, min_samples_split and min_samples_leaf which consider how many samples are needed to split or be defined as a leaf and min_weight_fraction_leaf when considering weighted samples. The overabundance and consideration of the hyperparameters means there is a need to understand your data before considering values for these. Methods we have seen such as grid search can aid in the process when we have many to consider.\n",
    "* Decision trees are sensitive if a category is dominated by a particular value. Careful consideration should be taken if this is the case and balancing the data can help. Methods used to balance could include resampling (adding copies of under respresented values) or under sampling (removal of some of the dominant class values. We should also pay close attention to the Precision, Recall and F1 Score when evaluating the model - as this can aid in selection. \n",
    "\n",
    "## Reasoning\n",
    "Based on the above I believe Decision Trees are a good candidate for our problem.\n",
    "* We have a single classification problem which lends itself well to decision trees. \n",
    "* We have categories which contain many classes (such as occupation) - we know decision trees can be used to great affect with this kind of data.\n",
    "* Easy to visulise and explain - justifying the model can be easily done with scikitlearn. We can plot the tree which will show us the categories and their values used to split at each node.\n",
    "* Categorical data - although we have accounted for categories with pd.get_dummies(), the model lends itself well to categorical data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Number of unique values in occupation column is 14\n"
     ]
    }
   ],
   "source": [
    "import collections\n",
    "occupation_cat_count = collections.Counter(data['occupation'].unique())\n",
    "occupation_cat_count = sum(occupation_cat_count.values())\n",
    "print(f'Number of unique values in occupation column is {occupation_cat_count}')\n",
    "# sum(collections.Counter(encoded).values())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# SVMs\n",
    "\n",
    "## Applications\n",
    "\n",
    "An application of a support vector machine in industry is:\n",
    "* SVMs have a wide application in image recognition and classification problems. When applied to image recognition each feature of the data set corresponds to a single image pixel. An SVM can be used to classify these pixels into which category they belong to based on their features (such as edge, colour or shape). In [11] SVMs were used on microscopic images of cells to detect the location of the cell nucleus. Manual location of the cell nuclei is a long and arduous process especially when considering there may be many of thousands of images to consider. A SVM can be used to learn what part of on image corresponds to a nucleus, and what part does not and was used to great effect in this case - managing to locate the neclei across multiple scales and stains successfully. Their usage is not limited to the medical sector and have many practical uses such as in geography in identifying areas of land suitable for cultivation and farming [12]\n",
    "\n",
    "## Advantages\n",
    "\n",
    "SVMs have many advantages and are a powerful classification method\n",
    "* They integerate well with kernel methods - this means that SVMs are very versatile. You can employ different Kernels when considering how you will map your points to a higher dimensional space and even write your own kernels if your data requires it.\n",
    "* When compared to linear regression methods SVMs are more robust due to the maximising of the margin. With the hyperparamter C you can control how much an incorrectly classified point is penalised.\n",
    "* They are excellent at non linear boundaries due to the kernels they employ. Although it is possible to employ kernels in other methods such as regression SVMs in scikitlearn have the kernels already implemented and it is much easier to use the \"kernel trick\" (the kernel trick using the fact that you can generalise kernels in higher dimensions by using the dot product in the original space and using a generalisation of the corresponding Kernel. [14] has an excellent write up on how this used for the Linear kernel) \n",
    "\n",
    "## Disadvantages\n",
    "Although SVMs are powerful in classification problems there are disadvantages we must consider when using them\n",
    "* Choosing a kernel function is not an easy task and can often be the main barrier to the success of the model. Although scikitlearn offers several kernals such as the linear kernel and the popular Radial Basis Function kernel or RBF. The RBF is often used and uses the squared euclidean distance between two points. The feature space of the kernel has an infinite number of dimensions [13] and this means the kernel can be used to project points any higher dimension - although this comes at a huge computational cost. \n",
    "* The model has a long training time on large data sets and this is due to several reasons\n",
    "    * The C parameter is a hyperparameter used to penalise misclassified points - the higher this is, the more accurate the results but the slower the training process is.\n",
    "    * The general method is of $O(n^3)$ (where $O$ is big Oh notation) - meaning it has to run a number of operations proportional to $n^3$. With 10,000 data points this means the number of operations is proportional to $10^{12}$ - a huge number which can affect our computational time greatly.\n",
    "    \n",
    "## Reasoning\n",
    "Based on the above I believe SVMs can be used for our model\n",
    "* We have a classification problem which is well suited to SVMs.\n",
    "* They are very good when we have a large number of features and after transforming our category values into feature values we know we have 98 features for our category data.\n",
    "* With careful selection of our C hyperparamter and a suitable kernel we can obtain good boundaries for our dataset."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# References\n",
    "[1] https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3671239/\n",
    "\n",
    "[2] https://www.slideshare.net/ashrafmath/naive-bayes-15644818\n",
    "\n",
    "[3] https://www.cs.waikato.ac.nz/~eibe/pubs/nbr.pdf\n",
    "\n",
    "[4] https://link.springer.com/article/10.1023/A:1009778005914\n",
    "\n",
    "[5] https://en.wikipedia.org/wiki/Dirac_delta_function\n",
    "\n",
    "[6] https://www.cs.unb.ca/~hzhang/publications/FLAIRS04ZhangH.pdf\n",
    "\n",
    "[7] https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4466856/\n",
    "\n",
    "[8] https://www.analyticsvidhya.com/blog/2018/01/channel-attribution-modeling-using-markov-chains-in-r/\n",
    "\n",
    "[9] https://scikit-learn.org/stable/modules/tree.html\n",
    "\n",
    "[10] https://www.sciencedirect.com/science/article/pii/S0957417406001825\n",
    "\n",
    "[11] https://link.springer.com/article/10.1007/s00138-010-0275-y\n",
    "\n",
    "[12] https://www.ncbi.nlm.nih.gov/pubmed/20052093\n",
    "\n",
    "[13] https://en.wikipedia.org/wiki/Radial_basis_function_kernel\n",
    "\n",
    "[14] https://www.quora.com/What-is-the-kernel-trick|"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Answer: **"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Implementation - Creating a Training and Predicting Pipeline\n",
    "To properly evaluate the performance of each model you've chosen, it's important that you create a training and predicting pipeline that allows you to quickly and effectively train models using various sizes of training data and perform predictions on the testing data. Your implementation here will be used in the following section.\n",
    "In the code block below, you will need to implement the following:\n",
    " - Import `fbeta_score` and `accuracy_score` from [`sklearn.metrics`](http://scikit-learn.org/stable/modules/classes.html#sklearn-metrics-metrics).\n",
    " - Fit the learner to the sampled training data and record the training time.\n",
    " - Perform predictions on the test data `X_test`, and also on the first 300 training points `X_train[:300]`.\n",
    "   - Record the total prediction time.\n",
    " - Calculate the accuracy score for both the training subset and testing set.\n",
    " - Calculate the F-score for both the training subset and testing set.\n",
    "   - Make sure that you set the `beta` parameter!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import fbeta_score, accuracy_score\n",
    "\n",
    "def train_predict(learner, sample_size, X_train, y_train, X_test, y_test): \n",
    "    '''\n",
    "    inputs:\n",
    "       - learner: the learning algorithm to be trained and predicted on\n",
    "       - sample_size: the size of samples (number) to be drawn from training set\n",
    "       - X_train: features training set\n",
    "       - y_train: income training set\n",
    "       - X_test: features testing set\n",
    "       - y_test: income testing set\n",
    "    '''\n",
    "    beta = 0.5\n",
    "    results = {}\n",
    "    \n",
    "    # TODO: Fit the learner to the training data using slicing with 'sample_size' using .fit(training_features[:], training_labels[:])\n",
    "    start = time() # Get start time\n",
    "    learner = learner.fit(X_train[:sample_size], y_train[:sample_size])\n",
    "    end = time() # Get end time\n",
    "    \n",
    "    # TODO: Calculate the training time\n",
    "    results['train_time'] = end - start\n",
    "        \n",
    "    # TODO: Get the predictions on the test set(X_test),\n",
    "    #       then get predictions on the first 300 training samples(X_train) using .predict()\n",
    "    start = time() # Get start time\n",
    "    predictions_test = learner.predict(X_test)\n",
    "    predictions_train = learner.predict(X_train[:300])\n",
    "    end = time() # Get end time\n",
    "    \n",
    "    # TODO: Calculate the total prediction time\n",
    "    results['pred_time'] = end - start\n",
    "            \n",
    "    # TODO: Compute accuracy on the first 300 training samples which is y_train[:300]\n",
    "    results['acc_train'] = accuracy_score(y_train[:300], predictions_train)\n",
    "        \n",
    "    # TODO: Compute accuracy on test set using accuracy_score()\n",
    "    results['acc_test'] = accuracy_score(y_test, predictions_test)\n",
    "    \n",
    "    # TODO: Compute F-score on the the first 300 training samples using fbeta_score()\n",
    "    results['f_train'] = fbeta_score(y_train[:300], predictions_train, beta)\n",
    "        \n",
    "    # TODO: Compute F-score on the test set which is y_test\n",
    "    results['f_test'] = fbeta_score(y_test, predictions_test, beta)\n",
    "       \n",
    "    # Success\n",
    "    print(\"{} trained on {} samples.\".format(learner.__class__.__name__, sample_size))\n",
    "        \n",
    "    # Return the results\n",
    "    return results"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Implementation: Initial Model Evaluation\n",
    "In the code cell, you will need to implement the following:\n",
    "- Import the three supervised learning models you've discussed in the previous section.\n",
    "- Initialize the three models and store them in `'clf_A'`, `'clf_B'`, and `'clf_C'`.\n",
    "  - Use a `'random_state'` for each model you use, if provided.\n",
    "  - **Note:** Use the default settings for each model — you will tune one specific model in a later section.\n",
    "- Calculate the number of records equal to 1%, 10%, and 100% of the training data.\n",
    "  - Store those values in `'samples_1'`, `'samples_10'`, and `'samples_100'` respectively.\n",
    "\n",
    "**Note:** Depending on which algorithms you chose, the following implementation may take some time to run!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "13181    0\n",
       "10342    0\n",
       "20881    0\n",
       "24972    1\n",
       "43867    0\n",
       "Name: income, dtype: int32"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "y_train.head(5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "36177 3617 361\n",
      "\n",
      "0 361\n",
      "GaussianNB trained on 361 samples.\n",
      "1 3617\n",
      "GaussianNB trained on 3617 samples.\n",
      "2 36177\n",
      "GaussianNB trained on 36177 samples.\n",
      "0 361\n",
      "DecisionTreeClassifier trained on 361 samples.\n",
      "1 3617\n",
      "DecisionTreeClassifier trained on 3617 samples.\n",
      "2 36177\n",
      "DecisionTreeClassifier trained on 36177 samples.\n",
      "0 361\n",
      "SVC trained on 361 samples.\n",
      "1 3617\n",
      "SVC trained on 3617 samples.\n",
      "2 36177\n",
      "SVC trained on 36177 samples.\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 52052 characters]\n",
      "text/plain": [
       "<Figure size 792x504 with 6 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "# TODO: Import the three supervised learning models from sklearn\n",
    "from sklearn.naive_bayes import GaussianNB\n",
    "from sklearn.tree import DecisionTreeClassifier\n",
    "from sklearn.svm import SVC\n",
    "\n",
    "# TODO: Initialize the three models\n",
    "clf_A = GaussianNB()\n",
    "clf_B = DecisionTreeClassifier()\n",
    "clf_C = SVC()\n",
    "\n",
    "# TODO: Calculate the number of samples for 1%, 10%, and 100% of the training data\n",
    "# HINT: samples_100 is the entire training set i.e. len(y_train)\n",
    "# HINT: samples_10 is 10% of samples_100 (ensure to set the count of the values to be `int` and not `float`)\n",
    "# HINT: samples_1 is 1% of samples_100 (ensure to set the count of the values to be `int` and not `float`)\n",
    "samples_100 = int(X_train.shape[0])\n",
    "samples_10 = int(samples_100 * 0.1)\n",
    "samples_1 = int(samples_100 * 0.01)\n",
    "print(samples_100, samples_10, samples_1)\n",
    "print()\n",
    "# Collect results on the learners\n",
    "results = {}\n",
    "for clf in [clf_A, clf_B, clf_C]:\n",
    "    clf_name = clf.__class__.__name__\n",
    "    results[clf_name] = {}\n",
    "    for i, samples in enumerate([samples_1, samples_10, samples_100]):\n",
    "        print(i, samples)\n",
    "        results[clf_name][i] = \\\n",
    "        train_predict(clf, samples, X_train, y_train, X_test, y_test)\n",
    "# Run metrics visualization for the three supervised learning models chosen\n",
    "vs.evaluate(results, accuracy, fscore)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "----\n",
    "## Improving Results\n",
    "In this final section, you will choose from the three supervised learning models the *best* model to use on the student data. You will then perform a grid search optimization for the model over the entire training set (`X_train` and `y_train`) by tuning at least one parameter to improve upon the untuned model's F-score. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Question 3 - Choosing the Best Model\n",
    "\n",
    "* Based on the evaluation you performed earlier, in one to two paragraphs, explain to *CharityML* which of the three models you believe to be most appropriate for the task of identifying individuals that make more than \\$50,000. \n",
    "\n",
    "** HINT: ** \n",
    "Look at the graph at the bottom left from the cell above(the visualization created by `vs.evaluate(results, accuracy, fscore)`) and check the F score for the testing set when 100% of the training set is used. Which model has the highest score? Your answer should include discussion of the:\n",
    "* metrics - F score on the testing when 100% of the training data is used, \n",
    "* prediction/training time\n",
    "* the algorithm's suitability for the data."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Answer: **\n",
    "\n",
    "From the above graphs we can see that when working on our training data (which is a subset of the entire dataset used exlusively for training our model) that the Decision Tree classifier appears to be overfitting. We can see this because the accuracy and F-score are very very close to one for all 3 splits of our data. This most likely suggests our model is overfitting and it will not generalise well when we introduce the rest of the data to try predict the result. \n",
    "\n",
    "Looking at a Support vector machine in the above graphs we can see that for the testing data (and the training data) that this model appears to show some promise. Accuracy for the SVM on 100% of the data appears to be around 80% with the default values. For the fscore we can see that the value is around 65-70% for 100% of the data. This is a good indicator that with some further tuning of the model - we should be able to increase this accuracy further.\n",
    "\n",
    "The training time for a SVM is the highest out of all of the 3 models chosen. Indeed with 100% of the data used only SVM is showing any significant time needed to train a model. This is something we will have to work with and be careful with. If the model takes a significant amount of time to train we could look to the other two models. If we chose a decision tree we would need to be careful that we do not overfit and put some work into tuning the hyperparameters for the model. \n",
    "\n",
    "We discuss below the algorithms suitability and how it works in simple terms as to the reason why we are choosing a SVM."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Question 4 - Describing the Model in Layman's Terms\n",
    "\n",
    "* In one to two paragraphs, explain to *CharityML*, in layman's terms, how the final model chosen is supposed to work. Be sure that you are describing the major qualities of the model, such as how the model is trained and how the model makes a prediction. Avoid using advanced mathematical jargon, such as describing equations.\n",
    "\n",
    "** HINT: **\n",
    "\n",
    "When explaining your model, if using external resources please include all citations."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Answer: ** \n",
    "\n",
    "A support vector machine is a supervised learning algorithm that can be used in regression, but it really shines when used as a classifier. As we are wanting to classify whether someone earns \\$50k or not we have a classification problem, which a support vector machine lends itself well to.\n",
    "\n",
    "\n",
    "The model works by classifying points. If we had 2 features (i.e if we took age and education level), converted them to arbitrary numbers and plotted them on a grid, we could colour each point red or green: red being they earn <50k and green meaning they earn >50k. In this plot a support vector machine would attempt to find a \"line\" that seperates the data.\n",
    "\n",
    "In our case we have many features (much more than 2), in this case visualising a plot is impossible, but the method remains the same just extended to higher dimensions. In this case we are not finding a line, rather a hyperplane (a higher dimensional line) that will seperate the points.\n",
    "\n",
    "When finding a hyperplane the model uses a margin to help optimise the model. We can think of the margin as the distance from a point to the seperating line (or hyperplane). If this margin is high, then this means there is a good distance from each classified point to the seperating hyperplane. If this margin is small, this means the points are close to the hyperplane - this means we are more likely to make a mistake in classifying a point. The aim of the method is to find the best line. It knows what the best is by maxmising this distance margin. \n",
    "\n",
    "A support vector machine uses a technique called the kernel trick to find this hyperplane. What this means in practice is that we can find very non linear hyperplanes to seperate our data. When compared to methods such as regression which do something similar, it means a support vector machine is much more useful in a non-linear seperation problem. If we observed our data in the 2 dimensional example as above, it might be obvious from the graph that a circle might seperate our data and classify points accurately. A SVM would allow us to do this, a regression line would not. \n",
    "\n",
    "To make a prediction the model will take a data point we give it, and \"plot\" it. It would then read from this what it believes the point is (what region it has been plotted in) based on the data we gave the model to train using the found hyperplane. This is how it makes a prediction\n",
    "\n",
    "** All information here is taken from this Udacity course - I have not cited it as per https://udacity.zendesk.com/hc/en-us/articles/360001451091-What-is-plagiarism-"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Implementation: Model Tuning\n",
    "Fine tune the chosen model. Use grid search (`GridSearchCV`) with at least one important parameter tuned with at least 3 different values. You will need to use the entire training set for this. In the code cell below, you will need to implement the following:\n",
    "- Import [`sklearn.grid_search.GridSearchCV`](http://scikit-learn.org/0.17/modules/generated/sklearn.grid_search.GridSearchCV.html) and [`sklearn.metrics.make_scorer`](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.make_scorer.html).\n",
    "- Initialize the classifier you've chosen and store it in `clf`.\n",
    " - Set a `random_state` if one is available to the same state you set before.\n",
    "- Create a dictionary of parameters you wish to tune for the chosen model.\n",
    " - Example: `parameters = {'parameter' : [list of values]}`.\n",
    " - **Note:** Avoid tuning the `max_features` parameter of your learner if that parameter is available!\n",
    "- Use `make_scorer` to create an `fbeta_score` scoring object (with $\\beta = 0.5$).\n",
    "- Perform grid search on the classifier `clf` using the `'scorer'`, and store it in `grid_obj`.\n",
    "- Fit the grid search object to the training data (`X_train`, `y_train`), and store it in `grid_fit`.\n",
    "\n",
    "**Note:** Depending on the algorithm chosen and the parameter list, the following implementation may take some time to run!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "SVC(C=0.01, cache_size=200, class_weight=None, coef0=0.0,\n",
       "  decision_function_shape='ovr', degree=3, gamma=0.1, kernel='rbf',\n",
       "  max_iter=-1, probability=False, random_state=None, shrinking=True,\n",
       "  tol=0.001, verbose=False)"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from sklearn.model_selection import GridSearchCV\n",
    "from sklearn.metrics import make_scorer\n",
    "\n",
    "clf = SVC(C=0.01, gamma=0.1, kernel='rbf')\n",
    "\n",
    "clf.fit(X_train, y_train)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [],
   "source": [
    "predictions_test = clf.predict(X_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.8245439469320066"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "accuracy_score(y_test, predictions_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Unoptimized model\n",
      "------\n",
      "Accuracy score on testing data: 0.8371\n",
      "F-score on testing data: 0.6745\n",
      "\n",
      "Optimized Model\n",
      "------\n",
      "Final accuracy score on the testing data: 0.8392\n",
      "Final F-score on the testing data: 0.6803\n"
     ]
    }
   ],
   "source": [
    "# TODO: Import 'GridSearchCV', 'make_scorer', and any other necessary libraries\n",
    "from sklearn.model_selection import GridSearchCV\n",
    "from sklearn.metrics import make_scorer\n",
    "\n",
    "# TODO: Initialize the classifier\n",
    "clf = SVC()\n",
    "\n",
    "# TODO: Create the parameters list you wish to tune, using a dictionary if needed.\n",
    "# HINT: parameters = {'parameter_1': [value1, value2], 'parameter_2': [value1, value2]}\n",
    "parameters = {'C': [0.001, 0.01, 0.1, 1, 10, 20, 30],\n",
    "              'gamma': [0.001, 0.01, 0.1, 1, 2, 5],\n",
    "              'kernel': ['linear', 'rbf']}\n",
    "\n",
    "# TODO: Make an fbeta_score scoring object using make_scorer()\n",
    "scorer = make_scorer(fbeta_score, beta=0.5)\n",
    "\n",
    "# TODO: Perform grid search on the classifier using 'scorer' as the scoring method using GridSearchCV()\n",
    "grid_obj = GridSearchCV(clf, param_grid=parameters, scoring=scorer, n_jobs=-1)\n",
    "\n",
    "# TODO: Fit the grid search object to the training data and find the optimal parameters using fit()\n",
    "grid_fit = grid_obj.fit(X_train, y_train)\n",
    "\n",
    "# Get the estimator\n",
    "best_clf = grid_fit.best_estimator_\n",
    "\n",
    "# Make predictions using the unoptimized and model\n",
    "predictions = (clf.fit(X_train, y_train)).predict(X_test)\n",
    "best_predictions = best_clf.predict(X_test)\n",
    "\n",
    "# Report the before-and-afterscores\n",
    "print(\"Unoptimized model\\n------\")\n",
    "print(\"Accuracy score on testing data: {:.4f}\".format(accuracy_score(y_test, predictions)))\n",
    "print(\"F-score on testing data: {:.4f}\".format(fbeta_score(y_test, predictions, beta = 0.5)))\n",
    "print(\"\\nOptimized Model\\n------\")\n",
    "print(\"Final accuracy score on the testing data: {:.4f}\".format(accuracy_score(y_test, best_predictions)))\n",
    "print(\"Final F-score on the testing data: {:.4f}\".format(fbeta_score(y_test, best_predictions, beta = 0.5)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "SVC(C=0.01, cache_size=200, class_weight=None, coef0=0.0,\n",
       "  decision_function_shape='ovr', degree=3, gamma=0.001, kernel='linear',\n",
       "  max_iter=-1, probability=False, random_state=None, shrinking=True,\n",
       "  tol=0.001, verbose=False)"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "best_clf"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<bound method BaseEstimator.get_params of GridSearchCV(cv='warn', error_score='raise-deprecating',\n",
       "       estimator=SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,\n",
       "  decision_function_shape='ovr', degree=3, gamma='auto_deprecated',\n",
       "  kernel='rbf', max_iter=-1, probability=False, random_state=None,\n",
       "  shrinking=True, tol=0.001, verbose=False),\n",
       "       fit_params=None, iid='warn', n_jobs=-1,\n",
       "       param_grid={'C': [0.001, 0.01, 0.1, 1, 10, 20, 30], 'gamma': [0.001, 0.01, 0.1, 1, 2, 5], 'kernel': ['linear', 'rbf']},\n",
       "       pre_dispatch='2*n_jobs', refit=True, return_train_score='warn',\n",
       "       scoring=make_scorer(fbeta_score, beta=0.5), verbose=0)>"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "grid_obj.get_params"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<matplotlib.axes._subplots.AxesSubplot at 0x23c91197278>"
      ]
     },
     "execution_count": 42,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 9112 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 2 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "from sklearn.metrics import confusion_matrix\n",
    "\n",
    "cf = confusion_matrix(y_test, best_predictions)\n",
    "\n",
    "sns.heatmap(cf, annot=True, fmt='d')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Question 5 - Final Model Evaluation\n",
    "\n",
    "* What is your optimized model's accuracy and F-score on the testing data? \n",
    "* Are these scores better or worse than the unoptimized model? \n",
    "* How do the results from your optimized model compare to the naive predictor benchmarks you found earlier in **Question 1**?_  \n",
    "\n",
    "**Note:** Fill in the table below with your results, and then provide discussion in the **Answer** box."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Results:\n",
    "\n",
    "|     Metric     | Unoptimized Model | Optimized Model |\n",
    "| :------------: | :---------------: | :-------------: | \n",
    "| Accuracy Score |    0.8371         |    0.8392       |\n",
    "| F-score        |    0.6745         |    0.6803       |\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Answer: **\n",
    "\n",
    "The results are better (only marginally). I ran this several times with the same parameters and it remains very close whether a rbf or linear kernel was chosen.\n",
    "\n",
    "\n",
    "The scores for the naive model were: Accuracy score: 0.2478, F-score: 0.2917\n",
    "\n",
    "If this were a production use case - I would do further investigation with the hyperparamters. Rather than using a step of 0.001, 0.01, 0.1 for C I would look at more granular steps in between these values. For values of C < 1 this usually suggests we have noisy data.\n",
    "\n",
    "We could also look at gamma - we have a relatively small value of gamma at 0.001. If this is too small then the model may not be able to accurately capture the shape of the data.\n",
    "\n",
    "If I were to work on this further - I would try a grid search with more granular values for gamma and C. I would then make use of the seaborn heatmap to see the validation accuracy on a scale of 0 to 1 to see the heatmap for each combination of values.\n",
    "\n",
    "That being said we have a much higher accuracy when compared to the naive predictor and this is to be expected. Since our assumption was naive and we have used a model with tuned parameters.\n",
    "\n",
    "We see that our accuracy of our tuned model is 0.8392 compared to 0.2478 of the naive model. This is an increase of ~240% which is a huge improvement. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "----\n",
    "## Feature Importance\n",
    "\n",
    "An important task when performing supervised learning on a dataset like the census data we study here is determining which features provide the most predictive power. By focusing on the relationship between only a few crucial features and the target label we simplify our understanding of the phenomenon, which is most always a useful thing to do. In the case of this project, that means we wish to identify a small number of features that most strongly predict whether an individual makes at most or more than \\$50,000.\n",
    "\n",
    "Choose a scikit-learn classifier (e.g., adaboost, random forests) that has a `feature_importance_` attribute, which is a function that ranks the importance of features according to the chosen classifier.  In the next python cell fit this classifier to training set and use this attribute to determine the top 5 most important features for the census dataset."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Question 6 - Feature Relevance Observation\n",
    "When **Exploring the Data**, it was shown there are thirteen available features for each individual on record in the census data. Of these thirteen records, which five features do you believe to be most important for prediction, and in what order would you rank them and why?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>age</th>\n",
       "      <th>workclass</th>\n",
       "      <th>education_level</th>\n",
       "      <th>education-num</th>\n",
       "      <th>marital-status</th>\n",
       "      <th>occupation</th>\n",
       "      <th>relationship</th>\n",
       "      <th>race</th>\n",
       "      <th>sex</th>\n",
       "      <th>capital-gain</th>\n",
       "      <th>capital-loss</th>\n",
       "      <th>hours-per-week</th>\n",
       "      <th>native-country</th>\n",
       "      <th>income</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>39</td>\n",
       "      <td>State-gov</td>\n",
       "      <td>Bachelors</td>\n",
       "      <td>13.0</td>\n",
       "      <td>Never-married</td>\n",
       "      <td>Adm-clerical</td>\n",
       "      <td>Not-in-family</td>\n",
       "      <td>White</td>\n",
       "      <td>Male</td>\n",
       "      <td>2174.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>40.0</td>\n",
       "      <td>United-States</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>50</td>\n",
       "      <td>Self-emp-not-inc</td>\n",
       "      <td>Bachelors</td>\n",
       "      <td>13.0</td>\n",
       "      <td>Married-civ-spouse</td>\n",
       "      <td>Exec-managerial</td>\n",
       "      <td>Husband</td>\n",
       "      <td>White</td>\n",
       "      <td>Male</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>13.0</td>\n",
       "      <td>United-States</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>38</td>\n",
       "      <td>Private</td>\n",
       "      <td>HS-grad</td>\n",
       "      <td>9.0</td>\n",
       "      <td>Divorced</td>\n",
       "      <td>Handlers-cleaners</td>\n",
       "      <td>Not-in-family</td>\n",
       "      <td>White</td>\n",
       "      <td>Male</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>40.0</td>\n",
       "      <td>United-States</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>53</td>\n",
       "      <td>Private</td>\n",
       "      <td>11th</td>\n",
       "      <td>7.0</td>\n",
       "      <td>Married-civ-spouse</td>\n",
       "      <td>Handlers-cleaners</td>\n",
       "      <td>Husband</td>\n",
       "      <td>Black</td>\n",
       "      <td>Male</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>40.0</td>\n",
       "      <td>United-States</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>28</td>\n",
       "      <td>Private</td>\n",
       "      <td>Bachelors</td>\n",
       "      <td>13.0</td>\n",
       "      <td>Married-civ-spouse</td>\n",
       "      <td>Prof-specialty</td>\n",
       "      <td>Wife</td>\n",
       "      <td>Black</td>\n",
       "      <td>Female</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>40.0</td>\n",
       "      <td>Cuba</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   age          workclass education_level  education-num       marital-status  \\\n",
       "0   39          State-gov       Bachelors           13.0        Never-married   \n",
       "1   50   Self-emp-not-inc       Bachelors           13.0   Married-civ-spouse   \n",
       "2   38            Private         HS-grad            9.0             Divorced   \n",
       "3   53            Private            11th            7.0   Married-civ-spouse   \n",
       "4   28            Private       Bachelors           13.0   Married-civ-spouse   \n",
       "\n",
       "           occupation    relationship    race      sex  capital-gain  \\\n",
       "0        Adm-clerical   Not-in-family   White     Male        2174.0   \n",
       "1     Exec-managerial         Husband   White     Male           0.0   \n",
       "2   Handlers-cleaners   Not-in-family   White     Male           0.0   \n",
       "3   Handlers-cleaners         Husband   Black     Male           0.0   \n",
       "4      Prof-specialty            Wife   Black   Female           0.0   \n",
       "\n",
       "   capital-loss  hours-per-week  native-country income  \n",
       "0           0.0            40.0   United-States      0  \n",
       "1           0.0            13.0   United-States      0  \n",
       "2           0.0            40.0   United-States      0  \n",
       "3           0.0            40.0   United-States      0  \n",
       "4           0.0            40.0            Cuba      0  "
      ]
     },
     "execution_count": 48,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data.head(5)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Answer:**\n",
    "\n",
    "I would rank the features in the following order\n",
    "\n",
    "1. Hours per week - I would consider this very important. Those who do not work full time (>35 hours a week) are much less likely to have a high income. It is noteworthy that if their marital status is married then this could explain why someone works few hours a week. As our data is income individually (and not household income) I would therefore rate this as the highest indicator.\n",
    "\n",
    "2. Capital gain - I would consider this important. Those who have investments that are paying off I would believe to have a high enough income to begin with to afford the investment. \n",
    "\n",
    "3. Education Level - Those who have a Bachelors degree or higher are more likely to be earning more than those who do not (see https://smartasset.com/retirement/the-average-salary-by-education-level)\n",
    "\n",
    "4. Native Country - I would expect that this would be quite important in determining whether someone earns over \\$50k. Countries such as the UK, USA and Luxembourg would have a higher median income compared to countries such as Liberia and other African states.\n",
    "\n",
    "5. Sex - On average women earn 78 cents to the dollar when compared to men (according to CNN in 2015 in the USA https://money.cnn.com/2015/04/13/news/economy/equal-pay-day-2015/). Although there are many reasons why this is the case in terms of looking just at the data and the problem we want to solve, I would expect more men than women to earn $50k or above."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Implementation - Extracting Feature Importance\n",
    "Choose a `scikit-learn` supervised learning algorithm that has a `feature_importance_` attribute availble for it. This attribute is a function that ranks the importance of each feature when making predictions based on the chosen algorithm.\n",
    "\n",
    "In the code cell below, you will need to implement the following:\n",
    " - Import a supervised learning model from sklearn if it is different from the three used earlier.\n",
    " - Train the supervised model on the entire training set.\n",
    " - Extract the feature importances using `'.feature_importances_'`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 24056 characters]\n",
      "text/plain": [
       "<Figure size 648x360 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "# TODO: Import a supervised learning model that has 'feature_importances_'\n",
    "from sklearn.tree import DecisionTreeClassifier\n",
    "\n",
    "# TODO: Train the supervised model on the training set using .fit(X_train, y_train)\n",
    "model = DecisionTreeClassifier()\n",
    "model.fit(X_train, y_train)\n",
    "\n",
    "# TODO: Extract the feature importances using .feature_importances_ \n",
    "importances = model.feature_importances_\n",
    "\n",
    "# Plot\n",
    "vs.feature_plot(importances, X_train, y_train)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Question 7 - Extracting Feature Importance\n",
    "\n",
    "Observe the visualization created above which displays the five most relevant features for predicting if an individual makes at most or above \\$50,000.  \n",
    "* How do these five features compare to the five features you discussed in **Question 6**?\n",
    "* If you were close to the same answer, how does this visualization confirm your thoughts? \n",
    "* If you were not close, why do you think these features are more relevant?\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Answer:**\n",
    "\n",
    "Features that are the same:\n",
    "1. Capital Gain\n",
    "2. Hours per Week\n",
    "\n",
    "Features that differ:\n",
    "1. Marital Status\n",
    "2. Age\n",
    "3. Education Number\n",
    "\n",
    "We can see that the five most important features from the graph account for nearly 70% of the feature weight. This means that these features account for 70% of the variability in determining our answer. \n",
    "\n",
    "Age is one feature I would have included instead of Sex - it makes sense that the older one is, the more money they would be earning. I can see why this is second in terms of importance when considering the data and the problem we are trying to answer.\n",
    "\n",
    "I am somewhat surprised to see that someone who is married to be number one in terms of importance. It is plausible that those who are married are able to earn more if we considered household income. \n",
    "\n",
    "Education Number is a metric I am not familiar with being from the UK - I am guessing that this is closely related to Education Level (e.g in a few cells up we see the first 5 rows of our data and everyone who has a Bachelors degree has an education number of 13). If this is the case then my suspicion that the level to which one is educated is an important factor in considering their income level."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Feature Selection\n",
    "How does a model perform if we only use a subset of all the available features in the data? With less features required to train, the expectation is that training and prediction time is much lower — at the cost of performance metrics. From the visualization above, we see that the top five most important features contribute more than half of the importance of **all** features present in the data. This hints that we can attempt to *reduce the feature space* and simplify the information required for the model to learn. The code cell below will use the same optimized model you found earlier, and train it on the same training set *with only the top five important features*. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Time took to fit: 5.49s\n",
      "Final Model trained on full data\n",
      "------\n",
      "Accuracy on testing data: 0.8392\n",
      "F-score on testing data: 0.6803\n",
      "\n",
      "Final Model trained on reduced data\n",
      "------\n",
      "Accuracy on testing data: 0.8226\n",
      "F-score on testing data: 0.6420\n"
     ]
    }
   ],
   "source": [
    "# Import functionality for cloning a model\n",
    "from sklearn.base import clone\n",
    "import time \n",
    "\n",
    "# Reduce the feature space\n",
    "X_train_reduced = X_train[X_train.columns.values[(np.argsort(importances)[::-1])[:5]]]\n",
    "X_test_reduced = X_test[X_test.columns.values[(np.argsort(importances)[::-1])[:5]]]\n",
    "\n",
    "start_time = time.time()\n",
    "# Train on the \"best\" model found from grid search earlier\n",
    "clf = (clone(best_clf)).fit(X_train_reduced, y_train)\n",
    "end_time = time.time()\n",
    "\n",
    "\n",
    "# Make new predictions\n",
    "reduced_predictions = clf.predict(X_test_reduced)\n",
    "\n",
    "\n",
    "\n",
    "print(f'Time took to fit: {end_time - start_time:.2f}s')\n",
    "# Report scores from the final model using both versions of data\n",
    "print(\"Final Model trained on full data\\n------\")\n",
    "print(\"Accuracy on testing data: {:.4f}\".format(accuracy_score(y_test, best_predictions)))\n",
    "print(\"F-score on testing data: {:.4f}\".format(fbeta_score(y_test, best_predictions, beta = 0.5)))\n",
    "print(\"\\nFinal Model trained on reduced data\\n------\")\n",
    "print(\"Accuracy on testing data: {:.4f}\".format(accuracy_score(y_test, reduced_predictions)))\n",
    "print(\"F-score on testing data: {:.4f}\".format(fbeta_score(y_test, reduced_predictions, beta = 0.5)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Question 8 - Effects of Feature Selection\n",
    "\n",
    "* How does the final model's F-score and accuracy score on the reduced data using only five features compare to those same scores when all features are used?\n",
    "* If training time was a factor, would you consider using the reduced data as your training set?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Answer:**\n",
    "\n",
    "The final model using the reduced features is very close to the result if we trained on the whole dataset. The accuracy decreases by 2% and the f-score decreases by 5.6%. **It took a mere 5.5 seconds to fit the data to the whole dataset.** Such a small trade off in accuracy for such a huge increase in time savings is something I would most certainly consider if training time was a factor.\n",
    "\n",
    "Indeed when using grid search I initially tried a much more granular approach to find the C and gamma values for the SVM. I initially tried a logspace of 14 numbers (np.logspace(-12, 3, num=14)) but even on powerful hardware (an intel i9 9900k with 32GB RAM) this hadn't completed after 72 hours continuously running. This was most likely due to the very small precise values of gamma and C oweing to much longer training times needed. Working with a much smaller feature set would be interesting to see if we can find more precise values in a much smaller time.\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> **Note**: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this by using the menu above and navigating to  \n",
    "**File -> Download as -> HTML (.html)**. Include the finished document along with this notebook as your submission."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
