Machine Learning Engineer Nanodegree

Supervised Learning

Project: Finding Donors for CharityML

By Michael Eryan

Welcome to the second project of the Machine Learning Engineer 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!

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.

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.

Getting Started

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.

The dataset for this project originates from the UCI Machine Learning Repository. 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. 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.


Exploring the Data

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.

In [3]:
# Python 3.6

# Import libraries necessary for this project
import os
#print (os.getcwd())

import sys
print ("\n Python version is:", sys.version_info, "\n")

import numpy as np
import pandas as pd
from time import time

#Try to avoid deprecation warnings 
import warnings
warnings.filterwarnings("ignore", category = UserWarning, module = "sklearn")
#still, shows the warning

import matplotlib.pyplot as plt
import seaborn as sns
import sklearn

from sklearn.preprocessing import MinMaxScaler
from sklearn.grid_search import GridSearchCV
from sklearn.metrics import make_scorer

from sklearn.cross_validation import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import f1_score, accuracy_score, fbeta_score
from sklearn.base import clone

# Import supplementary visualization code visuals.py
import visuals as vs

# Pretty display for notebooks
%matplotlib inline
 Python version is: sys.version_info(major=3, minor=6, micro=2, releaselevel='final', serial=0) 

In [3]:
# Load the Census dataset
data = pd.read_csv("census.csv")

print ("Boston housing dataset has {} data points with {} variables. Target is - income.".format(*data.shape) )
# Eyeball the data
print ("\n")
print (data.head(n=1))
Boston housing dataset has 45222 data points with 14 variables. Target is - income.


   age   workclass education_level  education-num  marital-status  \
0   39   State-gov       Bachelors           13.0   Never-married   

      occupation    relationship    race    sex  capital-gain  capital-loss  \
0   Adm-clerical   Not-in-family   White   Male        2174.0           0.0   

   hours-per-week  native-country income  
0            40.0   United-States  <=50K  

Implementation: Data Exploration

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:

  • The total number of records, 'n_records'
  • The number of individuals making more than \$50,000 annually, 'n_greater_50k'.
  • The number of individuals making at most \$50,000 annually, 'n_at_most_50k'.
  • The percentage of individuals making more than \$50,000 annually, 'greater_percent'.

HINT: You may need to look at the table above to understand how the 'income' entries are formatted.

In [4]:
# EDA: exploratory data analysis

# TODO: Total number of records
n_records = len(data) *1.0 #to get the decimal point below

# TODO: Number of records where individual's income is more than $50,000
n_greater_50k = len(data[data['income']=='>50K'])

# TODO: Number of records where individual's income is at most $50,000
n_at_most_50k = len(data[data['income']=='<=50K'])

# TODO: Percentage of individuals whose income is more than $50,000
greater_percent = n_greater_50k / n_records * 100

# Print the results
print ("Total number of records: {:,}".format(round(n_records)))
print ("Individuals making more than $50,000: {:,}".format(round(n_greater_50k)))
print ("Individuals making at most $50,000: {:,}".format(round(n_at_most_50k)))
print ("Percentage of individuals making more than $50,000: {:.2f}%".format(greater_percent))

#this is a pretty high event incidence which makes me optimistic of the models performance.
Total number of records: 45,222
Individuals making more than $50,000: 11,208
Individuals making at most $50,000: 34,014
Percentage of individuals making more than $50,000: 24.78%

Featureset Exploration

  • age: continuous.
  • workclass: Private, Self-emp-not-inc, Self-emp-inc, Federal-gov, Local-gov, State-gov, Without-pay, Never-worked.
  • 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.
  • education-num: continuous.
  • marital-status: Married-civ-spouse, Divorced, Never-married, Separated, Widowed, Married-spouse-absent, Married-AF-spouse.
  • 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.
  • relationship: Wife, Own-child, Husband, Not-in-family, Other-relative, Unmarried.
  • race: Black, White, Asian-Pac-Islander, Amer-Indian-Eskimo, Other.
  • sex: Female, Male.
  • capital-gain: continuous.
  • capital-loss: continuous.
  • hours-per-week: continuous.
  • 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.
In [5]:
# ME: Additional EDA, distributions and scatter plots
inc_count = data.loc[:,['income']].apply(pd.value_counts).fillna(0)
print (inc_count.plot(kind='bar',title='Income distribution',legend=True,color='grey'))
Axes(0.125,0.125;0.775x0.755)
In [6]:
#ME: Age
hist_age = data['age'].hist(bins=50 , normed=True, color='grey')
print (hist_age.set_xlim((10,100)))
print ("Looks like a lot of the ages were rounded, not really a continuous variable.")
(10, 100)
Looks like a lot of the ages were rounded, not really a continuous variable.
In [7]:
#ME: Income vs Sex
sg = pd.DataFrame(pd.crosstab(data.income, data.sex)) 
sg2 = sg / float(inc_count.sum())
print (sg2.plot(kind='bar'))

