Project: Finding Donors for CharityML

Getting Started

In this project, I will employ several supervised algorithms of your choice 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. 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.

This project was set up and graded by Udacity (Machine Learning Engineer Nanodegree)

Exploring the Data

In [31]:
# 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 supplementary visualization code
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
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

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, we 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'.
In [32]:
# TODO: Total number of records
n_records = data.shape[0]

# TODO: Number of records where individual's income is more than $50,000
n_greater_50k = data[data["income"]==">50K"].shape[0]

# TODO: Number of records where individual's income is at most $50,000
n_at_most_50k = data[data["income"]=="<=50K"].shape[0]

# evaluating the split of the dataset
assert (n_greater_50k + n_at_most_50k) == data.shape[0]

# TODO: Percentage of individuals whose income is more than $50,000
greater_percent = round(n_greater_50k / (n_greater_50k+n_at_most_50k) * 10000)/100

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

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 [33]:
# 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

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 [34]:
# 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.

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

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

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 [36]:
# TODO: One-hot encode the 'features_log_minmax_transform' data using pandas.get_dummies()
features_final = pd.get_dummies(features_log_minmax_transform)

# TODO: Encode the 'income_raw' data to numerical values
income = pd.get_dummies(income_raw)
income = income.drop(['<=50K'], axis=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)))
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. 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 [37]:
# Import train_test_split
from sklearn.cross_validation 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,
                                                    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 classification), 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?

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

tp = np.sum(income)
fp = income.count() - tp

tn = 0
fn = 0

# TODO: Calculate accuracy, precision and recall
accuracy = tp / income.count()
recall = tp / (tp + fn)
precision = tp / (tp + fp)

# TODO: 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: {:.4f}, F-score: {:.4f}]".format(accuracy[0], fscore[0]))
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 we 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

Model Application & the algorithms to take a look at

Decision Trees:

1) Decision Trees can be used in multiple use cases in different industries. A good example would be a fraud detection system at a bank, that tries to find out if a transaction is fraudulent or not. You might have different parameters that make up a fraudulent transaction and you want to find a way to predict fraudulent transactions in the future, so that way, you have some kind of warning system for people working in the legal department of the bank, to detect fraud before it's too late.

2) Decision Trees have the strength to develop a sense for relations between certain parameters and the value we want to predict. They literally build a dependency tree to sort parameters in a way, that makes it easy for the machine - and even for humans - to go a certain way to find the appropriate answer to a question. In case of fraud, the system checks the possible answers the decision tree made up in the first place, and then goes further to the following answers you can give by looking at the data.

In the following picture you can see a simple decision tree for what to do on weekends:


It clearly does well in telling you what parameters are the strongest to fastly predict the answer and is able to build further dependencies of the data in the same manner.

3) Weaknesses of Decision Trees

  • What a decision tree is not able to do is to adapt incoming new data. Once you build the model and you notice, that there's a switch in the data's dependency the whole tree can be forgotten. We can have a drastically different tree. Even slight changes in the data can make the main tree switch in a complete different structure
  • The model is very likely to overfit. The tree can quickly find a very effective way to make dependencies in the data, but it sometimes is very hard to generalize the model. As said before, the models are very sensitive and it is hard to find a good way to perfectly find the spot between underfitting and overfitting
  • Some of the problems are related to the problem of multicollinearity: when two variables both explain the same thing, a decision tree will greedily choose the best one, whereas many other methods will use them both.(
  • One disadvantage is that all terms are assumed to interact. That is, you can't have two explanatory variables that behave independently. Every variable in the tree is forced to interact with every variable further up the tree. This is extremely inefficient if there are variables that have no or weak interactions. (

4) The problem of our dataset is that we have several variables, of which we do not know the dependency to the income we want to predict. A decision tree classifier can help us to identify the most important factor and a path which we can check for a set of variables we have to find out if a person has an income above 50k. The model checks the information gain of each split in the dataset and can quickly tell us which variables are determining if a person gets more than 50K and which variables tell us a person definitely does not. Then, the algorithm adds decision nodes, which can finally identify a person's income if you can't tell by the first feature.

Ensemble Methods:

1) Ensemble Methods help us to optimize simpler algorithms like decision trees. They are used for making recommendations like in the app store (we even did this in class) or for movies. E.g. random forests, they use decision trees in a simple manner for random parameters (columns of data) and aggregate the results from it. This could look like the following:


2) Strengths of Ensemble Methods

The strength of an ensemble method is the way they use weak learners (very simple predictors) and aggregate them into one strong learner.

Caution: Got this from: Ensemble methods can be divided into two groups:

  • sequential ensemble methods where the base learners are generated sequentially (e.g. AdaBoost). The basic motivation of sequential methods is to exploit the dependence between the base learners. The overall performance can be boosted by weighing previously mislabeled examples with higher weight.
  • parallel ensemble methods where the base learners are generated in parallel (e.g. Random Forest). The basic motivation of parallel methods is to exploit independence between the base learners since the error can be reduced dramatically by averaging.

So ensemble methods basically have the strength of aggregating the power of algorithms in an iteration process to find the best solution. Either way - getting better solutions from averaging or exploiting the dependence between learners - help us getting better models.

3) Weaknesses of Ensemble Methods

I got inspired by this answer in Stack Exchange:

  • Models using ensemble methods are hard to interprete and hard to explain because the way the model and the solution is calculated is really hard to comprehend.
  • Boosting:
    • You have a lot of hyperparamters for boosting methods like AdaBoost
    • Models can easily overfit (watch the hyperparameters)
  • Bagging (Bootstrap Aggregating):
    • can be slow to score when complexity rises
  • Random Forests:

4) We already noticed, that our dataset is a good set for using decision trees. Ensemble Methods make use of those kind of algorithms to improve their accuracy - that's why it looks like a good choice. We definitely need to have an eye on the model complexity to look for potential overfitting, but it seems to be a good way to test ensemble methods for our case. I would go for random forests and AdaBoost to get a sense of their performance and how their solutions differentiate.

Gaussian Naive Bayes


1) Gaussian Naive Bayes is used for problems like spam classification ('spam or ham' like in class) as well as face recognition, sentiment analysis for textual data and digit recognition. You can use it to make probabilistic predictions for a classification problem with different parameters (as seen above)

2) Strengths of a GNB classifier (Gaussian Naive Bayes classifier)

  • The great strengths of a GNB classifier would be the following:
    • easy to implement because there are no hyperparameters you have to optimize
    • builds great probabilistic features for the dataset and can easily figure out a probabilities even for combined features
    • doesn't require a big dataset for training
    • doesn't cost a lot computing power

3) Weaknesses of a GNB classifier

4) We will definitely try to use the GNB classifier for our dataset. At the moment, we are not really able to tell, how the variables are correlating and depending to each other but we can try the GNB classifier to get a feeling for it. Our dataset clearly is good for the classifier, because we have both, categorical and continuos data to put in our model.

Implementation - Creating a Training and Predicting Pipeline

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

def train_predict(learner, sample_size, X_train, y_train, X_test, y_test):
       - 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 =[: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)
    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[:300])

    # 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[:300], beta=0.5)

    # TODO: 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

Implementation: Initial Model Evaluation

The following steps were taken:

  • Importing the three supervised learning models you've discussed in the previous section.
  • Initializing the three models and store them in 'clf_A', 'clf_B', and 'clf_C'.
  • I calculated the number of records equal to 1%, 10%, and 100% of the training data.
    • Those values are stored in 'samples_1', 'samples_10', and 'samples_100' respectively.
In [40]:
# TODO: Import the three supervised learning models from sklearn
from sklearn.tree import DecisionTreeClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.ensemble import AdaBoostClassifier
from sklearn import svm

# TODO: Initialize the three models
clf_A = DecisionTreeClassifier(random_state=33)
clf_B = AdaBoostClassifier(random_state=33)
clf_C = GaussianNB()#no random_state parameter possible

# 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 (ensure to set the count of the values to be `int` and not `float`)
# HINT: samples_1 is 1% of samples_100 (ensure to set the count of the values to be `int` and not `float`)
samples_100 = len(y_train)
samples_10 = int(.1*len(y_train))
samples_1 = int(.01*len(y_train))

# 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)
except ValueError as e:
DecisionTreeClassifier trained on 361 samples.
DecisionTreeClassifier trained on 3617 samples.
DecisionTreeClassifier trained on 36177 samples.
/opt/conda/lib/python3.6/site-packages/sklearn/utils/ DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().
  y = column_or_1d(y, warn=True)
