Machine Learning Engineer Nanodegree

Deep Learning

📑   P7: Building a Student Intervention System

1. Introduction

Question 1 - Classification vs. Regression

The 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 1

For simplicity, the border between regression and classification can be described in this way:

  • classification: predict the values of discrete or categorical targets;
  • regression: predict the values of continuous targets.

This supervised learning problem is in the classification field. We should predict the labels for the students: 'yes' or 'no' for the feature 'passed'.

2. Code Library

In [11]:
%%html
<style>
@import url('https://fonts.googleapis.com/css?family=Orbitron|Roboto');
body {background-color: #f6e4e4;} 
a {color: #a44a4a; font-family: 'Roboto';} 
h1 {color: #cd5c5c; font-family: 'Orbitron'; text-shadow: 4px 4px 4px #ccc;} 
h2, h3 {color: slategray; font-family: 'Orbitron'; text-shadow: 4px 4px 4px #ccc;}
h4 {color: #cd5c5c; font-family: 'Roboto';}
span {text-shadow: 4px 4px 4px #ccc;}
div.output_prompt, div.output_area pre {color: slategray;}
div.input_prompt, div.output_subarea {color: #a44a4a;}      
div.output_stderr pre {background-color: ghostwhite;}  
div.output_stderr {background-color: slategrey;}                        
</style>
<script>
code_show = true; 
function code_display() {
    if (code_show) {
        $('div.input').each(function(id) {
            if (id == 0 || $(this).html().indexOf('hide_code') > -1) {$(this).hide();}
        });
        $('div.output_prompt').css('opacity', 0);
    } else {
        $('div.input').each(function(id) {$(this).show();});
        $('div.output_prompt').css('opacity', 1);
    };
    code_show = !code_show;
} 
$(document).ready(code_display);
</script>
<form action="javascript: code_display()">
<input style="color: #cd5c5c; background: #f6e4e4; opacity: 0.8;" \ 
type="submit" value="Click to display or hide code cells">
</form>               
In [2]:
hide_code=''
# Import libraries
import numpy as np
import pandas as pd
from time import time
import warnings
from IPython.display import display 

# Display for notebooks
%matplotlib inline

#########################################
###     ADD EXTRA LIBRARIES HERE      ###
#########################################
from sklearn.metrics import f1_score, make_scorer
from sklearn.model_selection import ShuffleSplit, train_test_split
from sklearn.ensemble import AdaBoostClassifier 
from sklearn.ensemble import GradientBoostingClassifier 
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import GridSearchCV

3. Exploring the Data

We will start from loading 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.

In [3]:
hide_code
# Read student data
student_data = pd.read_csv("student-data.csv")
print ("Student data read successfully!")
student_data.describe().T
Student data read successfully!
Out[3]:
count mean std min 25% 50% 75% max
age 395.0 16.696203 1.276043 15.0 16.0 17.0 18.0 22.0
Medu 395.0 2.749367 1.094735 0.0 2.0 3.0 4.0 4.0
Fedu 395.0 2.521519 1.088201 0.0 2.0 2.0 3.0 4.0
traveltime 395.0 1.448101 0.697505 1.0 1.0 1.0 2.0 4.0
studytime 395.0 2.035443 0.839240 1.0 1.0 2.0 2.0 4.0
failures 395.0 0.334177 0.743651 0.0 0.0 0.0 0.0 3.0
famrel 395.0 3.944304 0.896659 1.0 4.0 4.0 5.0 5.0
freetime 395.0 3.235443 0.998862 1.0 3.0 3.0 4.0 5.0
goout 395.0 3.108861 1.113278 1.0 2.0 3.0 4.0 5.0
Dalc 395.0 1.481013 0.890741 1.0 1.0 1.0 2.0 5.0
Walc 395.0 2.291139 1.287897 1.0 1.0 2.0 3.0 5.0
health 395.0 3.554430 1.390303 1.0 3.0 4.0 5.0 5.0
absences 395.0 5.708861 8.003096 0.0 0.0 4.0 8.0 75.0

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. We will need to compute the following:

  • The total number of students, n_students.
  • The total number of features for each student, n_features.
  • The number of those students who passed, n_passed.
  • The number of those students who failed, n_failed.
  • The graduation rate of the class, grad_rate, in percent (%).
In [12]:
hide_code
# Calculate number of students
n_students = len(student_data)

# Calculate number of features
n_features = len(list(student_data.T.index))

# Calculate passing students
n_passed = len(student_data[student_data['passed'] == 'yes'])

# Calculate failing students
n_failed = len(student_data[student_data['passed'] == 'no'])

# Calculate graduation rate
grad_rate = n_passed * 100.0 / 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))
Total number of students: 395
Number of features: 31
Number of students who passed: 265
Number of students who failed: 130
Graduation rate of the class: 67.09%

4. Preparing the Data

In this section, we will prepare the data for modeling, training and testing.

4.1 Identify feature and target columns

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.

In [13]:
hide_code
# 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 ("Feature columns:\n{}".format(feature_cols))
print ("\nTarget column: {}".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]

# Show the feature information by printing the first five rows
print ("\nFeature values:")
print (X_all.head(7).T)
Feature columns:
['school', 'sex', 'age', 'address', 'famsize', 'Pstatus', 'Medu', 'Fedu', 'Mjob', 'Fjob', 'reason', 'guardian', 'traveltime', 'studytime', 'failures', 'schoolsup', 'famsup', 'paid', 'activities', 'nursery', 'higher', 'internet', 'romantic', 'famrel', 'freetime', 'goout', 'Dalc', 'Walc', 'health', 'absences']

Target column: passed

Feature values:
                  0        1        2         3       4           5       6
school           GP       GP       GP        GP      GP          GP      GP
sex               F        F        F         F       F           M       M
age              18       17       15        15      16          16      16
address           U        U        U         U       U           U       U
famsize         GT3      GT3      LE3       GT3     GT3         LE3     LE3
Pstatus           A        T        T         T       T           T       T
Medu              4        1        1         4       3           4       2
Fedu              4        1        1         2       3           3       2
Mjob        at_home  at_home  at_home    health   other    services   other
Fjob        teacher    other    other  services   other       other   other
reason       course   course    other      home    home  reputation    home
guardian     mother   father   mother    mother  father      mother  mother
traveltime        2        1        1         1       1           1       1
studytime         2        2        2         3       2           2       2
failures          0        0        3         0       0           0       0
schoolsup       yes       no      yes        no      no          no      no
famsup           no      yes       no       yes     yes         yes      no
paid             no       no      yes       yes     yes         yes      no
activities       no       no       no       yes      no         yes      no
nursery         yes       no      yes       yes     yes         yes     yes
higher          yes      yes      yes       yes     yes         yes     yes
internet         no      yes      yes       yes      no         yes     yes
romantic         no       no       no       yes      no          no      no
famrel            4        5        4         3       4           5       4
freetime          3        3        3         2       3           4       4
goout             4        3        2         2       2           2       4
Dalc              1        1        2         1       1           1       1
Walc              1        1        3         1       2           2       1
health            3        3        3         5       5           5       3
absences          6        4       10         2       4          10       0

4.2 Preprocess Feature Columns

As we 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.

In [14]:
hide_code
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{}".\
       format(len(X_all.columns), list(X_all.columns)))
Processed feature columns (48 total features):
['school_GP', 'school_MS', 'sex_F', 'sex_M', 'age', 'address_R', 'address_U', 'famsize_GT3', 'famsize_LE3', 'Pstatus_A', 'Pstatus_T', 'Medu', 'Fedu', 'Mjob_at_home', 'Mjob_health', 'Mjob_other', 'Mjob_services', 'Mjob_teacher', 'Fjob_at_home', 'Fjob_health', 'Fjob_other', 'Fjob_services', 'Fjob_teacher', 'reason_course', 'reason_home', 'reason_other', 'reason_reputation', 'guardian_father', 'guardian_mother', 'guardian_other', 'traveltime', 'studytime', 'failures', 'schoolsup', 'famsup', 'paid', 'activities', 'nursery', 'higher', 'internet', 'romantic', 'famrel', 'freetime', 'goout', 'Dalc', 'Walc', 'health', 'absences']

4.3 Training and Testing Data Split

So far, we have converted all categorical features into numeric values.

Next, we will randomly shuffle and split the data (X_all, y_all) into training and testing subsets by the following steps:

  • Use 300 training points (approximately 75%) and 95 testing points (approximately 25%).
  • Set a random_state for the function(s) we use, if provided.
  • Store the results in X_train, X_test, y_train, and y_test.
In [15]:
hide_code
# 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 and testing points above
X_train, X_test, y_train, y_test = train_test_split(X_all, y_all, \
test_size=1.0*num_test/len(X_all), random_state=1)

# 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 300 samples.
Testing set has 95 samples.

5. Training and Evaluating Models

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.

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

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

Question 2 - Model Application

List three supervised learning models that are appropriate for this problem. For each model chosen:

  • Describe one real-world application in industry where the model can be applied. (You may need to do a small bit of research for this — give references!)
  • What are the strengths of the model; when does it perform well?
  • What are the weaknesses of the model; when does it perform poorly?
  • What makes this model a good candidate for the problem, given what you know about the data?

Answer 2

I have chosen the following models:

  • GradientBoostingClassifier();
  • RandomForestClassifier();
  • AdaBoostClassifier().

Let's have a look at their applications and characteristics:

1) GradientBoostingClassifier.

2) RandomForestClassifier.

3) AdaBoostClassifier.

All these classifiers will produce enough good predictions in this case. We should produce the result with the variant of ranking and it's a well-known fact that classification tends to be a better paradigm for ranking than regression.

5.1 Setup

Let's initialize three helper functions which we can use for training and testing the three supervised learning models we'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.
    • This function will report the F1 score for both the training and testing data separately.
In [16]:
hide_code
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)))