print ("Proportinally more men have higher incomes. Could this be because men in the sample are older? Let's see.")
Axes(0.125,0.125;0.775x0.755)
Proportinally more men have higher incomes. Could this be because men in the sample are older? Let's see.
In [8]:
g = sns.FacetGrid(data, col="income", margin_titles=True)
age_bins = np.arange(0, 100, 10)
g.map(plt.hist, 'age', bins=age_bins, color="steelblue")

print (data.groupby('sex').mean())
print ("\n")
print ("By age distributions seem similiar for men and women.")
print ("So the answer is no - men are not disproportionately richer because the average man in the sample is much older than the average woman.")
               age  education-num  capital-gain  capital-loss  hours-per-week
sex                                                                          
 Female  36.984757      10.105886    588.132290     61.480095       36.932902
 Male    39.300423      10.124513   1348.520294    101.648115       42.865987


By age distributions seem similiar for men and women.
So the answer is no - men are not disproportionately richer because the average man in the sample is much older than the average woman.

Preparing the Data

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.

Transforming Skewed Continuous Features

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'.

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.

In [9]:
# Split the data into features and target label
income_raw = data['income']
features_raw = data.drop('income', axis = 1)

# Visualize skewed continuous features of original data
vs.distribution(data)

#ME: Monetary capital gain and loss variables are very skewed and will need to get normalized. 

For highly-skewed feature distributions such as 'capital-gain' and 'capital-loss', it is common practice to apply a logarithmic transformation 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.

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.

In [10]:
# Log-transform the skewed features
skewed = ['capital-gain', 'capital-loss']
features_log_transformed = pd.DataFrame(data = features_raw)
features_log_transformed[skewed] = features_raw[skewed].apply(lambda x: np.log(x + 1)) #ME: add 1 to 0s to avoid undefined error, bias should be minimal

# Visualize the new log distributions
vs.distribution(features_log_transformed, transformed = True)

#ME: OK, the ones not zero are more "normal" distributed

Normalizing Numerical Features

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.

Run the code cell below to normalize each numerical feature. We will use sklearn.preprocessing.MinMaxScaler for this.

In [11]:
#ME: Scaling - normalizing

# Initialize a scaler, then apply it to the features
scaler = MinMaxScaler() # default=(0, 1)
numerical = ['age', 'education-num', 'capital-gain', 'capital-loss', 'hours-per-week']

features_log_minmax_transform = pd.DataFrame(data = features_log_transformed)
features_log_minmax_transform[numerical] = scaler.fit_transform(features_log_transformed[numerical])

# Show an example of a record with scaling applied
display(features_log_minmax_transform.head(n = 5))
age workclass education_level education-num marital-status occupation relationship race sex capital-gain capital-loss hours-per-week native-country
0 0.301370 State-gov Bachelors 0.800000 Never-married Adm-clerical Not-in-family White Male 0.667492 0.0 0.397959 United-States
1 0.452055 Self-emp-not-inc Bachelors 0.800000 Married-civ-spouse Exec-managerial Husband White Male 0.000000 0.0 0.122449 United-States
2 0.287671 Private HS-grad 0.533333 Divorced Handlers-cleaners Not-in-family White Male 0.000000 0.0 0.397959 United-States
3 0.493151 Private 11th 0.400000 Married-civ-spouse Handlers-cleaners Husband Black Male 0.000000 0.0 0.397959 United-States
4 0.150685 Private Bachelors 0.800000 Married-civ-spouse Prof-specialty Wife Black Female 0.000000 0.0 0.397959 Cuba

Implementation: Data Preprocessing

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.

someFeature someFeature_A someFeature_B someFeature_C
0 B 0 1 0
1 C ----> one-hot encode ----> 0 0 1
2 A 1 0 0

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:

  • Use pandas.get_dummies() to perform one-hot encoding on the 'features_log_minmax_transform' data.
  • Convert the target label 'income_raw' to numerical entries.
    • Set records with "<=50K" to 0 and records with ">50K" to 1.
