Supervised Learning: Finding Donors for CharityML


Getting Started

In this project, I will employ several supervised algorithms to accurately model individuals' income using data collected from the 1994 U.S. Census. I will then choose the best candidate algorithm from preliminary results and further optimize this algorithm to best model the data. My goal with this implementation is to construct a model that accurately predicts whether an individual makes more than $50,000.

Understanding an individual's income can help the 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, I will infer this value from other publically available features.

Data Source: https://archive.ics.uci.edu/ml/datasets/Census+Income

In [109]:
# Import libraries necessary for this project
import numpy as np
import pandas as pd
from time import time
from IPython.display import display # Allows the use of display() for DataFrames
import seaborn as sns
import matplotlib.pyplot as pl

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

# Pretty display for notebooks
%matplotlib inline

# Load the Census dataset
data = pd.read_csv("census.csv")

# Success - Display the first record
display(data.head(n=5))
age workclass education_level education-num marital-status occupation relationship race sex capital-gain capital-loss hours-per-week native-country income
0 39 State-gov Bachelors 13.0 Never-married Adm-clerical Not-in-family White Male 2174.0 0.0 40.0 United-States <=50K
1 50 Self-emp-not-inc Bachelors 13.0 Married-civ-spouse Exec-managerial Husband White Male 0.0 0.0 13.0 United-States <=50K
2 38 Private HS-grad 9.0 Divorced Handlers-cleaners Not-in-family White Male 0.0 0.0 40.0 United-States <=50K
3 53 Private 11th 7.0 Married-civ-spouse Handlers-cleaners Husband Black Male 0.0 0.0 40.0 United-States <=50K
4 28 Private Bachelors 13.0 Married-civ-spouse Prof-specialty Wife Black Female 0.0 0.0 40.0 Cuba <=50K

Data Exploration

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

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 [2]:
# Total number of records
n_records = len(data)

# Number of records where individual's income is more than $50,000
n_greater_50k = len(data[data['income']=='>50K'])   #pythonic way of getting the count

# Number of records where individual's income is at most $50,000
n_at_most_50k = data[data['income']=='<=50K'].count()['income'] #pandas way of getting the count

# Percentage of individuals whose income is more than $50,000
greater_percent = round(n_greater_50k*100/n_records,2)

# Print the results
print("Total number of records: {}".format(n_records))
print("Individuals making more than $50,000: {}".format(n_greater_50k))
print("Individuals making at most $50,000: {}".format(n_at_most_50k))
print("Percentage of individuals making more than $50,000: {}%".format(greater_percent))
Total number of records: 45222
Individuals making more than $50,000: 11208
Individuals making at most $50,000: 34014
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 [114]:
sns.set(style="ticks")

sns.pairplot(data, hue="income")
Out[114]:
<seaborn.axisgrid.PairGrid at 0x2491a4ba20>

Few observations from the scatter matrix

  • The capital gain and capital loss histograms are mostly orange in color, showing that most data points in those features belong to people with higher income level
  • Education num histogram shows that the orange distribution is skewed more towards the right, indicating that people with higher income tends have a higher education num

Preparing the Data

Before data can be used as input for machine learning algorithms, it must be cleaned, formatted, and restructured. 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'.

Plotting a histogram of these two features. Note the range of the values present and how they are distributed.

In [3]:
# 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)

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 I will translate the values by a small amount above 0 to apply the the logarithm successfully. Again, note the range of values and how they are distributed.

In [4]:
# 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))

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

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. I will use sklearn.preprocessing.MinMaxScaler for this.

In [5]:
# Import sklearn.preprocessing.StandardScaler
from sklearn.preprocessing import MinMaxScaler

# 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))
C:\Users\Fahad\Anaconda3\lib\site-packages\sklearn\preprocessing\data.py:334: DataConversionWarning: Data with input dtype int64, float64 were all converted to float64 by MinMaxScaler.
  return self.partial_fit(X, y)
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 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.

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 simply encode these two categories as 0 and 1, respectively.

In [92]:
# Print all columns

print(list(features_log_minmax_transform.columns))