5.2 Model Performance Metrics

With the predefined functions above, we will now import the three supervised learning models of our choice and run the train_predict function for each one. We will need to train and predict on each classifier for three different training set sizes: 100, 200, and 300. Hence, we should expect to have 9 different outputs below — 3 for each model using the varying training set sizes.

It's time to implement the following steps:

  • Import the three supervised learning models you've discussed in the previous section.
  • Initialize the three models and store them in clf_A, clf_B, and clf_C.
    • Use a random_state for each model we use, if provided.
    • Note: Use the default settings for each model — we will tune one specific model in a later section.
  • Create the different training set sizes to be used to train each model.
    • Do not reshuffle and resplit the data! The new training points should be drawn from X_train and y_train.
  • Fit each model with each training set size and make predictions on the test set (9 in total).
In [18]:
hide_code
# Import the three supervised learning models from sklearn

# Initialize the three models
clf_A = AdaBoostClassifier()
clf_B = GradientBoostingClassifier()
clf_C = RandomForestClassifier()

# Set up the training set sizes
X_train_100, y_train_100 = X_train[:100], y_train[:100]
X_train_200, y_train_200 = X_train[:200], y_train[:200]
X_train_300, y_train_300 = X_train, y_train

# Execute the 'train_predict' function for each classifier and each training set size
for clf in [clf_A, clf_B, clf_C]:
    for (X_train, y_train) in [(X_train_100, y_train_100), 
                               (X_train_200, y_train_200), 
                               (X_train_300, y_train_300)]:
        train_predict(clf, X_train, y_train, X_test, y_test)