In [15]:
# TODO: One-hot encode the 'features_log_minmax_transform' data using pandas.get_dummies()
'''
ME: side-notes
If I simply encode the whole data set, this will drop the original categorical vars
If I needed to keep the originals, I would process only the categoricals and then join to the original dataframe
categorical = ['workclass','education_level','marital-status','occupation','relationship','race','sex','native-country']
features_cat = pd.get_dummies(features_log_minmax_transform[categorical])
Join scaled numerical and one-hot encoded categoricals
features_final=features_log_minmax_transform.join(features_cat)
'''

#w/o the original categorical vars
features_final = pd.get_dummies(features_log_minmax_transform, drop_first=True)
#using the drop_first we will exclude the first level of each variable making it the reference level
#if we don't do that, we'll have perfect multicollinearity in the data and the model will nto work. 

income = income_raw.replace(['<=50K', '>50K'], [0, 1])
print ("Proportion of above 50k=",round(income.mean(),2), " - which is correct.")

# Print the number of features after one-hot encoding
encoded = list(features_final.columns)
print ("\n")
print ("{} total features after one-hot encoding and dropping the reference levels.".format(len(encoded)))

# Uncomment the following line to see the encoded feature names
# print
# print (encoded)
# too much text
Proportion of above 50k= 0.25  - which is correct.


95 total features after one-hot encoding and dropping the reference levels.

Shuffle and Split Data

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.

Run the code cell below to perform this split.

In [16]:
# Split the 'features' and 'income' data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(features_final, 
                                                    income, 
                                                    test_size = 0.2, 
                                                    random_state = 0)

# Show the results of the split
print ("Training set has {} samples.".format(X_train.shape[0]))
print ("Testing set has {} samples.".format(X_test.shape[0]))
Training set has 36177 samples.
Testing set has 9045 samples.

Evaluating Model Performance

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.

Metrics and the Naive Predictor

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:

$$ F_{\beta} = (1 + \beta^2) \cdot \frac{precision \cdot recall}{\left( \beta^2 \cdot precision \right) + recall} $$

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).

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.

Note: Recap of accuracy, precision, recall

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).

Precision tells us what proportion of messages we classified as spam, actually were spam. 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

[True Positives/(True Positives + False Positives)]

Recall(sensitivity) tells us what proportion of messages that actually were spam were classified by us as spam. 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

[True Positives/(True Positives + False Negatives)]

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).

Question 1 - Naive Predictor Performace

  • 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.

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.

HINT:

  • 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.
  • Our Recall score(True Positives/(True Positives + False Negatives)) in this setting becomes 1 as we have no False Negatives.
In [17]:
'''
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.
FP = income.count() - TP # Specific to the naive case

TN = 0 # No predicted negatives in the naive case
FN = 0 # No predicted negatives in the naive case
'''
# TODO: Calculate accuracy, precision and recall
TP = np.sum(income) * 1.
total = income.count() * 1.

accuracy = ( TP + 0 ) / total
recall = TP / ( TP + 0 )
precision = TP / ( TP + total - TP )

# TODO: Calculate F-score using the formula above for beta = 0.5 and correct values for precision and recall.
beta = 0.5
fscore = (1 + beta**2) * (precision * recall) / ((beta**2 * precision) + recall)

# Print the results 
print ("Naive Predictor: [Accuracy score: {:.4f}, F-score: {:.4f}]".format(accuracy, fscore))
Naive Predictor: [Accuracy score: 0.2478, F-score: 0.2917]

Supervised Learning Models

The following are some of the supervised learning models that are currently available in scikit-learn that you may choose from:

  • Gaussian Naive Bayes (GaussianNB)
  • Decision Trees
  • Ensemble Methods (Bagging, AdaBoost, Random Forest, Gradient Boosting)
  • K-Nearest Neighbors (KNeighbors)
  • Stochastic Gradient Descent Classifier (SGDC)
  • Support Vector Machines (SVM)
  • Logistic Regression

Question 2 - Model Application

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

  • Describe one real-world application in industry where the model can be applied.
  • What are the strengths of the model; when does it perform well?
  • What are the weaknesses of the model; when does it perform poorly?
  • What makes this model a good candidate for the problem, given what you know about the data?

HINT:

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.

Answer:

Logistic Regression
  • Application

Logistic Regression truly is the workhorse for classification problems. It is very popular for predictive modeling in marketing (to identify potential customers), risk (fraud detection) and many other cases. For example, this model can be used to identify transactions that are in high probability fraudulent by finding patterns in the data not observable to naked eye.

  • Strengths

Logistic regression is computationally cheap to train and tends to perform well, not easily susceptible to overfitting.

  • Weaknesses

Logistic regression does not perform well when the data cannot be linearly separated but in such cases the features can be transformed to allow it to perform better.

  • Why does it apply to our problem?