categorical = ['age','workclass','education_level','marital-status','occupation','relationship','race','sex','native-country']
['age', 'workclass', 'education_level', 'education-num', 'marital-status', 'occupation', 'relationship', 'race', 'sex', 'capital-gain', 'capital-loss', 'hours-per-week', 'native-country']
In [84]:
# TOne-hot encode the 'features_log_minmax_transform' data using pandas.get_dummies()

features_final = pd.get_dummies(features_log_minmax_transform[categorical])
features_final[numerical] = features_log_minmax_transform[numerical]

# Encode the 'income_raw' data to numerical values
income = income_raw.replace({'<=50K': 0, '>50K': 1})

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

# Uncomment the following line to see the encoded feature names
#print(encoded)
103 total features after one-hot encoding.

Shuffle and Split Data

Now all categorical variables have been converted into numerical features, and all numerical features have been normalized. I 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.

In [93]:
# Import train_test_split
from sklearn.model_selection import train_test_split

# 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, I will investigate four different algorithms, and determine which is best at modeling the data. Three of these algorithms will be supervised learners, 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. I will 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 important to consider the naive prediction for this 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 this case, 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).

Naive Predictor Performace

  • 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 [94]:
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

# Calculate accuracy, precision and recall
accuracy = TP/len(income)
recall = TP/(TP+FN)
precision = TP/(TP+FP)

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

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

Supervised Learning Models

I will apply the below models on this dataset

Logistic Regression:

  • Strengths: Easy to interpret as output can be interpreted as a probability, can use l1/l2 regularization to avoid overfitting
  • Weaknesses: Regression assumes that the relationship between the predictor variable and dependent variable is unidirectional (be it positive or negative correlation, linear or non-linear)
  • Why this model: The sklearn implementation has a parameter to balance the weights of the classes, which will be useful as the data is imbalanced. Having the probability of the outcome can be really useful for identifying border line cases.

Random Forest:

  • Strengths: Good to parallel or distributed computing, calculates feature importance, does not require independent features
  • Weaknesses: Not easy to interpret, prone to overfitting
  • Why this model: The sklearn implementation has a parameter to balance the weights of the classes, which will be useful as the data is imbalanced. Since we don't know which features are dependent in the data, this model can be a good choice

Gradient Boosting:

  • Strengths: Good for unbalanced data sets due to weighting at every step, calculates feature importance, does not require independent features
  • Weaknesses: Not easy to interpret, prone to overfitting, since it is sequential takes longer to train, can be harder to tune
  • Why this model: Due to re-weighting at every step, it performs well for imbalanced data, which will be useful as the data is imbalanced. Since we don't know which features are dependent in the data, this model can be a good choice

Creating a Training and Predicting Pipeline

To properly evaluate the performance of each model, it's important to create a training and predicting pipeline to quickly and effectively train models using various sizes of training data and perform predictions on the testing data

In [97]:
# Import two metrics from sklearn - fbeta_score and accuracy_score
from sklearn.metrics import accuracy_score
from sklearn.metrics import fbeta_score