AdaBoostClassifier trained on 361 samples.
/opt/conda/lib/python3.6/site-packages/sklearn/utils/ DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().
  y = column_or_1d(y, warn=True)
AdaBoostClassifier trained on 3617 samples.
/opt/conda/lib/python3.6/site-packages/sklearn/utils/ DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().
  y = column_or_1d(y, warn=True)
AdaBoostClassifier trained on 36177 samples.
GaussianNB trained on 361 samples.
/opt/conda/lib/python3.6/site-packages/sklearn/utils/ DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().
  y = column_or_1d(y, warn=True)
GaussianNB trained on 3617 samples.
GaussianNB trained on 36177 samples.

The second row of the visuals is not displayed correctly. It is supposed to show "Model Testing", "Accuracy Score on Testing Set" and "F-Score on Testing Set".

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.

Choosing the Best Model

  • The F-Score for the testing set - when 100 % of the data is used - was the following for each model:

    • DecisionTreeClassifier: slightly above 0.6
    • AdaBoostClassifier: about 0.7
    • GaussianNBClassifier: about 0.4 => For this case, the higher the F_beta-score, the better the model performs for the testing data set => AdaBoost has the best score overall
  • Training and prediction time:

    • The time for training the data varies in between about 0.1 (Gaussian NB Cl.) and slighlty above 2.0 (AdaBoost Cl.)
    • The time for prediction making varies in between about 0.02 (DecisionTree Cl.) and slighlty above 0.4 (AdaBoost Cl.) => Overall, you can say, that this is quite good for each model. In one of my tries (not included in this notebook), I made a Support Vector Machine classifier to compare with AdaBoost, GaussianNB just for trying another alternative and got this result for training and prediction time:

    time.png (red = SVM, blue = AdaBoost, green = GaussianNB)

This is definitely some heavier discrepancy between the models, that way, the three I picked are good to go in this regard.

  • Algorithm's suitability for the data:
    • DecisionTreeClassifier: A usual Decision Tree does a good job on the data. Especially regarding accuracy on training and testing, it has a good fit on the data.
    • AdaBoostClassifier: You can clearly see the boosting algorithm outclassing the common Decision Tree Classifier. As mentioned above, it helps the prediction get slightly better for each training and testing. And you can still tweak the model a lot so I'm looking forward to see even better results.
    • GaussianNBClassifier: As mentioned above, the Gaussian NB classifier doesn't do a good job in making probabilistic predictions if the data correlates in a specific way. It seems that this dataset doesn't fit to this kind of classifier.

Describing the Model in Layman's Terms

Your final model will work the following: Imagine a big team of analysts working for you. They will work like a perfectly designed assembly line to be able to design the end product for you, in this case: the prediction. Each of them knows looks at the person and uses his or her experience to make a prediction. They all tell you if the person you look at earns above or under 50k. They collect their opinions and put it in a table and each opinion gets weighted by the analyst's experience.

This is all done by the computer who looks at the data in small steps to then put a weight to the data properly regarding experience of formely not correctly classified data.

Implementation: Model Tuning

Fine tune the chosen model. Using grid search (GridSearchCV) with at least one important parameter tuned with at least 3 different values, we will need to use the entire training set for this. In the code cell below, we will need to implement the following:

  • Import sklearn.grid_search.GridSearchCV and sklearn.metrics.make_scorer.
  • Initialize the classifier we'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 we wish to tune for the chosen model.
    • Example: parameters = {'parameter' : [list of values]}.
    • Note: Avoid tuning the max_features parameter of our 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.
In [ ]:
# TODO: Import 'GridSearchCV', 'make_scorer', and any other necessary libraries
from sklearn.grid_search import GridSearchCV
from sklearn.metrics import make_scorer
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import AdaBoostClassifier

# TODO: Initialize the classifier
clf = AdaBoostClassifier(random_state=33)

b_e_1 = DecisionTreeClassifier(max_depth=2, max_leaf_nodes = 7) # default estimator = DecisionTreeClassifier(max_depth=1)

