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?
For simplicity, the border between regression and classification can be described in this way:
This supervised learning problem is in the classification field. We should predict the labels for the students: 'yes' or 'no' for the feature 'passed'.
%%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>
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
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.
hide_code
# Read student data
student_data = pd.read_csv("student-data.csv")
print ("Student data read successfully!")
student_data.describe().T
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:
n_students
.n_features
.n_passed
.n_failed
.grad_rate
, in percent (%).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))
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.
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)
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.
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)))
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:
random_state
for the function(s) we use, if provided.X_train
, X_test
, y_train
, and y_test
.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]))
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:
List three supervised learning models that are appropriate for this problem. For each model chosen:
I have chosen the following models:
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.
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
.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)))
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:
clf_A
, clf_B
, and clf_C
.random_state
for each model we use, if provided.X_train
and y_train
.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)
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 |
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.
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?
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.
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.
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:
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:
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
.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()))
What is the final model's F1 score for training and testing? How does that score compare to the untuned model?
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.
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.