def train_predict(learner, sample_size, X_train, y_train, X_test, y_test): 
    '''
    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 = {}
    
    # Fit the learner to the training data using slicing with 'sample_size' using .fit(training_features[:], training_labels[:])
    start = time() # Get start time
    learner.fit(X_train[:sample_size], y_train[:sample_size])
    end = time() # Get end time
    
    # Calculate the training time
    results['train_time'] = end-start
        
    # 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
    
    # Calculate the total prediction time
    results['pred_time'] = end-start
            
    # Compute accuracy on the first 300 training samples which is y_train[:300]
    results['acc_train'] = accuracy_score(y_train[:300],predictions_train)
        
    # Compute accuracy on test set using accuracy_score()
    results['acc_test'] = accuracy_score(y_test,predictions_test)
    
    # Compute F-score on the the first 300 training samples using fbeta_score()
    results['f_train'] = fbeta_score(y_train[:300],predictions_train, beta=0.5)
        
    # Compute F-score on the test set which is y_test
    results['f_test'] = fbeta_score(y_test,predictions_test,beta=0.5)
       
    # Success
    print("{} trained on {} samples.".format(learner.__class__.__name__, sample_size))
        
    # Return the results
    return results

Initial Model Evaluation

  • Using 1%, 10%, and 100% of the training data to evaluate performance change
In [100]:
# Import the three supervised learning models from sklearn

from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import GradientBoostingClassifier

# Initialize the three models

clf_A = LogisticRegression(class_weight='balanced',random_state=22)
clf_B = RandomForestClassifier(class_weight='balanced',random_state=22)
clf_C = GradientBoostingClassifier(random_state=22)

# Calculate the number of samples for 1%, 10%, and 100% of the training data
# samples_100 is the entire training set
# samples_10 is 10% of samples_100
# samples_1 is 1% of samples_100
samples_100 = len(y_train)
samples_10 = int(len(y_train)/10)
samples_1 = int(len(y_train)/100)

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

# Run metrics visualization for the three supervised learning models chosen
vs.evaluate(results, accuracy, fscore)
C:\Users\Fahad\Anaconda3\lib\site-packages\sklearn\linear_model\logistic.py:433: FutureWarning: Default solver will be changed to 'lbfgs' in 0.22. Specify a solver to silence this warning.
  FutureWarning)
LogisticRegression trained on 361 samples.
LogisticRegression trained on 3617 samples.
C:\Users\Fahad\Anaconda3\lib\site-packages\sklearn\linear_model\logistic.py:433: FutureWarning: Default solver will be changed to 'lbfgs' in 0.22. Specify a solver to silence this warning.
  FutureWarning)
C:\Users\Fahad\Anaconda3\lib\site-packages\sklearn\linear_model\logistic.py:433: FutureWarning: Default solver will be changed to 'lbfgs' in 0.22. Specify a solver to silence this warning.
  FutureWarning)
LogisticRegression trained on 36177 samples.
C:\Users\Fahad\Anaconda3\lib\site-packages\sklearn\ensemble\forest.py:246: FutureWarning: The default value of n_estimators will change from 10 in version 0.20 to 100 in 0.22.
  "10 in version 0.20 to 100 in 0.22.", FutureWarning)
RandomForestClassifier trained on 361 samples.
RandomForestClassifier trained on 3617 samples.
RandomForestClassifier trained on 36177 samples.
GradientBoostingClassifier trained on 361 samples.
GradientBoostingClassifier trained on 3617 samples.
GradientBoostingClassifier trained on 36177 samples.

Improving Results

I will choose the best model and then perform a grid search optimization for the model over the entire training set (X_train and y_train) by tuning at least model parameters to improve upon the untuned model's F-score.

Best Model - Gradient Boosting

Gradient Boosting is the most appropriate for the task of identifying individuals that make more than $50,000 due to the below observations:

Metrics (F-score): When 100% of the training data is used, Gradient Boosting performs the best. Random Forest is a close second. Whereas Logistic Regression has the lowest F-score.

Prediction/training time: Logistic Regression takes the least amount for training followed by Random Forest. Gradient Boosted takes the most time for predicting.

Algorithm's suitability for the data: Based on performance, gradient boosting is the best algorithm. Though logistic regression takes less time than Gradient Boosted to train, with 55k rows of data, this is not a big consideration t this stage.The data is imbalanced. Having an algorithm, which is built to handle imbalanced data is an important consideration, which Gradient Boosting does very well. Also, Gradient Boosted can provide the feature importance which can be really useful to the organization.

About Gradient Boosting

Gradient Boosting (GB) is one of the classification algorithms from the ensemble methods. Ensemble methods use the outcome of several weak learners to create a strong learner. For CharityML, we will use GB to classify between two outcomes, income more than $50k or less based on the feature attributes.

How the model works: When the model is fed an input of attributes and outcomes, it learns how do these attributes cause the outcome to be a positive or a negative outcome. GB works by creating several decision trees. A decision tree uses every feature to answer a series of yes/no questions and building a model based on these answers. The GB algorithm sequentially creates several decision trees. At every step, the GB evaluates the trees and learns from the trees where the results were poor. Hence, it is a corrective algorithm. At the end of all steps, the GB has created a model which has learnt from all previous trees to come up with the best model.

Training: The available data is split between training(80 percent) and test data set(20 percent). During training, the model learns from the training data to assign appropriate weights to each decision tree to determine which features are more important. By the end of training, the model is created with the collective intelligence of several decision trees.

Prediction: The above trained model is then used to predict the outcomes for the test data. Multiple evaluation metrics are then calculated using the model outcome and the actual outcome of the test data. This is used to determine how affective the model is, in predicting outcomes for new data that the model hasn't seen yet.

Model Tuning

I use grid search (GridSearchCV) to fine tune the model parameters

In [6]:
# Import 'GridSearchCV', 'make_scorer', and any other necessary libraries
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import make_scorer

# Initialize the classifier
clf = GradientBoostingClassifier(random_state=22)

# Create the parameters list you wish to tune, using a dictionary if needed
parameters = {'n_estimators': [10,100,1000], 'learning_rate': [0.01,0.1,1], 'max_depth': [2,3,5]}

# TODO: Make an fbeta_score scoring object using make_scorer()
scorer = make_scorer(fbeta_score, beta=0.5)

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

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

# Get the estimator
best_clf = grid_fit.best_estimator_
print("Best parameters are : ")
print(grid_fit.best_params_)

# Make predictions using the unoptimized and model
predictions = (clf.fit(X_train, y_train)).predict(X_test)
best_predictions = best_clf.predict(X_test)

# Report the before-and-afterscores
print("Unoptimized model\n------")
print("Accuracy score on testing data: {}".format(accuracy_score(y_test, predictions)))
print("F-score on testing data: {}".format(fbeta_score(y_test, predictions, beta = 0.5)))
print("\nOptimized Model\n------")
print("Final accuracy score on the testing data: {}".format(accuracy_score(y_test, best_predictions)))
print("Final F-score on the testing data: {}".format(fbeta_score(y_test, best_predictions, beta = 0.5)))
Best parameters are : 
{'learning_rate': 0.1, 'max_depth': 2, 'n_estimators': 1000}
Unoptimized model 
------ 
Accuracy score on testing data: 0.8630182421227197 
F-score on testing data: 0.7395338561802719  
Optimized Model 
------ 
Final accuracy score on the testing data: 0.8703150912106136 
Final F-score on the testing data: 0.7519273418523603

Final Model Evaluation Results

Metric Unoptimized Model Optimized Model
Accuracy Score 0.86 0.87
F-score 0.74 0.75

Observation: Optimized model's accuracy and F-score is slightly higher than the unoptimized model, but it took quite some time for the hyperparameter tuning. The results of the final model are much better than the naive predictor benchmarks.


Feature Importance

An important task when performing supervised learning 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.

In [106]:
# Import a supervised learning model that has 'feature_importances_'
# Train the supervised model on the training set using .fit(X_train, y_train)

# Can use the Gradient Boosted model trained above as it has the feature importance method

# Extract the feature importances using .feature_importances_ 
importances = best_clf.feature_importances_

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

These features do make sense as a predictor of higher income:

  • Being married seems to be a strong indicator of having high income
  • Capital-gain/loss: People who invest in stocks must have disposable income to be invested
  • Higher education level in general would help in higher paying jobs
  • Age: As people grow older they usually build on their experience and earn more

Model Performance with Feature Selection

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. Training it on the same training set with only the top five important features.

In [107]:
# Import functionality for cloning a model
from sklearn.base import clone

# 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("Final Model trained on full data\n------")
print("Accuracy on testing data: {}".format(accuracy_score(y_test, best_predictions)))
print("F-score on testing data: {}".format(fbeta_score(y_test, best_predictions, beta = 0.5)))
print("\nFinal Model trained on reduced data\n------")
print("Accuracy on testing data: {}".format(accuracy_score(y_test, reduced_predictions)))
print("F-score on testing data: {}".format(fbeta_score(y_test, reduced_predictions, beta = 0.5)))
Final Model trained on full data
------
Accuracy on testing data: 0.8703150912106136
F-score on testing data: 0.7519273418523603

Final Model trained on reduced data
------
Accuracy on testing data: 0.8597014925373134
F-score on testing data: 0.7294948397609995

Effects of Feature Selection

  • Considering that we reduced the data by more than 60% (13 to 5 features), the drop in accuracy and F-score is by just a couple of percentage points
  • If training time was a factor, I would consider using the reduced data as the training set