# I did the following steps to get the best result:
# Trying out n_estimators with [50,55,60] and learning_rate with [0.8,0.9,1.0,1.1,1.2]
# Then I got the best n_estimators=55 and learning_rate=1.0
# Then I tried out different max_depths for the base estimators for AdaBoost:
    # DecisionTreeClassifier(max_depth=2) => this one made the best result
    # DecisionTreeClassifier(max_depth=3)

# In the next step, I tried to find out if other values for min_samples_split worked better
    # DecisionTreeClassifier(max_depth=2,min_samples_split=3)
# But the default value of 2 worked the best

# After that, I tried to tweak max_leaf_nodes as parameter
    # DecisionTreeClassifier(max_depth=2, max_leaf_nodes = 5)
    # DecisionTreeClassifier(max_depth=2, max_leaf_nodes = 6)
    # DecisionTreeClassifier(max_depth=2, max_leaf_nodes = 7) => best result

# So these parameters 

parameters = {'base_estimator':[b_e_1],'n_estimators':[50,55,60], 'learning_rate':[0.9,1.0,1.1]}

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

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

# TODO: Fit the grid search object to the training data and find the optimal parameters using fit()
grid_fit =, y_train.values.ravel()) #

# Get the estimator
best_clf = grid_fit.best_estimator_

# Make predictions using the unoptimized and model
predictions = (, 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: {:.4f}".format(accuracy_score(y_test, predictions)))
print("F-score on testing data: {:.4f}".format(fbeta_score(y_test, predictions, beta = 0.5)))
print("\nOptimized Model\n------")
print("Final accuracy score on the testing data: {:.4f}".format(accuracy_score(y_test, best_predictions)))
print("Final F-score on the testing data: {:.4f}".format(fbeta_score(y_test, best_predictions, beta = 0.5)))
print("Best estimator:")

Final Model Evaluation


Metric Unoptimized Model Optimized Model
Accuracy Score 0.8576 0.8704
F-score 0.7246 0.7488
  • The scores got better, but only about 1.3 % for accuracy and 2.4 % for the F-score, so the AdaBoost algorithm seems to make a good job without being tweaked.
  • Regarding the naive predictor, the model makes a huge win in accuracy and F-score (of course) but I bet that my model doesn't have a recall score of 1.0. But this was clear... ;-)

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.

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 we believe to be most important for prediction, and in what order would we rank them and why?


I would say, the following features are most important to predict the income:

  • age
  • capital-gain
  • education
  • occupation
  • hours-per-week

I would rank them in the following order:

  1. hours-per-week

    • Because usually, you would say that the more a person works, the more money they earn
  2. age

    • Experience is a big factor for income. That's why I would choose this features as one of the top ones
  3. education

    • This - in my experience - is an important factor for income as well. So it definitely belongs in the top 5 features.
  4. capital gain

    • income from investment sources other than salary/wages => most likely to be high for people with higher income
  5. occupation

    • there are some occupations where you most likely earn more than 50K (e.g. exec-managerial) and a few where you expect somebody not to get as much income out of (e.g. farming-fishing)

Implementation - Extracting Feature Importance

Choosing 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, we 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 [ ]:
# TODO: Import a supervised learning model that has 'feature_importances_'
from sklearn.ensemble import ExtraTreesClassifier

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

# TODO: Extract the feature importances using .feature_importances_ 
importances = model.feature_importances_

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

Extracting Feature Importance


  • I guessed very well. Though, I couldn't see how much the marital-status says about your income. Interesting...
  • The first three features were in my top 5 as well, and as you can see, the working experience seems to be THE top indicator for income. Though, this graph doesn't show us in WHICH DIRECTION these variables affect the predicition, we can guess, that the older a person is, the more income he or she has. And that seems to be the main indicator!
  • Actually, the marital status is a good indicator, but I'm still not sure how this would be an indicator for the predicition. I have two ideas, though:
    • Maybe people who are married are usually older which corresponds with the age feature (higher age <-> higher income)
    • Another reason could be that people who are never married can concentrate more on careers which help them get more income overall.

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

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?

I would not choose to make the final model based on the most important features. Training time was no factor for the AdaBoost algorithm I used for the whole dataset and even the fact, the figures for accuracy and F-score didn't go down that much - having an overall prediction accuracy of 84,84 % whereas the f-score with 70.14 % is not very much worse either - I would still use the model using all features.

In [ ]:
!!jupyter nbconvert *.ipynb