It will train quickly and output estimated probabilities which will allow us to sort the individuals in the order of likelihood to respond to CharityML, so that we can start our marketing from the "top" - most likely to have income >50K are also most likely to respond and donate.

Decision Tree
  • Application

Decision tree can be used for drilling into the data and uncovering deep patterns. It is very intuitive to understand and easy to present visually.

  • Strengths

Decision tree does not require any feature transformation, can be used for both discreet and continuous target variables.

  • Weaknesses

Decision tree is very likely to overfit as it can easily memorize patterns about the training data that do not necessarily apply to the new data.

  • Why does it apply to our problem?

It will also train quickly and output easily interpretable results. Included in the output will be the feature importance statistic that would allow to keep the most useful features in the final model. So, it can be used both for feature selection and modeling.

Ensemble Method: Random Forests
  • Application

Random forest is often used as the next step after training decision trees. It too can be used for marketing, customer analytics and fraud detection.

  • Strengths

Random forest is like a decision tree on steroids - it trains any number of individual decision trees and then averages their results to reduce overfit and produce a generalizable model.

  • Weaknesses

Random forests are computationally more expensive and their outputs are not interpretable as individual decision trees. Also all the underlying models have to be used for scoring new observations.

  • Why does it apply to our problem?

We have over 30k observations and over a dozen features - so we have enough observations and decent number of features for random forests to build a good generalizable model.

Main reference: Raschka, Sebastian, and Vahid Mirjalili. Python Machine Learning: Machine Learning and Deep Learning with Python, Scikit-Learn, and TensorFlow. Packt, 2017.

Implementation - Creating a Training and Predicting Pipeline

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. In the code block below, you will need to implement the following:

  • Import fbeta_score and accuracy_score from sklearn.metrics.
  • Fit the learner to the sampled training data and record the training time.
  • Perform predictions on the test data X_test, and also on the first 300 training points X_train[:300].
    • Record the total prediction time.
  • Calculate the accuracy score for both the training subset and testing set.
  • Calculate the F-score for both the training subset and testing set.
    • Make sure that you set the beta parameter!
In [18]:
# TODO: Import two metrics from sklearn - fbeta_score and accuracy_score

def train_predict(learner, sample_size, X_train, y_train, X_test, y_test, beta=0.5): 
    '''
    inputs:
       - learner: the learning algorithm to be trained and predicted on
       - sample_size: the size of samples (number) to be drawn from training set
       - X_train: features training set
       - y_train: income training set
       - X_test: features testing set
       - y_test: income testing set
    '''
    
    results = {}
    
    # TODO: Fit the learner to the training data using slicing with 'sample_size' using .fit(training_features[:], training_labels[:])
    start = time() # Get start time
    
    learner = learner
    learner.fit(X_train[:sample_size], y_train[:sample_size])
    
    end = time() # Get end time
    
    # TODO: Calculate the training time
    results['train_time'] = end - start
        
    # TODO: Get the predictions on the test set(X_test),
    #       then get predictions on the first 300 training samples(X_train) using .predict()
    start = time() # Get start time
    predictions_test = learner.predict(X_test)
    predictions_train = learner.predict(X_train[:300])
    end = time() # Get end time
    
    # TODO: Calculate the total prediction time
    results['pred_time'] = end - start
            
    # TODO: Compute accuracy on the first 300 training samples which is y_train[:300]
    results['acc_train'] = accuracy_score (y_train[:300], predictions_train)
    
    # TODO: Compute accuracy on test set using accuracy_score()
    results['acc_test'] = accuracy_score (y_test, predictions_test)
    
    # TODO: Compute F-score on the the first 300 training samples using fbeta_score()
    results['f_train'] = fbeta_score (y_train[:300], predictions_train, beta)
        
    # TODO: Compute F-score on the test set which is y_test
    results['f_test'] = fbeta_score (y_test, predictions_test, beta)
       
    # Success
    print ("{} trained on {} samples.".format(learner.__class__.__name__, sample_size) )
        
    # Return the results
    return results

Implementation: Initial Model Evaluation

In the code cell, you will need to implement the following:

  • Import the three supervised learning models you've discussed in the previous section.
  • Initialize the three models and store them in 'clf_A', 'clf_B', and 'clf_C'.
    • Use a 'random_state' for each model you use, if provided.
    • Note: Use the default settings for each model — you will tune one specific model in a later section.
  • Calculate the number of records equal to 1%, 10%, and 100% of the training data.
    • Store those values in 'samples_1', 'samples_10', and 'samples_100' respectively.