Training a AdaBoostClassifier using a training set size of 100. . .
Trained model in 0.1898 seconds
Made predictions in 0.0136 seconds.
F1 score for training set: 0.9624.
Made predictions in 0.0149 seconds.
F1 score for test set: 0.6949.
Training a AdaBoostClassifier using a training set size of 200. . .
Trained model in 0.2855 seconds
Made predictions in 0.0534 seconds.
F1 score for training set: 0.8633.
Made predictions in 0.0125 seconds.
F1 score for test set: 0.7647.
Training a AdaBoostClassifier using a training set size of 300. . .
Trained model in 0.3138 seconds
Made predictions in 0.0206 seconds.
F1 score for training set: 0.8578.
Made predictions in 0.0170 seconds.
F1 score for test set: 0.8116.
Training a GradientBoostingClassifier using a training set size of 100. . .
Trained model in 0.2313 seconds
Made predictions in 0.0011 seconds.
F1 score for training set: 1.0000.
Made predictions in 0.0011 seconds.
F1 score for test set: 0.7538.
Training a GradientBoostingClassifier using a training set size of 200. . .
Trained model in 0.2811 seconds
Made predictions in 0.0014 seconds.
F1 score for training set: 1.0000.
Made predictions in 0.0014 seconds.
F1 score for test set: 0.7761.
Training a GradientBoostingClassifier using a training set size of 300. . .
Trained model in 0.3538 seconds
Made predictions in 0.0021 seconds.
F1 score for training set: 0.9706.
Made predictions in 0.0010 seconds.
F1 score for test set: 0.8088.
Training a RandomForestClassifier using a training set size of 100. . .
Trained model in 0.0496 seconds
Made predictions in 0.0035 seconds.
F1 score for training set: 0.9924.
Made predictions in 0.0028 seconds.
F1 score for test set: 0.6400.
Training a RandomForestClassifier using a training set size of 200. . .
Trained model in 0.0700 seconds
Made predictions in 0.0076 seconds.
F1 score for training set: 0.9848.
Made predictions in 0.0027 seconds.
F1 score for test set: 0.7299.
Training a RandomForestClassifier using a training set size of 300. . .
Trained model in 0.0513 seconds
Made predictions in 0.0033 seconds.
F1 score for training set: 0.9949.
Made predictions in 0.0070 seconds.
F1 score for test set: 0.7353.

5.3 Tabular Results


Classifer 1 - AdaBoostClassifier

Training Set Size Training Time Prediction Time (test) F1 Score (train) F1 Score (test)
100 0.1898 0.0149 0.9624 0.6949
200 0.2855 0.0125 0.8633 0.7647
300 0.3138 0.0170 0.8578 0.8116

Classifer 2 - GradientBoostingClassifier

