Machine Learning Engineer Nanodegree

Deep Learning

📑  P7: Building a Student Intervention System

Introduction

Resources

🕸scikit-learn. Machine Learning in Python  🕸Scipy Lecture Notes 

Code Library


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.

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.

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 (%).

Preparing the Data

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

Identify feature and target columns

It is often the case that the data you obtain contains non-numeric features. This can be a problem because most machine learning algorithms expect numeric data to perform computations with.

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.

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 the random_state parameter for the function(s) we use, if provided.
- Store the results in X_train, X_test, y_train, y_test.

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

Let's make quick checking F1 scores of the mentioned models:

I have chosen the following models: LogisticRegressionCV, svm.SVC, RadiusNeighborsClassifier.
In the experiments, they usually have a higher result than others.
Let's have a look at their applications and characteristics:
1) LogisticRegressionCV.
Applications:
- spam detection (to separate spam emails);
- credit card fraud (to detect fraud transactions);
- health diagnostics (to be sure about the right conclusions);
- banking (to predict finance defaults);
etc.
Example of Real World Business Applying
🕸Credit Risk Analysis Using Logistic Regression Modeling
Example of Courses about Linear Regression Models in Health Care
🕸Logistic Regression in R for Public Health
Strengths:
This model combines strong sides of logistic regression and cross-validation and fits data for a range of parameters instead of a single parameter value.
Estimation is done through maximum likelihood and suits very well for a binary classification case (the simple "yes/no" choice).
It’s easy interpretable and regularizable and can be used as a base for checking how more complex models work.
Weaknesses:
It requires independent (not correlated to each other) features and quite large sample sizes.
The algorithm does not work well when variables are not enough strongly correlated with a prediction target.
This model doesn't solve non-linear problems.
Adding more and more variables to the model can result in overfitting.
2) svm.SVC.
Applications:
- face detection;
- intrusion detection;
- complex classification of emails, news articles and web pages;
- classification of genes;
- handwriting recognition;
etc.
Example of Real World Medicine Applying
🕸Application of support vector machine modeling for prediction of common diseases: the case of diabetes and pre-diabetes
Examples of Real World Engineering Applying
🕸Support vector machines in engineering: an overview
Strengths:
It usually offers high accuracy and fast prediction compared to other simple classifiers.
This model uses less memory by subsetting of training points.
It works enough well with high dimensional space.
Weaknesses:
It has high training time and not suitable for big data.
This model sensitive for kernel choice.
It doesn't work with overlapping classes.
3) RadiusNeighborsClassifier.
Applications:
- recommender systems for clients;
- identification (persons, products or other objects).
Examples of Real World Bioinformatics Applying
🕸Protein secondary structure prediction using nearest-neighbor methods
Strengths:
It's one of the best choice for not uniformly sampled data.
This method is universal in the meaning of applying in supervised and unsupervised learning.
Weaknesses:
The algorithm becomes less effective for high-dimensional parameter spaces.
It simply collects the data examples and does not construct any internal functions, regularities or models for generalization.

All these classifiers will make 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.

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_classifier and predict_labels.
  - This function will report the F1 score for both the training and testing data separately.

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 the random_state parameter for each model we use, if provided.
  - Note: Use the default settings for each model β€” we will tune one specific model in the next 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).

Tabular Results




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 svm.SVC algorithm as it showed the highest f-scores for the testing set and escaped overfitting.
The algorithm is proved to be not so time-consuming in the training and predicting processes, the number of data points is quite small and we have the result very quickly.

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

The mechanism of SVM groups of algorithms can be explained very simply using geometric interpretation.
They create decision planes (or hyperplanes) which separate sets of objects having different class memberships.
A gap (margin) between the closest points in different classes is calculated like a distance and allows to check the effectiveness of the separation process.

SVM algorithms construct borders between classes using the kernel tricks which transform input data into high dimensional space,
i.e. data becomes separatable by adding more dimensions.
The choice of a suitable kernel allows to build a very accurate classifier.

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

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 means we escape the overfitting problem. This result confirms the effectiveness of the algorithm GridSearchCV for tuning.

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 enough high result for such a small data set.

Additional Code Cell