Note: Depending on which algorithms you chose, the following implementation may take some time to run!

In [21]:
#ME: Test on a single model first before testing a 3*3 grid below

# initialize
clf_A = LogisticRegression(random_state=3)

# sample
samples_1 = int(y_train.count() * 0.01)

# fit
clf_A.fit(X_train[samples_1:], y_train[samples_1:])

# collect results
results_A = train_predict(clf_A, samples_1, X_train, y_train, X_test, y_test, beta=0.5)
print (results_A)
#OK, looks good, performs pretty well
LogisticRegression trained on 361 samples.
{'train_time': 0.002034902572631836, 'pred_time': 0.0049610137939453125, 'acc_train': 0.84999999999999998, 'acc_test': 0.8231066887783306, 'f_train': 0.71721311475409844, 'f_test': 0.64030990087729289}
In [22]:
# TODO: Initialize the three models
clf_A = LogisticRegression(random_state=3)
clf_B = DecisionTreeClassifier(random_state=3)
clf_C = RandomForestClassifier(random_state=3)

# TODO: Calculate the number of samples for 1%, 10%, and 100% of the training data
# HINT: samples_100 is the entire training set i.e. len(y_train)
# HINT: samples_10 is 10% of samples_100
# HINT: samples_1 is 1% of samples_100
samples_100 = int(y_train.count() * 1)
samples_10 = int(y_train.count() * 0.1)
samples_1 = int(y_train.count() * 0.01)

# Collect results on the learners
results = {}
for clf in [clf_A, clf_B, clf_C]:
    clf_name = clf.__class__.__name__
    results[clf_name] = {}
    for i, samples in enumerate([samples_1, samples_10, samples_100]):
        results[clf_name][i] = \
        train_predict(clf, samples, X_train, y_train, X_test, y_test)
LogisticRegression trained on 361 samples.
LogisticRegression trained on 3617 samples.
LogisticRegression trained on 36177 samples.
DecisionTreeClassifier trained on 361 samples.
DecisionTreeClassifier trained on 3617 samples.
DecisionTreeClassifier trained on 36177 samples.
RandomForestClassifier trained on 361 samples.
RandomForestClassifier trained on 3617 samples.
RandomForestClassifier trained on 36177 samples.
In [23]:
# Run metrics visualization for the three supervised learning models chosen
vs.evaluate(results, accuracy, fscore)
# nice, looks really pretty

Observations:

  • Random forest (RF) takes longest to fit and predict as expected
  • Both decision tree (DT) and RF overfit a whole lot more than logistic regression (LR) does
  • LR has the lowest variance - more realistic performance
  • DT and RF give highly optimistic performance on the training set even when using the whole training data set
  • So, based on these observations, I would pick LR

Improving Results

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.

Question 3 - Choosing the Best Model

  • 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.

HINT: 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:

  • metrics - F score on the testing when 100% of the training data is used,
  • prediction/training time
  • the algorithm's suitability for the data.

Answer:

Among the three algorithms tested here I would recommend using Logistic Regression. Its F1-score is 0.7 on the training data is lower than DT and RF which are about 0.9 but it also has a lower variance (gap) with F1-score of also close to 0.7 on the testing data while DT and RF have about the same or lower value.

RF is my runner up because of its complexity, longer training time and unrealistically high performance on the training data set (overfitting).

Logistic Regression performs reasonably well in our case and, in general, handles both continuous and dummy features well.

Question 4 - Describing the Model in Layman's Terms

  • 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.

HINT:

When explaining your model, if using external resources please include all citations.

Answer:

Dear Layman at CharityML,

Given our goal of finding people who are willing to contribute to your charity, let's predict an individual's income and use it as a proxy for willingness to contribute to CharityML.

We start by creating a dummy target variable "income" with values yes(1)/no(0) where yes(1) stands for income that is above 50k dollars. Now let's imagine that the "no's" can differ from each other. Two people (A and B) who both have income=0 can still differ from each other - A's underlying value of income could be 0.1 (very unlikely that income is above 50k) and B's was 0.9 (very likely that income is above 50k). But this underlying value is invisible to us. What can help us is the logistic regression which will represent our dummy yes/no variable as a continuous variable in the range of 0 to 1.

Our next step is to collect enough useful characteristics to help us explain the difference between A and B. Why is A=0.1 and B=0.9? Perhaps, their demographic features like gender, race, education and married status have something to do with their income being above or below the 50k threshold. The logistic regression can accept these demographic features and determine how they are related to our target variable.