Training Set Size Training Time Prediction Time (test) F1 Score (train) F1 Score (test)
100 0.2313 0.0011 1.0000 0.7538
200 0.2811 0.0014 1.0000 0.7761
300 0.3538 0.0010 0.9706 0.8088

Classifer 3 - RandomForestClassifier

Training Set Size Training Time Prediction Time (test) F1 Score (train) F1 Score (test)
100 0.0496 0.0027 0.9924 0.6400
200 0.0700 0.0033 0.9848 0.7299
300 0.0513 0.0070 0.9949 0.7353

6. Choosing the Best Model

In this final section, we will choose from the three supervised learning models the best model to use on the student data. We 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.

Question 3 - Choosing the Best Model

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 3

I have chosen the AdaBoostClassifier algorithm as it showed the highest accuracy and f-score for the testing set and escaped overfitting. The algorithm is proved to be very time-consuming in the training and predicting processes, but it can be ignored since the number of datapoints is quite small.

Question 4 - Model in Layman's Terms

In one to two paragraphs, explain to the board of directors in layman's terms how the final model chosen is supposed to work. Be sure that you are describing the major qualities of the model, such as how the model is trained and how the model makes a prediction. Avoid using advanced mathematical or technical jargon, such as describing equations or discussing the algorithm implementation.

Answer 4

In general, boosting in the machine learning is the construction a highly accurate prediction rule by combining many relatively weak and inaccurate rules. It based on the assumption: each of the weak hypotheses has accuracy a little bit better than a random guess. The AdaBoost algorithm unites weak classifiers in this way: the predictions from all of them are then combined through a weighted majority vote (or sum) to produce the final prediction. As many learning methods, AdaBoost uses minimizing a loss function that measures how well a model fits the observed data (more accurately - minimizing the exponential loss).

So what happens during an iteration process:

1) any underlying classifier can be chosen as a weak learner, 2) this classifier is trained on a random subset of the total training set, 3) the AdaBoost algorithm assigns (at the first step) or modifies (at the next steps) the weight to each training example, 4) the weights of training examples with incorrect predictions by the boosted model increases, whereas the weights are decreased for examples predicted correctly, so a weak learner is forced to concentrate on the "difficult" examples of wrong predictions, 5) each iteration should modify the underlying classifier to minimize the loss function.

References:

6.1 Model Tuning

Finaly, we will tune the chosen model and use 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.

Our steps in the tuning:

  • Import sklearn.grid_search.GridSearchCV and sklearn.metrics.make_scorer.
  • Create a dictionary of parameters you wish to tune for the chosen model.
    • Example: parameters = {'parameter' : [list of values]}.
  • Initialize the classifier you've chosen and store it in clf.
  • Create the F1 scoring function using make_scorer and store it in f1_scorer.
    • Set the pos_label parameter to the correct value!
  • Perform grid search on the classifier clf using f1_scorer as the scoring method, and store it in grid_obj.
  • Fit the grid search object to the training data (X_train, y_train), and store it in grid_obj.
In [19]:
hide_code
# Import 'GridSearchCV' and 'make_scorer'

# Create the parameters list you wish to tune
parameters = {'n_estimators': [48, 96, 192, 384], 
              'learning_rate':[0.1, 0.2, 0.3]}

# Initialize the classifier
clf = AdaBoostClassifier()

# Make an f1 scoring function using 'make_scorer' 
f1_scorer = make_scorer(f1_score, pos_label='yes')

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

# Fit the grid search object to the training data and find the optimal parameters
grid_fit = grid_obj.fit(X_train, y_train)

# Get the estimator
best_clf = grid_fit.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(best_clf, X_train, y_train)))
print ("Tuned model has a testing F1 score of {:.4f}.".\
       format(predict_labels(best_clf, X_test, y_test)))
print ("Tuned model has the parameters: \n{}".format(best_clf.get_params()))
Made predictions in 0.0137 seconds.
Tuned model has a training F1 score of 0.8268.
Made predictions in 0.0140 seconds.
Tuned model has a testing F1 score of 0.8725.
Tuned model has the parameters: 
{'algorithm': 'SAMME.R', 'base_estimator': None, 'learning_rate': 0.1, 'n_estimators': 48, 'random_state': None}

Question 5 - Final F1 Score

What is the final model's F1 score for training and testing? How does that score compare to the untuned model?

Answer 5

The final model's F-score was improved significantly for the test data.

It becomes 0.8268 instead of 0.8578 for the training set and 0.8725 instead of 0.8116 for the testing set.

It means we escape the overfitting problem. This result confirms the effectiveness of the algorithm GridSearchCV for tuning.

7. Conclusion

In this project, some classifiers and their application to predict categorical variables were discussed in detail. We studied the methods of data preparing and model optimizing as well. The final model has an F1 score of 0.8725 for the testing set, and it's an enough high result for such a small data set.