├── CODEOWNERS
├── .DS_Store
├── README.md
├── .github
└── workflows
│ └── manual.yml
├── LICENSE.txt
└── starter
├── README.md
├── visuals.py
└── finding_donors.ipynb
/CODEOWNERS:
--------------------------------------------------------------------------------
1 | * @udacity/active-public-content
--------------------------------------------------------------------------------
/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/udacity/cd0025-supervised-learning/HEAD/.DS_Store
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Supervised Learning (cd0025)
2 |
3 | Content for Udacity's Supervised Learning curriculum, which includes project starter files.
4 |
5 | 
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. Please refer to [Udacity Terms of Service](https://www.udacity.com/legal) for further information.
6 |
--------------------------------------------------------------------------------
/.github/workflows/manual.yml:
--------------------------------------------------------------------------------
1 | # Workflow to ensure whenever a Github PR is submitted,
2 | # a JIRA ticket gets created automatically.
3 | name: Manual Workflow
4 |
5 | # Controls when the action will run.
6 | on:
7 | # Triggers the workflow on pull request events but only for the master branch
8 | pull_request_target:
9 | types: [opened, reopened]
10 |
11 | # Allows you to run this workflow manually from the Actions tab
12 | workflow_dispatch:
13 |
14 | jobs:
15 | test-transition-issue:
16 | name: Convert Github Issue to Jira Issue
17 | runs-on: ubuntu-latest
18 | steps:
19 | - name: Checkout
20 | uses: actions/checkout@master
21 |
22 | - name: Login
23 | uses: atlassian/gajira-login@master
24 | env:
25 | JIRA_BASE_URL: ${{ secrets.JIRA_BASE_URL }}
26 | JIRA_USER_EMAIL: ${{ secrets.JIRA_USER_EMAIL }}
27 | JIRA_API_TOKEN: ${{ secrets.JIRA_API_TOKEN }}
28 |
29 | - name: Create NEW JIRA ticket
30 | id: create
31 | uses: atlassian/gajira-create@master
32 | with:
33 | project: CONUPDATE
34 | issuetype: Task
35 | summary: |
36 | Github PR nd229 - Intro to Machine Learning with PyTorch | Repo: ${{ github.repository }} | PR# ${{github.event.number}}
37 | description: |
38 | Repo link: https://github.com/${{ github.repository }}
39 | PR no. ${{ github.event.pull_request.number }}
40 | PR title: ${{ github.event.pull_request.title }}
41 | PR description: ${{ github.event.pull_request.description }}
42 | In addition, please resolve other issues, if any.
43 | fields: '{"components": [{"name":"nd229 - Intro to Machine Learning with PyTorch"}], "customfield_16449":"https://classroom.udacity.com/", "customfield_16450":"Resolve the PR", "labels": ["github"], "priority":{"id": "4"}}'
44 |
45 | - name: Log created issue
46 | run: echo "Issue ${{ steps.create.outputs.issue }} was created"
47 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | Copyright © 2012 - 2020, Udacity, Inc.
2 |
3 | Udacity hereby grants you a license in and to the Educational Content, including
4 | but not limited to homework assignments, programming assignments, code samples,
5 | and other educational materials and tools (as further described in the Udacity
6 | Terms of Use), subject to, as modified herein, the terms and conditions of the
7 | Creative Commons Attribution-NonCommercial- NoDerivs 3.0 License located at
8 | http://creativecommons.org/licenses/by-nc-nd/4.0 and successor locations for
9 | such license (the "CC License") provided that, in each case, the Educational
10 | Content is specifically marked as being subject to the CC License.
11 |
12 | Udacity expressly defines the following as falling outside the definition of
13 | "non-commercial":
14 | (a) the sale or rental of (i) any part of the Educational Content, (ii) any
15 | derivative works based at least in part on the Educational Content, or (iii)
16 | any collective work that includes any part of the Educational Content;
17 | (b) the sale of access or a link to any part of the Educational Content without
18 | first obtaining informed consent from the buyer (that the buyer is aware
19 | that the Educational Content, or such part thereof, is available at the
20 | Website free of charge);
21 | (c) providing training, support, or editorial services that use or reference the
22 | Educational Content in exchange for a fee;
23 | (d) the sale of advertisements, sponsorships, or promotions placed on the
24 | Educational Content, or any part thereof, or the sale of advertisements,
25 | sponsorships, or promotions on any website or blog containing any part of
26 | the Educational Material, including without limitation any "pop-up
27 | advertisements";
28 | (e) the use of Educational Content by a college, university, school, or other
29 | educational institution for instruction where tuition is charged; and
30 | (f) the use of Educational Content by a for-profit corporation or non-profit
31 | entity for internal professional development or training.
32 |
33 | THE SERVICES AND ONLINE COURSES (INCLUDING ANY CONTENT) ARE PROVIDED "AS IS" AND
34 | "AS AVAILABLE" WITH NO REPRESENTATIONS OR WARRANTIES OF ANY KIND, EITHER
35 | EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
36 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. YOU
37 | ASSUME TOTAL RESPONSIBILITY AND THE ENTIRE RISK FOR YOUR USE OF THE SERVICES,
38 | ONLINE COURSES, AND CONTENT. WITHOUT LIMITING THE FOREGOING, WE DO NOT WARRANT
39 | THAT (A) THE SERVICES, WEBSITES, CONTENT, OR THE ONLINE COURSES WILL MEET YOUR
40 | REQUIREMENTS OR EXPECTATIONS OR ACHIEVE THE INTENDED PURPOSES, (B) THE WEBSITES
41 | OR THE ONLINE COURSES WILL NOT EXPERIENCE OUTAGES OR OTHERWISE BE UNINTERRUPTED,
42 | TIMELY, SECURE OR ERROR-FREE, (C) THE INFORMATION OR CONTENT OBTAINED THROUGH
43 | THE SERVICES, SUCH AS CHAT ROOM SERVICES, WILL BE ACCURATE, COMPLETE, CURRENT,
44 | ERROR- FREE, COMPLETELY SECURE OR RELIABLE, OR (D) THAT DEFECTS IN OR ON THE
45 | SERVICES OR CONTENT WILL BE CORRECTED. YOU ASSUME ALL RISK OF PERSONAL INJURY,
46 | INCLUDING DEATH AND DAMAGE TO PERSONAL PROPERTY, SUSTAINED FROM USE OF SERVICES.
47 |
--------------------------------------------------------------------------------
/starter/README.md:
--------------------------------------------------------------------------------
1 | # Supervised Learning
2 | ## Project: Finding Donors for CharityML
3 |
4 | ### Install
5 |
6 | This project requires **Python 3.x** and the following Python libraries installed:
7 |
8 | - [NumPy](http://www.numpy.org/)
9 | - [Pandas](http://pandas.pydata.org)
10 | - [matplotlib](http://matplotlib.org/)
11 | - [scikit-learn](http://scikit-learn.org/stable/)
12 |
13 | You will also need to have software installed to run and execute an [iPython Notebook](http://ipython.org/notebook.html)
14 |
15 | We recommend students install [Anaconda](https://www.continuum.io/downloads), a pre-packaged Python distribution that contains all of the necessary libraries and software for this project.
16 |
17 | ### Code
18 |
19 | Template code is provided in the `finding_donors.ipynb` notebook file. You will also be required to use the included `visuals.py` Python file and the `census.csv` dataset file to complete your work. While some code has already been implemented to get you started, you will need to implement additional functionality when requested to successfully complete the project. Note that the code included in `visuals.py` is meant to be used out-of-the-box and not intended for students to manipulate. If you are interested in how the visualizations are created in the notebook, please feel free to explore this Python file.
20 |
21 | ### Run
22 |
23 | In a terminal or command window, navigate to the top-level project directory `finding_donors/` (that contains this README) and run one of the following commands:
24 |
25 | ```bash
26 | ipython notebook finding_donors.ipynb
27 | ```
28 | or
29 | ```bash
30 | jupyter notebook finding_donors.ipynb
31 | ```
32 |
33 | This will open the iPython Notebook software and project file in your browser.
34 |
35 | ### Data
36 |
37 | The modified census dataset consists of approximately 32,000 data points, with each datapoint having 13 features. This dataset is a modified version of the dataset published in the paper *"Scaling Up the Accuracy of Naive-Bayes Classifiers: a Decision-Tree Hybrid",* by Ron Kohavi. You may find this paper [online](https://www.aaai.org/Papers/KDD/1996/KDD96-033.pdf), with the original dataset hosted on [UCI](https://archive.ics.uci.edu/ml/datasets/Census+Income).
38 |
39 | **Features**
40 | - `age`: Age
41 | - `workclass`: Working Class (Private, Self-emp-not-inc, Self-emp-inc, Federal-gov, Local-gov, State-gov, Without-pay, Never-worked)
42 | - `education_level`: Level of 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)
43 | - `education-num`: Number of educational years completed
44 | - `marital-status`: Marital status (Married-civ-spouse, Divorced, Never-married, Separated, Widowed, Married-spouse-absent, Married-AF-spouse)
45 | - `occupation`: Work 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)
46 | - `relationship`: Relationship Status (Wife, Own-child, Husband, Not-in-family, Other-relative, Unmarried)
47 | - `race`: Race (White, Asian-Pac-Islander, Amer-Indian-Eskimo, Other, Black)
48 | - `sex`: Sex (Female, Male)
49 | - `capital-gain`: Monetary Capital Gains
50 | - `capital-loss`: Monetary Capital Losses
51 | - `hours-per-week`: Average Hours Per Week Worked
52 | - `native-country`: 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)
53 |
54 | **Target Variable**
55 | - `income`: Income Class (<=50K, >50K)
56 |
--------------------------------------------------------------------------------
/starter/visuals.py:
--------------------------------------------------------------------------------
1 | ###########################################
2 | # Suppress matplotlib user warnings
3 | # Necessary for newer version of matplotlib
4 | import warnings
5 | warnings.filterwarnings("ignore", category = UserWarning, module = "matplotlib")
6 | #
7 | # Display inline matplotlib plots with IPython
8 | from IPython import get_ipython
9 | get_ipython().run_line_magic('matplotlib', 'inline')
10 | ###########################################
11 |
12 | import matplotlib.pyplot as pl
13 | import matplotlib.patches as mpatches
14 | import numpy as np
15 | import pandas as pd
16 | from time import time
17 | from sklearn.metrics import f1_score, accuracy_score
18 |
19 |
20 | colors = [pl.cm.Paired(i) for i in range(12)]
21 |
22 | def distribution(data, transformed = False):
23 | """
24 | Visualization code for displaying skewed distributions of features
25 | """
26 |
27 | # Create figure
28 | fig = pl.figure(figsize = (11,5));
29 |
30 | # Skewed feature plotting
31 | for i, feature in enumerate(['capital-gain','capital-loss']):
32 | ax = fig.add_subplot(1, 2, i+1)
33 | ax.hist(data[feature], bins = 25, color = colors[0])
34 | ax.set_title(f"'{feature}' Feature Distribution", fontsize = 14)
35 | ax.set_xlabel("Value")
36 | ax.set_ylabel("Number of Records")
37 | ax.set_ylim((0, 2000))
38 | ax.set_yticks([0, 500, 1000, 1500, 2000])
39 | ax.set_yticklabels([0, 500, 1000, 1500, ">2000"])
40 |
41 | # Plot aesthetics
42 | if transformed:
43 | fig.suptitle("Log-transformed Distributions of Continuous Census Data Features", \
44 | fontsize = 16, y = 1.03)
45 | else:
46 | fig.suptitle("Skewed Distributions of Continuous Census Data Features", \
47 | fontsize = 16, y = 1.03)
48 |
49 | fig.tight_layout()
50 | fig.show()
51 |
52 |
53 | def evaluate(results, accuracy, f1):
54 | """
55 | Visualization code to display results of various learners.
56 |
57 | inputs:
58 | - learners: a list of supervised learners
59 | - stats: a list of dictionaries of the statistic results from 'train_predict()'
60 | - accuracy: The score for the naive predictor
61 | - f1: The score for the naive predictor
62 | """
63 |
64 | # Create figure
65 | fig, ax = pl.subplots(2, 3, figsize = (11,8))
66 |
67 | # Constants
68 | bar_width = 0.3
69 |
70 | # Super loop to plot four panels of data
71 | for k, learner in enumerate(results.keys()):
72 | for j, metric in enumerate(['train_time', 'acc_train', 'f_train', 'pred_time', 'acc_test', 'f_test']):
73 | for i in np.arange(3):
74 |
75 | # Creative plot code
76 | ax[j//3, j%3].bar(i+k*bar_width, results[learner][i][metric], width = bar_width, color = colors[k])
77 | ax[j//3, j%3].set_xticks([0.45, 1.45, 2.45])
78 | ax[j//3, j%3].set_xticklabels(["1%", "10%", "100%"])
79 | ax[j//3, j%3].set_xlabel("Training Set Size")
80 | ax[j//3, j%3].set_xlim((-0.1, 3.0))
81 |
82 | # Add unique y-labels
83 | ax[0, 0].set_ylabel("Time (in seconds)")
84 | ax[0, 1].set_ylabel("Accuracy Score")
85 | ax[0, 2].set_ylabel("F-score")
86 | ax[1, 0].set_ylabel("Time (in seconds)")
87 | ax[1, 1].set_ylabel("Accuracy Score")
88 | ax[1, 2].set_ylabel("F-score")
89 |
90 | # Add titles
91 | ax[0, 0].set_title("Model Training")
92 | ax[0, 1].set_title("Accuracy Score on Training Subset")
93 | ax[0, 2].set_title("F-score on Training Subset")
94 | ax[1, 0].set_title("Model Predicting")
95 | ax[1, 1].set_title("Accuracy Score on Testing Set")
96 | ax[1, 2].set_title("F-score on Testing Set")
97 |
98 | # Add horizontal lines for naive predictors
99 | ax[0, 1].axhline(y = accuracy, xmin = -0.1, xmax = 3.0, linewidth = 1, color = 'k', linestyle = 'dashed')
100 | ax[1, 1].axhline(y = accuracy, xmin = -0.1, xmax = 3.0, linewidth = 1, color = 'k', linestyle = 'dashed')
101 | ax[0, 2].axhline(y = f1, xmin = -0.1, xmax = 3.0, linewidth = 1, color = 'k', linestyle = 'dashed')
102 | ax[1, 2].axhline(y = f1, xmin = -0.1, xmax = 3.0, linewidth = 1, color = 'k', linestyle = 'dashed')
103 |
104 | # Set y-limits for score panels
105 | ax[0, 1].set_ylim((0, 1))
106 | ax[0, 2].set_ylim((0, 1))
107 | ax[1, 1].set_ylim((0, 1))
108 | ax[1, 2].set_ylim((0, 1))
109 |
110 | # Create patches for the legend
111 | patches = []
112 | for i, learner in enumerate(results.keys()):
113 | patches.append(mpatches.Patch(color = colors[i], label = learner))
114 | pl.legend(handles = patches, bbox_to_anchor = (-.80, 2.53), \
115 | loc = 'upper center', borderaxespad = 0., ncol = 3, fontsize = 'x-large')
116 |
117 | # Aesthetics
118 | pl.suptitle("Performance Metrics for Three Supervised Learning Models", fontsize = 16, x = 0.63, y = 1.05)
119 | # Tune the subplot layout
120 | # Refer - https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.subplots_adjust.html for more details on the arguments
121 | pl.subplots_adjust(left = 0.125, right = 1.2, bottom = 0.1, top = 0.9, wspace = 0.2, hspace = 0.3)
122 | pl.tight_layout()
123 | pl.show()
124 |
125 |
126 | def feature_plot(importances, X_train, y_train):
127 |
128 | # Display the five most important features
129 | indices = np.argsort(importances)[::-1]
130 | columns = X_train.columns.values[indices[:5]]
131 | values = importances[indices][:5]
132 |
133 | # Creat the plot
134 | fig = pl.figure(figsize = (9, 5))
135 | pl.title("Normalized Weights for First Five Most Predictive Features", fontsize = 16)
136 | pl.bar(np.arange(5) - 0.1, values, width = 0.2, align="center", color=colors[0], \
137 | label = "Feature Weight")
138 | pl.bar(np.arange(5) + 0.1, np.cumsum(values), width = 0.2, align = "center", color=colors[1], \
139 | label = "Cumulative Feature Weight")
140 | pl.xticks(np.arange(5), columns, rotation=20)
141 | pl.xlim((-0.5, 4.5))
142 | pl.ylabel("Weight", fontsize = 12)
143 | pl.xlabel("Feature", fontsize = 12)
144 |
145 | pl.legend()
146 | pl.tight_layout()
147 | pl.show()
148 |
--------------------------------------------------------------------------------
/starter/finding_donors.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Introduction to Machine Learning with PyTorch\n",
8 | "## Project: Finding Donors for *CharityML*"
9 | ]
10 | },
11 | {
12 | "cell_type": "markdown",
13 | "metadata": {},
14 | "source": [
15 | "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",
16 | "\n",
17 | "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",
18 | "\n",
19 | ">**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."
20 | ]
21 | },
22 | {
23 | "cell_type": "markdown",
24 | "metadata": {},
25 | "source": [
26 | "## Getting Started\n",
27 | "\n",
28 | "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",
29 | "\n",
30 | "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."
31 | ]
32 | },
33 | {
34 | "cell_type": "markdown",
35 | "metadata": {},
36 | "source": [
37 | "----\n",
38 | "## Exploring the Data\n",
39 | "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."
40 | ]
41 | },
42 | {
43 | "cell_type": "code",
44 | "execution_count": 1,
45 | "metadata": {},
46 | "outputs": [
47 | {
48 | "data": {
49 | "text/html": [
50 | "
\n",
51 | "\n",
64 | "
\n",
65 | " \n",
66 | " \n",
67 | " | \n",
68 | " age | \n",
69 | " workclass | \n",
70 | " education_level | \n",
71 | " education-num | \n",
72 | " marital-status | \n",
73 | " occupation | \n",
74 | " relationship | \n",
75 | " race | \n",
76 | " sex | \n",
77 | " capital-gain | \n",
78 | " capital-loss | \n",
79 | " hours-per-week | \n",
80 | " native-country | \n",
81 | " income | \n",
82 | "
\n",
83 | " \n",
84 | " \n",
85 | " \n",
86 | " | 0 | \n",
87 | " 39 | \n",
88 | " State-gov | \n",
89 | " Bachelors | \n",
90 | " 13.0 | \n",
91 | " Never-married | \n",
92 | " Adm-clerical | \n",
93 | " Not-in-family | \n",
94 | " White | \n",
95 | " Male | \n",
96 | " 2174.0 | \n",
97 | " 0.0 | \n",
98 | " 40.0 | \n",
99 | " United-States | \n",
100 | " <=50K | \n",
101 | "
\n",
102 | " \n",
103 | "
\n",
104 | "
"
105 | ],
106 | "text/plain": [
107 | " age workclass education_level education-num marital-status \\\n",
108 | "0 39 State-gov Bachelors 13.0 Never-married \n",
109 | "\n",
110 | " occupation relationship race sex capital-gain capital-loss \\\n",
111 | "0 Adm-clerical Not-in-family White Male 2174.0 0.0 \n",
112 | "\n",
113 | " hours-per-week native-country income \n",
114 | "0 40.0 United-States <=50K "
115 | ]
116 | },
117 | "metadata": {},
118 | "output_type": "display_data"
119 | }
120 | ],
121 | "source": [
122 | "# Import libraries necessary for this project\n",
123 | "import numpy as np\n",
124 | "import pandas as pd\n",
125 | "from time import time\n",
126 | "from IPython.display import display # Allows the use of display() for DataFrames\n",
127 | "\n",
128 | "# Import supplementary visualization code visuals.py\n",
129 | "import visuals as vs\n",
130 | "\n",
131 | "# Pretty display for notebooks\n",
132 | "%matplotlib inline\n",
133 | "\n",
134 | "# Load the Census dataset\n",
135 | "data = pd.read_csv(\"census.csv\")\n",
136 | "\n",
137 | "# Success - Display the first record\n",
138 | "display(data.head(n=1))"
139 | ]
140 | },
141 | {
142 | "cell_type": "markdown",
143 | "metadata": {},
144 | "source": [
145 | "### Implementation: Data Exploration\n",
146 | "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",
147 | "- The total number of records, `n_records`\n",
148 | "- The number of individuals making more than $50,000 annually, `n_greater_50k`.\n",
149 | "- The number of individuals making at most $50,000 annually, `n_at_most_50k`.\n",
150 | "- The percentage of individuals making more than $50,000 annually, `greater_percent`.\n",
151 | "\n",
152 | "**HINT:** You may need to look at the table above to understand how the `income` entries are formatted. "
153 | ]
154 | },
155 | {
156 | "cell_type": "code",
157 | "execution_count": null,
158 | "metadata": {
159 | "collapsed": true
160 | },
161 | "outputs": [],
162 | "source": [
163 | "# TODO: Total number of records\n",
164 | "n_records = None\n",
165 | "\n",
166 | "# TODO: Number of records where individual's income is more than $50,000\n",
167 | "n_greater_50k = None\n",
168 | "\n",
169 | "# TODO: Number of records where individual's income is at most $50,000\n",
170 | "n_at_most_50k = None\n",
171 | "\n",
172 | "# TODO: Percentage of individuals whose income is more than $50,000\n",
173 | "greater_percent = None\n",
174 | "\n",
175 | "# Print the results\n",
176 | "print(\"Total number of records: {}\".format(n_records))\n",
177 | "print(\"Individuals making more than $50,000: {}\".format(n_greater_50k))\n",
178 | "print(\"Individuals making at most $50,000: {}\".format(n_at_most_50k))\n",
179 | "print(\"Percentage of individuals making more than $50,000: {}%\".format(greater_percent))"
180 | ]
181 | },
182 | {
183 | "cell_type": "markdown",
184 | "metadata": {},
185 | "source": [
186 | "**Featureset Exploration**\n",
187 | "\n",
188 | "* **age**: continuous. \n",
189 | "* **workclass**: Private, Self-emp-not-inc, Self-emp-inc, Federal-gov, Local-gov, State-gov, Without-pay, Never-worked. \n",
190 | "* **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",
191 | "* **education-num**: continuous. \n",
192 | "* **marital-status**: Married-civ-spouse, Divorced, Never-married, Separated, Widowed, Married-spouse-absent, Married-AF-spouse. \n",
193 | "* **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",
194 | "* **relationship**: Wife, Own-child, Husband, Not-in-family, Other-relative, Unmarried. \n",
195 | "* **race**: Black, White, Asian-Pac-Islander, Amer-Indian-Eskimo, Other. \n",
196 | "* **sex**: Female, Male. \n",
197 | "* **capital-gain**: continuous. \n",
198 | "* **capital-loss**: continuous. \n",
199 | "* **hours-per-week**: continuous. \n",
200 | "* **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."
201 | ]
202 | },
203 | {
204 | "cell_type": "markdown",
205 | "metadata": {},
206 | "source": [
207 | "----\n",
208 | "## Preparing the Data\n",
209 | "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."
210 | ]
211 | },
212 | {
213 | "cell_type": "markdown",
214 | "metadata": {},
215 | "source": [
216 | "### Transforming Skewed Continuous Features\n",
217 | "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",
218 | "\n",
219 | "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."
220 | ]
221 | },
222 | {
223 | "cell_type": "code",
224 | "execution_count": null,
225 | "metadata": {
226 | "collapsed": true
227 | },
228 | "outputs": [],
229 | "source": [
230 | "# Split the data into features and target label\n",
231 | "income_raw = data['income']\n",
232 | "features_raw = data.drop('income', axis = 1)\n",
233 | "\n",
234 | "# Visualize skewed continuous features of original data\n",
235 | "vs.distribution(data)"
236 | ]
237 | },
238 | {
239 | "cell_type": "markdown",
240 | "metadata": {},
241 | "source": [
242 | "For highly-skewed feature distributions such as `capital-gain` and `capital-loss`, it is common practice to apply a [logarithmic transformation](https://en.wikipedia.org/wiki/Data_transformation_(statistics)) 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",
243 | "\n",
244 | "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. "
245 | ]
246 | },
247 | {
248 | "cell_type": "code",
249 | "execution_count": null,
250 | "metadata": {
251 | "collapsed": true
252 | },
253 | "outputs": [],
254 | "source": [
255 | "# Log-transform the skewed features\n",
256 | "skewed = ['capital-gain', 'capital-loss']\n",
257 | "features_log_transformed = pd.DataFrame(data = features_raw)\n",
258 | "features_log_transformed[skewed] = features_raw[skewed].apply(lambda x: np.log(x + 1))\n",
259 | "\n",
260 | "# Visualize the new log distributions\n",
261 | "vs.distribution(features_log_transformed, transformed = True)"
262 | ]
263 | },
264 | {
265 | "cell_type": "markdown",
266 | "metadata": {},
267 | "source": [
268 | "### Normalizing Numerical Features\n",
269 | "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",
270 | "\n",
271 | "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."
272 | ]
273 | },
274 | {
275 | "cell_type": "code",
276 | "execution_count": null,
277 | "metadata": {
278 | "collapsed": true
279 | },
280 | "outputs": [],
281 | "source": [
282 | "# Import sklearn.preprocessing.StandardScaler\n",
283 | "from sklearn.preprocessing import MinMaxScaler\n",
284 | "\n",
285 | "# Initialize a scaler, then apply it to the features\n",
286 | "scaler = MinMaxScaler() # default=(0, 1)\n",
287 | "numerical = ['age', 'education-num', 'capital-gain', 'capital-loss', 'hours-per-week']\n",
288 | "\n",
289 | "features_log_minmax_transform = pd.DataFrame(data = features_log_transformed)\n",
290 | "features_log_minmax_transform[numerical] = scaler.fit_transform(features_log_transformed[numerical])\n",
291 | "\n",
292 | "# Show an example of a record with scaling applied\n",
293 | "display(features_log_minmax_transform.head(n = 5))"
294 | ]
295 | },
296 | {
297 | "cell_type": "markdown",
298 | "metadata": {},
299 | "source": [
300 | "### Implementation: Data Preprocessing\n",
301 | "\n",
302 | "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`:\n",
303 | "\n",
304 | "| | someFeature | \n",
305 | "| :-: | :-: | \n",
306 | "| 0 | B | \n",
307 | "| 1 | C |\n",
308 | "| 2 | A | \n",
309 | "\n",
310 | "We then encode this feature into `someFeature_A`, `someFeature_B` and `someFeature_C`:\n",
311 | "\n",
312 | "|| someFeature_A | someFeature_B | someFeature_C |\n",
313 | "| :-: | :-: | :-: | :-: |\n",
314 | "|0| 0 | 1 | 0 |\n",
315 | "|1| 0 | 0 | 1 |\n",
316 | "|2| 1 | 0 | 0 |\n",
317 | "\n",
318 | "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",
319 | " - 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",
320 | " - Convert the target label `income_raw` to numerical entries.\n",
321 | " - Set records with \"<=50K\" to 0 and records with \">50K\" to 1."
322 | ]
323 | },
324 | {
325 | "cell_type": "code",
326 | "execution_count": null,
327 | "metadata": {
328 | "collapsed": true,
329 | "scrolled": true
330 | },
331 | "outputs": [],
332 | "source": [
333 | "# TODO: One-hot encode the 'features_log_minmax_transform' data using pandas.get_dummies()\n",
334 | "features_final = None\n",
335 | "\n",
336 | "# TODO: Encode the 'income_raw' data to numerical values\n",
337 | "income = None\n",
338 | "\n",
339 | "# Print the number of features after one-hot encoding\n",
340 | "encoded = list(features_final.columns)\n",
341 | "print(\"{} total features after one-hot encoding.\".format(len(encoded)))\n",
342 | "\n",
343 | "# Uncomment the following line to see the encoded feature names\n",
344 | "# print(encoded)"
345 | ]
346 | },
347 | {
348 | "cell_type": "markdown",
349 | "metadata": {},
350 | "source": [
351 | "### Shuffle and Split Data\n",
352 | "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",
353 | "\n",
354 | "Run the code cell below to perform this split."
355 | ]
356 | },
357 | {
358 | "cell_type": "code",
359 | "execution_count": null,
360 | "metadata": {
361 | "collapsed": true
362 | },
363 | "outputs": [],
364 | "source": [
365 | "# Import train_test_split\n",
366 | "from sklearn.model_selection import train_test_split\n",
367 | "\n",
368 | "# Split the 'features' and 'income' data into training and testing sets\n",
369 | "X_train, X_test, y_train, y_test = train_test_split(features_final, \n",
370 | " income, \n",
371 | " test_size = 0.2, \n",
372 | " random_state = 0)\n",
373 | "\n",
374 | "# Show the results of the split\n",
375 | "print(\"Training set has {} samples.\".format(X_train.shape[0]))\n",
376 | "print(\"Testing set has {} samples.\".format(X_test.shape[0]))"
377 | ]
378 | },
379 | {
380 | "cell_type": "markdown",
381 | "metadata": {},
382 | "source": [
383 | "----\n",
384 | "## Evaluating Model Performance\n",
385 | "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*."
386 | ]
387 | },
388 | {
389 | "cell_type": "markdown",
390 | "metadata": {},
391 | "source": [
392 | "### Metrics and the Naive Predictor\n",
393 | "*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",
394 | "\n",
395 | "$$ F_{\\beta} = (1 + \\beta^2) \\cdot \\frac{\\text{precision} \\cdot \\text{recall}}{\\left( \\beta^2 \\cdot \\text{precision} \\right) + \\text{recall}} $$\n",
396 | "\n",
397 | "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",
398 | "\n",
399 | "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",
400 | "\n",
401 | "\n",
402 | "#### Note: Recap of accuracy, precision, recall\n",
403 | "\n",
404 | "**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",
405 | "\n",
406 | "**Precision** tells us what proportion of messages we classified as spam, actually were spam.\n",
407 | "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",
408 | "\n",
409 | "$$\\text{Precision} = \\frac{\\text{True Positives}} {\\text{True Positives} + \\text{False Positives}}$$\n",
410 | "\n",
411 | "**Recall (sensitivity)** tells us what proportion of messages that actually were spam were classified by us as spam.\n",
412 | "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",
413 | "\n",
414 | "$$\\text{Recall} = \\frac{\\text{True Positives}} {\\text{True Positives} + \\text{False Negatives}}$$\n",
415 | "\n",
416 | "For classification problems that are skewed in their classification distributions, like in our case, for example, if we had 100 text messages and only 2 were spam and the remaining 98 weren't, accuracy 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 and the 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 when dealing with ratios)."
417 | ]
418 | },
419 | {
420 | "cell_type": "markdown",
421 | "metadata": {},
422 | "source": [
423 | "### Question 1 - Naive Predictor Performace\n",
424 | "* 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",
425 | "\n",
426 | "**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",
427 | "\n",
428 | "**HINT:** \n",
429 | "\n",
430 | "* 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",
431 | "* Our Recall score (True Positives / (True Positives + False Negatives)) in this setting becomes 1 as we have no False Negatives."
432 | ]
433 | },
434 | {
435 | "cell_type": "code",
436 | "execution_count": null,
437 | "metadata": {
438 | "collapsed": true
439 | },
440 | "outputs": [],
441 | "source": [
442 | "TP = np.sum(income) # Counting the ones as this is the naive case. Note that 'income' is the 'income_raw' data encoded to numerical values done in the data preprocessing step.\n",
443 | "FP = income.count() - TP # Specific to the naive case\n",
444 | "\n",
445 | "TN = 0 # No predicted negatives in the naive case\n",
446 | "FN = 0 # No predicted negatives in the naive case\n",
447 | "\n",
448 | "# TODO: Calculate accuracy, precision and recall\n",
449 | "accuracy = None\n",
450 | "recall = None\n",
451 | "precision = None\n",
452 | "\n",
453 | "# TODO: Calculate F-score using the formula above for beta = 0.5 and correct values for precision and recall.\n",
454 | "fscore = None\n",
455 | "\n",
456 | "# Print the results \n",
457 | "print(\"Naive Predictor: [Accuracy score: {:.4f}, F-score: {:.4f}]\".format(accuracy, fscore))"
458 | ]
459 | },
460 | {
461 | "cell_type": "markdown",
462 | "metadata": {},
463 | "source": [
464 | "### Supervised Learning Models\n",
465 | "**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",
466 | "- Gaussian Naive Bayes (GaussianNB)\n",
467 | "- Decision Trees\n",
468 | "- Ensemble Methods (Bagging, AdaBoost, Random Forest, Gradient Boosting)\n",
469 | "- K-Nearest Neighbors (KNeighbors)\n",
470 | "- Stochastic Gradient Descent Classifier (SGDC)\n",
471 | "- Support Vector Machines (SVM)\n",
472 | "- Logistic Regression"
473 | ]
474 | },
475 | {
476 | "cell_type": "markdown",
477 | "metadata": {},
478 | "source": [
479 | "### Question 2 - Model Application\n",
480 | "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",
481 | "\n",
482 | "- Describe one real-world application in industry where the model can be applied. \n",
483 | "- What are the strengths of the model; when does it perform well?\n",
484 | "- What are the weaknesses of the model; when does it perform poorly?\n",
485 | "- What makes this model a good candidate for the problem, given what you know about the data?\n",
486 | "\n",
487 | "**HINT:**\n",
488 | "\n",
489 | "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."
490 | ]
491 | },
492 | {
493 | "cell_type": "markdown",
494 | "metadata": {},
495 | "source": [
496 | "**Answer:**"
497 | ]
498 | },
499 | {
500 | "cell_type": "markdown",
501 | "metadata": {},
502 | "source": [
503 | "### Implementation - Creating a Training and Predicting Pipeline\n",
504 | "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",
505 | "In the code block below, you will need to implement the following:\n",
506 | " - Import `fbeta_score` and `accuracy_score` from [`sklearn.metrics`](http://scikit-learn.org/stable/modules/classes.html#sklearn-metrics-metrics).\n",
507 | " - Fit the learner to the sampled training data and record the training time.\n",
508 | " - Perform predictions on the test data `X_test`, and also on the first 300 training points `X_train[:300]`.\n",
509 | " - Record the total prediction time.\n",
510 | " - Calculate the accuracy score for both the training subset and testing set.\n",
511 | " - Calculate the F-score for both the training subset and testing set.\n",
512 | " - Make sure that you set the `beta` parameter!"
513 | ]
514 | },
515 | {
516 | "cell_type": "code",
517 | "execution_count": null,
518 | "metadata": {
519 | "collapsed": true
520 | },
521 | "outputs": [],
522 | "source": [
523 | "# TODO: Import two metrics from sklearn - fbeta_score and accuracy_score\n",
524 | "\n",
525 | "def train_predict(learner, sample_size, X_train, y_train, X_test, y_test): \n",
526 | " '''\n",
527 | " inputs:\n",
528 | " - learner: the learning algorithm to be trained and predicted on\n",
529 | " - sample_size: the size of samples (number) to be drawn from training set\n",
530 | " - X_train: features training set\n",
531 | " - y_train: income training set\n",
532 | " - X_test: features testing set\n",
533 | " - y_test: income testing set\n",
534 | " '''\n",
535 | " \n",
536 | " results = {}\n",
537 | " \n",
538 | " # TODO: Fit the learner to the training data using slicing with 'sample_size' using .fit(training_features[:], training_labels[:])\n",
539 | " start = time() # Get start time\n",
540 | " learner = None\n",
541 | " end = time() # Get end time\n",
542 | " \n",
543 | " # TODO: Calculate the training time\n",
544 | " results['train_time'] = None\n",
545 | " \n",
546 | " # TODO: Get the predictions on the test set(X_test),\n",
547 | " # then get predictions on the first 300 training samples(X_train) using .predict()\n",
548 | " start = time() # Get start time\n",
549 | " predictions_test = None\n",
550 | " predictions_train = None\n",
551 | " end = time() # Get end time\n",
552 | " \n",
553 | " # TODO: Calculate the total prediction time\n",
554 | " results['pred_time'] = None\n",
555 | " \n",
556 | " # TODO: Compute accuracy on the first 300 training samples which is y_train[:300]\n",
557 | " results['acc_train'] = None\n",
558 | " \n",
559 | " # TODO: Compute accuracy on test set using accuracy_score()\n",
560 | " results['acc_test'] = None\n",
561 | " \n",
562 | " # TODO: Compute F-score on the the first 300 training samples using fbeta_score()\n",
563 | " results['f_train'] = None\n",
564 | " \n",
565 | " # TODO: Compute F-score on the test set which is y_test\n",
566 | " results['f_test'] = None\n",
567 | " \n",
568 | " # Success\n",
569 | " print(\"{} trained on {} samples.\".format(learner.__class__.__name__, sample_size))\n",
570 | " \n",
571 | " # Return the results\n",
572 | " return results"
573 | ]
574 | },
575 | {
576 | "cell_type": "markdown",
577 | "metadata": {},
578 | "source": [
579 | "### Implementation: Initial Model Evaluation\n",
580 | "In the code cell, you will need to implement the following:\n",
581 | "- Import the three supervised learning models you've discussed in the previous section.\n",
582 | "- Initialize the three models and store them in `clf_A`, `clf_B`, and `clf_C`.\n",
583 | " - Use a `random_state` for each model you use, if provided.\n",
584 | " - **Note:** Use the default settings for each model — you will tune one specific model in a later section.\n",
585 | "- Calculate the number of records equal to 1%, 10%, and 100% of the training data.\n",
586 | " - Store those values in `samples_1`, `samples_10`, and `samples_100` respectively.\n",
587 | "\n",
588 | "**Note:** Depending on which algorithms you chose, the following implementation may take some time to run!"
589 | ]
590 | },
591 | {
592 | "cell_type": "code",
593 | "execution_count": null,
594 | "metadata": {
595 | "collapsed": true
596 | },
597 | "outputs": [],
598 | "source": [
599 | "# TODO: Import the three supervised learning models from sklearn\n",
600 | "\n",
601 | "# TODO: Initialize the three models\n",
602 | "clf_A = None\n",
603 | "clf_B = None\n",
604 | "clf_C = None\n",
605 | "\n",
606 | "# TODO: Calculate the number of samples for 1%, 10%, and 100% of the training data\n",
607 | "# HINT: samples_100 is the entire training set i.e. len(y_train)\n",
608 | "# HINT: samples_10 is 10% of samples_100 (ensure to set the count of the values to be `int` and not `float`)\n",
609 | "# HINT: samples_1 is 1% of samples_100 (ensure to set the count of the values to be `int` and not `float`)\n",
610 | "samples_100 = None\n",
611 | "samples_10 = None\n",
612 | "samples_1 = None\n",
613 | "\n",
614 | "# Collect results on the learners\n",
615 | "results = {}\n",
616 | "for clf in [clf_A, clf_B, clf_C]:\n",
617 | " clf_name = clf.__class__.__name__\n",
618 | " results[clf_name] = {}\n",
619 | " for i, samples in enumerate([samples_1, samples_10, samples_100]):\n",
620 | " results[clf_name][i] = \\\n",
621 | " train_predict(clf, samples, X_train, y_train, X_test, y_test)\n",
622 | "\n",
623 | "# Run metrics visualization for the three supervised learning models chosen\n",
624 | "vs.evaluate(results, accuracy, fscore)"
625 | ]
626 | },
627 | {
628 | "cell_type": "markdown",
629 | "metadata": {},
630 | "source": [
631 | "----\n",
632 | "## Improving Results\n",
633 | "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. "
634 | ]
635 | },
636 | {
637 | "cell_type": "markdown",
638 | "metadata": {},
639 | "source": [
640 | "### Question 3 - Choosing the Best Model\n",
641 | "\n",
642 | "* 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",
643 | "\n",
644 | "**HINT:** \n",
645 | "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",
646 | "* metrics - F score on the testing when 100% of the training data is used, \n",
647 | "* prediction/training time\n",
648 | "* the algorithm's suitability for the data."
649 | ]
650 | },
651 | {
652 | "cell_type": "markdown",
653 | "metadata": {},
654 | "source": [
655 | "**Answer:**"
656 | ]
657 | },
658 | {
659 | "cell_type": "markdown",
660 | "metadata": {},
661 | "source": [
662 | "### Question 4 - Describing the Model in Layman's Terms\n",
663 | "\n",
664 | "* 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",
665 | "\n",
666 | "**HINT:**\n",
667 | "\n",
668 | "When explaining your model, if using external resources please include all citations."
669 | ]
670 | },
671 | {
672 | "cell_type": "markdown",
673 | "metadata": {},
674 | "source": [
675 | "**Answer:** "
676 | ]
677 | },
678 | {
679 | "cell_type": "markdown",
680 | "metadata": {},
681 | "source": [
682 | "### Implementation: Model Tuning\n",
683 | "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",
684 | "- 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",
685 | "- Initialize the classifier you've chosen and store it in `clf`.\n",
686 | " - Set a `random_state` if one is available to the same state you set before.\n",
687 | "- Create a dictionary of parameters you wish to tune for the chosen model.\n",
688 | " - Example: `parameters = {'parameter' : [list of values]}`.\n",
689 | " - **Note:** Avoid tuning the `max_features` parameter of your learner if that parameter is available!\n",
690 | "- Use `make_scorer` to create an `fbeta_score` scoring object (with $\\beta = 0.5$).\n",
691 | "- Perform grid search on the classifier `clf` using the `scorer`, and store it in `grid_obj`.\n",
692 | "- Fit the grid search object to the training data (`X_train`, `y_train`), and store it in `grid_fit`.\n",
693 | "\n",
694 | "**Note:** Depending on the algorithm chosen and the parameter list, the following implementation may take some time to run!"
695 | ]
696 | },
697 | {
698 | "cell_type": "code",
699 | "execution_count": null,
700 | "metadata": {
701 | "collapsed": true
702 | },
703 | "outputs": [],
704 | "source": [
705 | "# TODO: Import 'GridSearchCV', 'make_scorer', and any other necessary libraries\n",
706 | "\n",
707 | "# TODO: Initialize the classifier\n",
708 | "clf = None\n",
709 | "\n",
710 | "# TODO: Create the parameters list you wish to tune, using a dictionary if needed.\n",
711 | "# HINT: parameters = {'parameter_1': [value1, value2], 'parameter_2': [value1, value2]}\n",
712 | "parameters = None\n",
713 | "\n",
714 | "# TODO: Make an fbeta_score scoring object using make_scorer()\n",
715 | "scorer = None\n",
716 | "\n",
717 | "# TODO: Perform grid search on the classifier using 'scorer' as the scoring method using GridSearchCV()\n",
718 | "grid_obj = None\n",
719 | "\n",
720 | "# TODO: Fit the grid search object to the training data and find the optimal parameters using fit()\n",
721 | "grid_fit = None\n",
722 | "\n",
723 | "# Get the estimator\n",
724 | "best_clf = grid_fit.best_estimator_\n",
725 | "\n",
726 | "# Make predictions using the unoptimized and model\n",
727 | "predictions = (clf.fit(X_train, y_train)).predict(X_test)\n",
728 | "best_predictions = best_clf.predict(X_test)\n",
729 | "\n",
730 | "# Report the before-and-afterscores\n",
731 | "print(\"Unoptimized model\\n------\")\n",
732 | "print(\"Accuracy score on testing data: {:.4f}\".format(accuracy_score(y_test, predictions)))\n",
733 | "print(\"F-score on testing data: {:.4f}\".format(fbeta_score(y_test, predictions, beta = 0.5)))\n",
734 | "print(\"\\nOptimized Model\\n------\")\n",
735 | "print(\"Final accuracy score on the testing data: {:.4f}\".format(accuracy_score(y_test, best_predictions)))\n",
736 | "print(\"Final F-score on the testing data: {:.4f}\".format(fbeta_score(y_test, best_predictions, beta = 0.5)))"
737 | ]
738 | },
739 | {
740 | "cell_type": "markdown",
741 | "metadata": {},
742 | "source": [
743 | "### Question 5 - Final Model Evaluation\n",
744 | "\n",
745 | "* What is your optimized model's accuracy and F-score on the testing data? \n",
746 | "* Are these scores better or worse than the unoptimized model? \n",
747 | "* How do the results from your optimized model compare to the naive predictor benchmarks you found earlier in **Question 1**? \n",
748 | "\n",
749 | "**Note:** Fill in the table below with your results, and then provide discussion in the **Answer** box."
750 | ]
751 | },
752 | {
753 | "cell_type": "markdown",
754 | "metadata": {},
755 | "source": [
756 | "#### Results:\n",
757 | "\n",
758 | "| Metric | Unoptimized Model | Optimized Model |\n",
759 | "| :------------: | :---------------: | :-------------: | \n",
760 | "| Accuracy Score | | |\n",
761 | "| F-score | | EXAMPLE |\n"
762 | ]
763 | },
764 | {
765 | "cell_type": "markdown",
766 | "metadata": {},
767 | "source": [
768 | "**Answer:**"
769 | ]
770 | },
771 | {
772 | "cell_type": "markdown",
773 | "metadata": {},
774 | "source": [
775 | "----\n",
776 | "## Feature Importance\n",
777 | "\n",
778 | "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",
779 | "\n",
780 | "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."
781 | ]
782 | },
783 | {
784 | "cell_type": "markdown",
785 | "metadata": {},
786 | "source": [
787 | "### Question 6 - Feature Relevance Observation\n",
788 | "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?"
789 | ]
790 | },
791 | {
792 | "cell_type": "markdown",
793 | "metadata": {},
794 | "source": [
795 | "**Answer:**"
796 | ]
797 | },
798 | {
799 | "cell_type": "markdown",
800 | "metadata": {},
801 | "source": [
802 | "### Implementation - Extracting Feature Importance\n",
803 | "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",
804 | "\n",
805 | "In the code cell below, you will need to implement the following:\n",
806 | " - Import a supervised learning model from sklearn if it is different from the three used earlier.\n",
807 | " - Train the supervised model on the entire training set.\n",
808 | " - Extract the feature importances using `.feature_importances_`."
809 | ]
810 | },
811 | {
812 | "cell_type": "code",
813 | "execution_count": null,
814 | "metadata": {
815 | "collapsed": true
816 | },
817 | "outputs": [],
818 | "source": [
819 | "# TODO: Import a supervised learning model that has 'feature_importances_'\n",
820 | "\n",
821 | "\n",
822 | "# TODO: Train the supervised model on the training set using .fit(X_train, y_train)\n",
823 | "model = None\n",
824 | "\n",
825 | "# TODO: Extract the feature importances using .feature_importances_ \n",
826 | "importances = None\n",
827 | "\n",
828 | "# Plot\n",
829 | "vs.feature_plot(importances, X_train, y_train)"
830 | ]
831 | },
832 | {
833 | "cell_type": "markdown",
834 | "metadata": {},
835 | "source": [
836 | "### Question 7 - Extracting Feature Importance\n",
837 | "\n",
838 | "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",
839 | "* How do these five features compare to the five features you discussed in **Question 6**?\n",
840 | "* If you were close to the same answer, how does this visualization confirm your thoughts? \n",
841 | "* If you were not close, why do you think these features are more relevant?"
842 | ]
843 | },
844 | {
845 | "cell_type": "markdown",
846 | "metadata": {},
847 | "source": [
848 | "**Answer:**"
849 | ]
850 | },
851 | {
852 | "cell_type": "markdown",
853 | "metadata": {},
854 | "source": [
855 | "### Feature Selection\n",
856 | "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*. "
857 | ]
858 | },
859 | {
860 | "cell_type": "code",
861 | "execution_count": null,
862 | "metadata": {
863 | "collapsed": true
864 | },
865 | "outputs": [],
866 | "source": [
867 | "# Import functionality for cloning a model\n",
868 | "from sklearn.base import clone\n",
869 | "\n",
870 | "# Reduce the feature space\n",
871 | "X_train_reduced = X_train[X_train.columns.values[(np.argsort(importances)[::-1])[:5]]]\n",
872 | "X_test_reduced = X_test[X_test.columns.values[(np.argsort(importances)[::-1])[:5]]]\n",
873 | "\n",
874 | "# Train on the \"best\" model found from grid search earlier\n",
875 | "clf = (clone(best_clf)).fit(X_train_reduced, y_train)\n",
876 | "\n",
877 | "# Make new predictions\n",
878 | "reduced_predictions = clf.predict(X_test_reduced)\n",
879 | "\n",
880 | "# Report scores from the final model using both versions of data\n",
881 | "print(\"Final Model trained on full data\\n------\")\n",
882 | "print(\"Accuracy on testing data: {:.4f}\".format(accuracy_score(y_test, best_predictions)))\n",
883 | "print(\"F-score on testing data: {:.4f}\".format(fbeta_score(y_test, best_predictions, beta = 0.5)))\n",
884 | "print(\"\\nFinal Model trained on reduced data\\n------\")\n",
885 | "print(\"Accuracy on testing data: {:.4f}\".format(accuracy_score(y_test, reduced_predictions)))\n",
886 | "print(\"F-score on testing data: {:.4f}\".format(fbeta_score(y_test, reduced_predictions, beta = 0.5)))"
887 | ]
888 | },
889 | {
890 | "cell_type": "markdown",
891 | "metadata": {},
892 | "source": [
893 | "### Question 8 - Effects of Feature Selection\n",
894 | "\n",
895 | "* 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",
896 | "* If training time was a factor, would you consider using the reduced data as your training set?"
897 | ]
898 | },
899 | {
900 | "cell_type": "markdown",
901 | "metadata": {},
902 | "source": [
903 | "**Answer:**"
904 | ]
905 | },
906 | {
907 | "cell_type": "markdown",
908 | "metadata": {},
909 | "source": [
910 | "> **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",
911 | "**File -> Download as -> HTML (.html)**. Include the finished document along with this notebook as your submission."
912 | ]
913 | }
914 | ],
915 | "metadata": {
916 | "kernelspec": {
917 | "display_name": "Python 3",
918 | "language": "python",
919 | "name": "python3"
920 | },
921 | "language_info": {
922 | "codemirror_mode": {
923 | "name": "ipython",
924 | "version": 3
925 | },
926 | "file_extension": ".py",
927 | "mimetype": "text/x-python",
928 | "name": "python",
929 | "nbconvert_exporter": "python",
930 | "pygments_lexer": "ipython3",
931 | "version": "3.6.1"
932 | }
933 | },
934 | "nbformat": 4,
935 | "nbformat_minor": 1
936 | }
937 |
--------------------------------------------------------------------------------