Once we fit our logistic regression on a training sample of people for whom we know both their demographic features and the value of the target variable, we can then score new people for whom we have the features but not the target variable.

After we score the new people the logistic regression will produce predicted probabilities that they above 50k threshold. We can then sort the individuals in the descending order of the probability and start approaching them for donations thereby maximizing our chances of success. Alternatively, we can approach all the people with the probability above a certain "cutoff" value we chose depending on our circumstances.

Implementation: Model Tuning

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:

  • Import sklearn.grid_search.GridSearchCV and sklearn.metrics.make_scorer.
  • Initialize the classifier you've chosen and store it in clf.
    • Set a random_state if one is available to the same state you set before.
  • Create a dictionary of parameters you wish to tune for the chosen model.
    • Example: parameters = {'parameter' : [list of values]}.
    • Note: Avoid tuning the max_features parameter of your learner if that parameter is available!
  • Use make_scorer to create an fbeta_score scoring object (with $\beta = 0.5$).
  • Perform grid search on the classifier clf using the 'scorer', and store it in grid_obj.
  • Fit the grid search object to the training data (X_train, y_train), and store it in grid_fit.

Note: Depending on the algorithm chosen and the parameter list, the following implementation may take some time to run!

In [24]:
#ME: tune the model manually first to understand better

lr = LogisticRegression(C=100.0, random_state=1)
lr.fit(X_train, y_train) 

print ("Probabilities for class 0 (nonevent) and class 1 (event) for the first 3 observations.")
print (lr.predict_proba(X_test[:3]))

print ("\n")
print ("Predicted classes for the first 3 observations.")
print (lr.predict(X_test[:3]))
#cutoff is 0.5 by default 

# Manual search 
#Overfitting occurs because of high model complexity. To keep complexity lower, we use regularization.
#L2 Regularization - adds a bias on weights into the cost fn to penalize extreme weights (coeffs)
#Hyper parameter C is the inverse of Lambda, so smaller C means a stricter, stonger regularization
#Lambda is the regularization parameter - the larger, the strong the regularization, penalization of model complexity - the less likely to overfit
#C is the inverse-regularization parameter

weights, params = [], []
for c in np.arange(-5, 5):
    lr = LogisticRegression(C=10.**c, random_state=3)
    lr.fit(X_train, y_train) 
    weights.append(lr.coef_[0])
    params.append(10.**c)

# Plot weights for different C's for the first 3 features, whatever they are
weights = np.array(weights)
plt.plot(params, weights[:, 0],
         label='Feature 1')
plt.plot(params, weights[:, 1], linestyle='--',
         label='Feature 2')
plt.plot(params, weights[:, 2], linestyle=':',
         label='Feature 3')
plt.ylabel('weight coefficient')
plt.xlabel('C')
plt.legend(loc='upper left')
plt.xscale('log')
plt.show()

print ("Plot shows that larger C means lower lambda - lower penalty for model complexity, which is why the weights increase.")
Probabilities for class 0 (nonevent) and class 1 (event) for the first 3 observations.
[[ 0.81990396  0.18009604]
 [ 0.77510663  0.22489337]
 [ 0.85646667  0.14353333]]


Predicted classes for the first 3 observations.
[0 0 0]
Plot shows that larger C means lower lambda - lower penalty for model complexity, which is why the weights increase.
In [25]:
# TODO: Import 'GridSearchCV', 'make_scorer', and any other necessary libraries
#ME: prefer to import everything on top
#Also, split this section into separate parts

# TODO: Initialize the classifier
clf = LogisticRegression()
# C: default: 1.0 Inverse of regularization strength; must be a positive float. 
# Like in support vector machines, smaller values specify stronger regularization.
# also default - penalty='l2'

# TODO: Create the parameters list you wish to tune, using a dictionary if needed.
# HINT: parameters = {'parameter_1': [value1, value2], 'parameter_2': [value1, value2]}

print ("\n Testing 1 parameter C with 10 settings on both L1 and L2 regularizations.")

c_list = []
for c in np.arange(-5, 5):
    C=10.**c
    c_list.append(C)
    
parameters = { "C":c_list , "penalty":["l2","l1"]}
# had to search penalty too to get better results
 Testing 1 parameter C with 10 settings on both L1 and L2 regularizations.
In [26]:
# TODO: Make an fbeta_score scoring object using make_scorer()
beta = 0.5
scorer = make_scorer(fbeta_score, beta=beta)

# TODO: Perform grid search on the classifier using 'scorer' as the scoring method using GridSearchCV()
grid_obj = GridSearchCV(clf, parameters, scoring=scorer)

