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: 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.
Your goal for this project is to identify students who might need early intervention before they fail to graduate. Which type of supervised learning problem is this, classification or regression? Why?
Answer: Given that we wish to place students into discrete categories (pass, fail), we would want to use a classification learning algorithm for this task. A regression algorithm, on the other hand, would be used for when we want to predict some value along a continuous scale, such as height, weight, score.
Run the code cell below to load necessary Python libraries and load the student data. Note that the last column from this dataset, 'passed'
, will be our target label (whether the student graduated or didn't graduate). All other columns are features about each student.
# Import libraries
import numpy as np
import pandas as pd
from time import time
from sklearn.metrics import f1_score
# display DataFrames as HTML tables
from IPython.display import display
# Read student data
student_data = pd.read_csv("student-data.csv")
print "Student data read successfully!"
Let's begin by investigating the dataset to determine how many students we have information on, and learn about the graduation rate among these students. In the code cell below, you will need to compute the following:
n_students
.n_features
.n_passed
.n_failed
.grad_rate
, in percent (%).# Number of students
n_students = student_data.shape[0]
# Number of features
n_features = (student_data.columns!= "passed").sum()
# Number of passing students
n_passed = (student_data["passed"] == "yes").sum()
# Number of failing students
n_failed = (student_data["passed"] == "no").sum()
# Graduation rate
grad_rate = 100 * (n_passed / float(n_students))
# Print the results
print "Total number of students: {}".format(n_students)
print "Number of features: {}".format(n_features)
print "Number of students who passed: {}".format(n_passed)
print "Number of students who failed: {}".format(n_failed)
print "Graduation rate of the class: {:.2f}%".format(grad_rate)
In this section, we will prepare the data for modeling, training and testing.
It is often the case that the data you obtain contains non-numeric features. This can be a problem, as most machine learning algorithms expect numeric data to perform computations with.
Run the code cell below to separate the student data into feature and target columns to see if any features are non-numeric.
# Extract feature columns
feature_cols = list(student_data.columns[:-1])
# Extract target column 'passed'
target_col = student_data.columns[-1]
# Show the list of columns
# print the feature and output label name
print "FEATURE COLUMNS:\n{}".format(", ".join(feature_cols))
print "\nTARGET LABEL:\n{}".format(target_col)
# Separate the data into feature data and target data (X_all and y_all, respectively)
X_all = student_data[feature_cols]
y_all = student_data[target_col]
# Display a sample of the first 5 rows of data.
# Displayed 8 columns at a time to fit nicely on the page
print "\nFEATURE VALUES:"
chunk_size = 8
for i in range(chunk_size, len(feature_cols)+chunk_size, chunk_size):
chunk_features = feature_cols[i-chunk_size: i]
display(X_all[chunk_features].head())
As you can see, there are several non-numeric columns that need to be converted! Many of them are simply yes
/no
, e.g. internet
. These can be reasonably converted into 1
/0
(binary) values.
Other columns, like Mjob
and Fjob
, have more than two values, and are known as categorical variables. The recommended way to handle such a column is to create as many columns as possible values (e.g. Fjob_teacher
, Fjob_other
, Fjob_services
, etc.), and assign a 1
to one of them and 0
to all others.
These generated columns are sometimes called dummy variables, and we will use the pandas.get_dummies()
function to perform this transformation. Run the code cell below to perform the preprocessing routine discussed in this section.
def preprocess_features(X):
''' Preprocesses the student data and converts non-numeric binary variables
into binary (0/1) variables. Converts categorical variables into dummy
variables. '''
# Initialize new output DataFrame
output = pd.DataFrame(index = X.index)
# Investigate each feature column for the data
for col, col_data in X.iteritems():
# If data type is non-numeric, replace all yes/no values with 1/0
if col_data.dtype == object:
col_data = col_data.replace(['yes', 'no'], [1, 0])
# If data type is categorical, convert to dummy variables
if col_data.dtype == object:
# Example: 'school' => 'school_GP' and 'school_MS'
col_data = pd.get_dummies(col_data, prefix = col)
# Collect the revised columns
output = output.join(col_data)
return output
X_all = preprocess_features(X_all)
print "Processed feature columns ({} total features):"\
"\n\n{}".format(len(X_all.columns), ", ".join(X_all.columns))
So far, we have converted all categorical features into numeric values. For the next step, we split the data (both features and corresponding labels) into training and test sets. In the following code cell below, you will need to implement the following:
X_all
, y_all
) into training and testing subsets.random_state
for the function(s) you use, if provided.X_train
, X_test
, y_train
, and y_test
.from sklearn.cross_validation import train_test_split
# Set the number of training points
num_train = 300
# Set the number of testing points
num_test = X_all.shape[0] - num_train
# Shuffle and split the dataset into the number of training/testing points above
X_train, X_test, y_train, y_test = \
train_test_split(X_all, y_all, test_size=num_test, random_state=354, stratify=y_all)
# 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])
# Checking proportion of each Class in train and test sets
print "proportions in entire data set"
print y_all.value_counts(sort=False, dropna=False, normalize=True)
print "proportions in training data"
print y_train.value_counts(sort=False, dropna=False, normalize=True)
print "proportions in test data"
print y_test.value_counts(sort=False, dropna=False, normalize=True)
We can see that the proportions are preserved in the splits
In this section, you will choose 3 supervised learning models that are appropriate for this problem and available in scikit-learn
. You will first discuss the reasoning behind choosing these three models by considering what you know about the data and each model's strengths and weaknesses. You will then fit the model to varying sizes of training data (100 data points, 200 data points, and 300 data points) and measure the F1 score. You will need to produce three tables (one for each model) that shows the training set size, training time, prediction time, F1 score on the training set, and F1 score on the testing set.
List three supervised learning models that are appropriate for this problem. What are the general applications of each model? What are their strengths and weaknesses? Given what you know about the data, why did you choose these models to be applied?
Answer: For this task we can look at a few different learning algorithms to explore which one will perform best. The three learning algorithms that will be considered are Naive Bayes
, Random Forrests
and Support Vector Machines
(SVMs
). These algorithms were chosen based on the fact that they can often give good results for classification tasks, and with the consideration that this is a relatively small dataset.
Naive Bayes
has the advantage that it is a very simple algorithm, so it should train very quickly, and should make very quick predictions too (Zang, 2004). However one of its weaknesses is that it makes a strong assumption that all the input features are completely independent of each other. While it is common for different variables to interact with each other, this algorithm can often still provide good results. In fact it is particularly well known for doing well on document classification tasks such as spam detection (Rennie et al. 2003)
Random Forrests
(Ho, 1995; Leo, 2001) can be though of as taking advantage of the "collective wisdom" of a bunch of other classifiers known as Decision Trees
. Each individual decision tree can create very complex and jagged decision boundaries which tend to overfit to the training data quite easily, especially for small datasets. This creates a high variance problem where the classifier appears to perfrom well on the training data, but perform much more poorly on new data. Random Forrests mitigate this problem by taking advantage of the property that decision trees will overfit in different ways. Decision trees will create quite different decision boundaries when trained on different subsets of the data. While any one of the decision trees might have regions which misclassify items, not all of them will misclassify in the same way, so when you pool their predictions together and take a majority vote, you will get a more prediction than any one of the individual decision trees. The disadvantage of random forrests is that you have to train multiple decision trees, so there may be a computational overhead involved in training these extra models. Random forrests can be useful for classification tasks where you may be uncertain what variables might be relevant, as they are robust against irelevant variables.
Support Vector Machines
(SVMs
) (Cortes and Vapnik, 1995) are quite capable of generating non-linear decision boundaries, and can achieve high accuracies. This algorithm can give good results even for small datasets, in fact they are only really useful for small to intermediate datasets since the training time scales quadratically with the number of training samples. As such SVMs become slow quite quickly as sample sizes increase. A further limitation is that prediction time scales not just as a function of the number of items being predicted upon, but also linearly with the number of samples used during the training phase. But with the small dataset we have got, SVMs should run within small enough time frames and the hope is that it will still produce good results. Support vector machines are useful for tasks that might have very complex decision boundaries, but with a small number of training samples.
Run the code cell below to initialize three helper functions which you can use for training and testing the three supervised learning models you've chosen above. The functions are as follows:
train_classifier
- takes as input a classifier and training data and fits the classifier to the data.predict_labels
- takes as input a fit classifier, features, and a target labeling and makes predictions using the F1 score.train_predict
- takes as input a classifier, and the training and testing data, and performs train_clasifier
and predict_labels
.def train_classifier(clf, X_train, y_train):
''' Fits a classifier to the training data. '''
# Start the clock, train the classifier, then stop the clock
start = time()
clf.fit(X_train, y_train)
end = time()
# Print the results
print "Trained model in {:.4f} seconds".format(end - start)
def predict_labels(clf, features, target):
''' Makes predictions using a fit classifier based on F1 score. '''
# Start the clock, make predictions, then stop the clock
start = time()
y_pred = clf.predict(features)
end = time()
# Print and return results
print "Made predictions in {:.4f} seconds.".format(end - start)
return f1_score(target.values, y_pred, pos_label='yes')
def train_predict(clf, X_train, y_train, X_test, y_test):
''' Train and predict using a classifer based on F1 score. '''
# Indicate the classifier and the training set size
print "Training a {} using a training set size of {}. . .".format(clf.__class__.__name__, len(X_train))
# Train the classifier
train_classifier(clf, X_train, y_train)
# Print the results of prediction for both training and testing
print "F1 score for training set: {:.4f}.".format(predict_labels(clf, X_train, y_train))
print "F1 score for test set: {:.4f}.".format(predict_labels(clf, X_test, y_test))
With the predefined functions above, you will now import the three supervised learning models of your choice and run the train_predict
function for each one. Remember that you will need to train and predict on each classifier for three different training set sizes: 100, 200, and 300. Hence, you should expect to have 9 different outputs below — 3 for each model using the varying training set sizes. In the following code cell, you will need to implement the following:
clf_A
, clf_B
, and clf_C
.random_state
for each model you use, if provided.X_train
and y_train
.# Import the three supervised learning models from sklearn
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
from sklearn.naive_bayes import MultinomialNB
# Random seed set for reproducibility of results
random_seed = 321
# Initialize the three models
clf_A = MultinomialNB()
clf_B = RandomForestClassifier(random_state=random_seed)
clf_C = SVC(kernel="rbf", random_state=random_seed)
# Execute the 'train_predict' function for each classifier and training set size
classifiers = [clf_A, clf_B, clf_C]
classifier_names = ["Naive Bayes using Multinomial Distribution",
"Random Forrest",
"Support Vector Machine",
]
sizes = [100, 200, 300]
for i, classifier in enumerate(classifiers):
print "===================================================================="
print classifier_names[i]
print "===================================================================="
for size in sizes:
print size
train_predict(classifier, X_train.head(size), y_train.head(size),
X_test, y_test)
print "\n"
Classifer 1 - Naive Bayes with Multinomial Distribution
Training Set Size | Training Time | Prediction Time (test) | F1 Score (train) | F1 Score (test) |
---|---|---|---|---|
100 | 0.0018 | 0.0003 | 0.8356 | 0.7826 |
200 | 0.0017 | 0.0003 | 0.7758 | 0.7536 |
300 | 0.0019 | 0.0003 | 0.7869 | 0.7556 |
Classifer 1 - Random Forrest
Training Set Size | Training Time | Prediction Time (test) | F1 Score (train) | F1 Score (test) |
---|---|---|---|---|
100 | 0.0287 | 0.0014 | 1.0 | 0.7059 |
200 | 0.0253 | 0.0013 | 0.9925 | 0.7353 |
300 | 0.0237 | 0.0013 | 0.9950 | 0.7231 |
Classifer 2 - Support Vector Machine
Training Set Size | Training Time | Prediction Time (test) | F1 Score (train) | F1 Score (test) |
---|---|---|---|---|
100 | 0.0017 | 0.0010 | 0.8846 | 0.8158 |
200 | 0.0048 | 0.0018 | 0.8491 | 0.8129 |
300 | 0.0097 | 0.0021 | 0.8667 | 0.8212 |
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 F1 score.
Based on the experiments you performed earlier, in one to two paragraphs, explain to the board of supervisors what single model you chose as the best model. Which model is generally the most appropriate based on the available data, limited resources, cost, and performance?
Answer:
Each of the algorithms considered were tested on a single core of a laptop capable of running at 2.20Ghz. Each algorithm was able to train on the data within a tiny fraction of a second. Predictions were all made within milliseconds (or a fraction of a millisecond) for close to 100 items being predicted in one go. The training phase only really needs to be run at most once or twice a year. Predictions would likely be run in batches, at most a few times a year. As such, none of these algorithms create much of a computational burden, even when you consider the accumulated usage. If computation is run locally, then energy costs are a factor. If computation is run on a cloud service such as Amazon EC2, then it is running time that is the cost factor (in hourly blocks). Shaving a tiny fraction of a second makes no significant difference to energy consumption, and no difference whatsoever for the cost of running it on a clowd service. As such, we can safely ignore training time and prediction time as a factor for deciding on one of these three algorithms, and concentrate exclusively on the F1 score.
Naive Bayes is unlikely to get much better performance than what it is already achieving in this untuned model. There is high variance in the untuned Random Forrest model, but it is unclear roughly where performance may end up once we reduce this variance, only that it will likely be somewhere between 0.7 and 1.0. It is possible that it might just require more data in order to reduce that variance. SVM on the other hand is giving us a clear indication that we can expect low variance, and F1 performance somewhere within the range 0.8 and 0.85. As such, it seems that the most reasonable algorithm to explore further is the SVM. However, one caveat will be made. Compute time may become an issue if this algorithm is going to continue to be used further on into the future as more and more data from students over the years is collected. It is therefore recomended to make use of a subset of the data, giving preference to the most recent data.
In one to two paragraphs, explain to the board of directors in layman's terms how the final model chosen is supposed to work. For example if you've chosen to use a decision tree or a support vector machine, how does the model go about making a prediction?
Answer: We have a several pieces of information for each student, we call these features. Now imagine for instance that all the students are arranged in a large field, and the exact position in which they stand is determined by the values of these features. What we want is to create a topography that allows us to reliably identify where the students that passed or failed are standing, by separating them in some way. Support Vector Machines do this through what is known as a kernel. This kernel can be thought of as a way of creating small hills in this field. These hills are placed strategically, such that there are peaks in regions where there are lots of students that passed, and valleys in regions where there are more people that failed. If we fill up the region with a bit of water, we can create a visible boundary that allows us to easily identify regions where students that likely passed or failed are. We can then use this topography to make predictions on new student. Since the position the student stands on is determined by information about the student we can get ahead of time, we can see where they would be standing on this landscape. If the student is on dry elevated land, then we classify that student as more likely to pass. If the student is standing with feet in water, then we classify being more likely to fail.
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:
sklearn.grid_search.gridSearchCV
and sklearn.metrics.make_scorer
.parameters = {'parameter' : [list of values]}
.clf
.make_scorer
and store it in f1_scorer
.pos_label
parameter to the correct value!clf
using f1_scorer
as the scoring method, and store it in grid_obj
.X_train
, y_train
), and store it in grid_obj
.from sklearn.grid_search import GridSearchCV
from sklearn.metrics import make_scorer
from sklearn.metrics import f1_score
# Create the parameters list you wish to tune
parameters = {
"C": [0.001, 0.005, 0.01, 0.05, 0.1, 0.3, 0.7, 1.0, 1.3, 1.7, 2.0],
"kernel": ["rbf", "poly", "sigmoid"],
"gamma":["auto", 0.0001, 0.001, 0.01, 0.03, 0.07, 0.1, 0.3, 0.7, 1.0],
"degree": [2, 3] # degree for the polynomial kernel
}
# Initialize the classifier (explicitly specifying the seed for reproducibility)
clf = SVC(kernel="rbf", random_state=3729)
# Make an f1 scoring function using 'make_scorer'
f1_scorer = make_scorer(f1_score, greater_is_better=True, pos_label='yes')
# Perform grid search on the classifier using the f1_scorer as the scoring method
grid_obj = GridSearchCV(clf, parameters, scoring=f1_scorer, cv=10)
# Fit the grid search object to the training data and find the optimal parameters
grid_obj = grid_obj.fit(X_train, y_train)
# Get the best classifier
clf = grid_obj.best_estimator_
# Report the final F1 score for training and testing after parameter tuning
print "Tuned model has a training F1 score of {:.4f}.".format(predict_labels(clf, X_train, y_train))
print "Tuned model has a testing F1 score of {:.4f}.".format(predict_labels(clf, X_test, y_test))
# Best Score during Cross Validation
print "\nBest Score During Cross Validation", grid_obj.best_score_
# The parameters that led to the best results
grid_obj.best_params_
What is the final model's F1 score for training and testing? How does that score compare to the untuned model?
Answer: The final model's F1 score for predictions made on the training data is 0.858, and 0.80 on the test set. This F1 value on the test set is smaller than what we got from the untuned model (0.821). However it does not mean that it is a worse model. Selecting the best tuned model was done using grid search with cross validation. The purpose of cross validation is to give a good idea about how well some model generalises to new unseen data. The final model was chosen on the basis that it is the one that is most likely to do well on new data. It didnt happen to perform as well on the specific test set that we set aside, but if we were to make predictions more predictions on other unseen data, we would have a greater likelihood of getting better results from the final tuned model than the first untuned model.