# TODO: Fit the grid search object to the training data and find the optimal parameters using fit()
grid_fit = grid_obj.fit(X_train, y_train)
print ("\n What is inside the grid_fit? \n")
print (grid_fit)

# Get the estimator
best_clf = grid_fit.best_estimator_
print ("\n What is inside the best_clf? \n")
print (best_clf)
# C is 10 and l2 - so, not much different from default
 What is inside the grid_fit? 

GridSearchCV(cv=None, error_score='raise',
       estimator=LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,
          intercept_scaling=1, max_iter=100, multi_class='ovr', n_jobs=1,
          penalty='l2', random_state=None, solver='liblinear', tol=0.0001,
          verbose=0, warm_start=False),
       fit_params={}, iid=True, n_jobs=1,
       param_grid={'C': [1.0000000000000001e-05, 0.0001, 0.001, 0.01, 0.10000000000000001, 1.0, 10.0, 100.0, 1000.0, 10000.0], 'penalty': ['l2', 'l1']},
       pre_dispatch='2*n_jobs', refit=True,
       scoring=make_scorer(fbeta_score, beta=0.5), verbose=0)

 What is inside the best_clf? 

LogisticRegression(C=0.10000000000000001, class_weight=None, dual=False,
          fit_intercept=True, intercept_scaling=1, max_iter=100,
          multi_class='ovr', n_jobs=1, penalty='l2', random_state=None,
          solver='liblinear', tol=0.0001, verbose=0, warm_start=False)
In [27]:
# Make predictions using the unoptimized (stock) and best model
predictions = (clf.fit(X_train, y_train)).predict(X_test)
best_predictions = best_clf.predict(X_test)

# Question 5 - Final Model Evaluation

# Report the before-and-afterscores
print ("\n Beta used for grid search and evaluation:",beta)
print ("\n Unoptimized model\n------")
print ("Accuracy score on testing data: {:.4f}".format(accuracy_score(y_test, predictions)))
print ("Fbeta-score on testing data: {:.4f}".format(fbeta_score(y_test, predictions, beta = beta)))
print ("Still, pretty good! \n")

print ("\nOptimized Model\n------")
print ("Final accuracy score on the testing data: {:.4f}".format(accuracy_score(y_test, best_predictions)))
print ("Final Fbeta-score on the testing data: {:.4f}".format(fbeta_score(y_test, best_predictions, beta = beta)))
print ("Negligible improvement over the default model \n")

print ("\n Bottom line: a logistic regression even on default settings is much better than the Naive Predictor that we examined above.")
print ("Naive Predictor was: [Accuracy score: {:.4f}, F-score: {:.4f}]".format(accuracy, fscore))
 Beta used for grid search and evaluation: 0.5

 Unoptimized model
------
Accuracy score on testing data: 0.8419
Fbeta-score on testing data: 0.6832
Still, pretty good! 


Optimized Model
------
Final accuracy score on the testing data: 0.8421
Final Fbeta-score on the testing data: 0.6849
Negligible improvement over the default model 


 Bottom line: a logistic regression even on default settings is much better than the Naive Predictor that we examined above.
Naive Predictor was: [Accuracy score: 0.2478, F-score: 0.2917]

Question 5 - Final Model Evaluation

  • What is your optimized model's accuracy and F-score on the testing data?
  • Are these scores better or worse than the unoptimized model?
  • How do the results from your optimized model compare to the naive predictor benchmarks you found earlier in Question 1?_

Note: Fill in the table below with your results, and then provide discussion in the Answer box.

Results:

Metric Naive Predictor Unoptimized Model Optimized Model
Accuracy Score 0.2478 0.8419 0.8421
F-score 0.2917 0.6832 0.6849

Answer:

The optimized model is only marginally better than the unoptimized one. The gains are not enough to warrant expending the time and computing resources. But this is just in this particular case - obviously, in other cases optimization might be very beneficial.

The performance of the simple unoptimized logistic regression even on default settings is already much better than the Naive Predictor (reminder: it always predicts an individual makes more than $50k).

Therefore, even this simple logistic regression is so much better than a simple "rule-of-thumb" naive predictor.


Feature Importance

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.

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.

Question 6 - Feature Relevance Observation

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?

Answer:

My speculations. I would rank the following five demographic features in the descending order of importance: age, education, sex, race and marital status. This is based on my common sense reasoning.

Older people are bound to have more experience and more experienced people make more money. Also more educated people are bound to have higher paying jobs, men make more money for the same work as women (sad but still true), whites make more money for the same work as non-whites (also sad but still true), and married people make more than single ones (on this one the jury is still out why - deserves own project really).

Implementation - Extracting Feature Importance

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.

In the code cell below, you will need to implement the following:

  • Import a supervised learning model from sklearn if it is different from the three used earlier.
  • Train the supervised model on the entire training set.
  • Extract the feature importances using '.feature_importances_'.
In [28]:
# Feature Importance - cannot use logistic, so let's pick random forest

# TODO: Train the supervised model on the training set using .fit(X_train, y_train)
model = RandomForestClassifier(random_state=3)
model.fit(X_train, y_train) 

# TODO: Extract the feature importances using .feature_importances_ 
importances = model.feature_importances_ 
#importances quickly decline after the first 5: age is the most important one

# Plot
vs.feature_plot(importances, X_train, y_train)

Question 7 - Extracting Feature Importance

Observe the visualization created above which displays the five most relevant features for predicting if an individual makes at most or above \$50,000.

  • How do these five features compare to the five features you discussed in Question 6?
  • If you were close to the same answer, how does this visualization confirm your thoughts?
  • If you were not close, why do you think these features are more relevant?

Answer:

My speculations were right for 3 out of 5 features. My guessed correctly the presence of age, marital status and education as obvious from the visualizations. In the order of importance: age, hours-per-week, married, capital-gain and education. So, I got the order right for age > married but I was wrong in guessing education > married. This seems to suggest that getting married is a better investment than education!

I forgot about hours-per-week though - which came up in the importances graph. It does make sense to me now. Annual income is proportional to the hours worked per week - at least for hourly workers, but maybe for salaried ones as well. This is not a demographic feature but rather a component in the annual income calculation. Perhaps, this model would be better off if we used the hourly wage equivalent of the annual salary.

Capital-gain is also in the graph and makes sense too now. It must be the earning from stock dividends etc which directly add to the annual income. This is also an ingredient of the annual salary but not a demographic feature.

Overall, it seems that the model should perform reasonably well with just these top five features. These five make up more than 60% of the importance of all the features. So, all the other features combined contribute less than 40% and it might be OK to drop them if we wished to.

Feature Selection

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.

In [29]:
# Reduce the feature space
X_train_reduced = X_train[X_train.columns.values[(np.argsort(importances)[::-1])[:5]]]
X_test_reduced = X_test[X_test.columns.values[(np.argsort(importances)[::-1])[:5]]]

# Train on the "best" model found from grid search earlier
clf = (clone(best_clf)).fit(X_train_reduced, y_train)

# Make new predictions
reduced_predictions = clf.predict(X_test_reduced)

# Report scores from the final model using both versions of data
print ("\n Optimized Final Model trained on full data\n------")
print ("Accuracy on testing data: {:.4f}".format(accuracy_score(y_test, best_predictions)))
print ("Fbeta-score on testing data: {:.4f}".format(fbeta_score(y_test, best_predictions, beta = beta)))

print ("\nFinal Model trained on reduced data\n------")
print ("Accuracy on testing data: {:.4f}".format(accuracy_score(y_test, reduced_predictions)))
print ("Fbeta-score on testing data: {:.4f}".format(fbeta_score(y_test, reduced_predictions, beta = beta)))

print ("\n Indeed - Fbeta-score is now 0.6499 which is only a little bit worse than the optimal model 0.6849 we trained above.")
print ("In a production environment such a sacrifice might be worth the savings in training and scoring time and ease of implementation.") 
 Optimized Final Model trained on full data
------
Accuracy on testing data: 0.8421
Fbeta-score on testing data: 0.6849

Final Model trained on reduced data
------
Accuracy on testing data: 0.8271
Fbeta-score on testing data: 0.6499

 Indeed - Fbeta-score is now 0.6499 which is only a little bit worse than the optimal model 0.6849 we trained above.
In a production environment such a sacrifice might be worth the savings in training and scoring time and ease of implementation.

Question 8 - Effects of Feature Selection

  • 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?
  • If training time was a factor, would you consider using the reduced data as your training set?

Answer:

Metric Optimized Model Final Model
Accuracy Score 0.8421 0.8271
F-score 0.6849 0.6499

The final model's Accuracy and F-score are only marginally worse than the full model with more than a dozen features. In the "wild" a slight sacrifice of perfomance might be tolerable in exchange for saving resources on procuring and processing more features.

Also, given a lot of observations and a complex model, training and scoring time might be the determing factor to use the model with fewer features. It really depends on the circumstances: if we need to refresh the model and score new observations often, then a simpler leaner model might be preferred.

The End.

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
File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.