This lesson is being piloted (Beta version)

Introduction to Machine Learning using Python

Introduction to Machine Learning

Overview

Teaching: 10 min
Exercises: 0 min
Questions
  • What is Machine Learning

Objectives
  • Learng basic about Machine Learning

image

image

image

image

image

image

image

image

image

image

Key Points

  • Basic Machine Learning


Introduction to Scikit Learn

Overview

Teaching: 40 min
Exercises: 0 min
Questions
  • What is Scikit Learn

Objectives
  • Master Scikit Learn for Machine Learning

2.1 What is Scikit-Learn

image

  - data splitting
  - pre-processing
  - feature selection
  - model tuning using resampling
  - variable importance estimation
  as well as other functionality.
  

2.2 Install sklearn

We have installed kernel ML_SKLN which contains the scikit-learn package in Palmetto. However for new conda environment installation, here is the command: $ pip3 install -U scikit-learn

2.3 Pre-processing using sklearn

There are several steps that we will use sklearn for. For preprocessing raw data, we gonna use sklearn in these tasks:

2.3.1 Pre-processing with missing value

knnImpute can also be used to fill in missing value

from sklearn.impute import KNNImputer
imputer = KNNImputer(n_neighbors=2, weights="uniform")
data_knnimpute = pd.DataFrame(imputer.fit_transform(data_df))

Note:

2.3.2 Pre-processing with Transforming data

2.3.2.1 Using Standardization

image

2.3.2.2 Using scaling with predefine range

Transform features by scaling each feature to a given range. This estimator scales and translates each feature individually such that it is in the given range on the training set, e.g. between zero and one. Formulation for this is:

X_std = (X - X.min(axis=0)) / (X.max(axis=0) - X.min(axis=0))
X_scaled = X_std * (max - min) + min
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
#By default, it scales for (0, 1) range
data_scaler = pd.DataFrame(scaler.fit_transform(data3))

2.3.2.3 Using Box-Cox Transformation

import matplotlib.pyplot as plt
ax1 = plt.subplot(1,2,1)
ax1.hist(data3["Ozone"])
ax1.set_title("Original probability")
ax1.set_xlabel('Ozone')
ax1.set_ylabel('Count')
ax2 = plt.subplot(1,2,2)
ax2.hist(data_BxCx["Ozone"])
ax2.set_title("Box-Cox Transformation")
ax2.set_xlabel('Ozone')
ax2.set_ylabel('Count')
plt.show()

image

Key Points

  • sklearn


Data Partition with Scikit-Learn

Overview

Teaching: 20 min
Exercises: 0 min
Questions
  • What is Data Partition

Objectives
  • Learn how to split data using sklearn

Data partition: training and testing

image

Due to time constraint, we only focus on train_test_split, KFolds and StratifiedKFold

3.1 Scikit-Learn data

The sklearn.datasets package embeds some small toy datasets

For each dataset, there are 4 varibles:
- **data**: numpy array of predictors/X
- **target**: numpy array of predictant/target/y
- **feature_names**: names of all predictors in X
- **target_names**: names of all predictand in y

For example:

from sklearn.datasets import load_iris
data = load_iris()
print(data.data)
print(data.target)
print(data.feature_names)
print(data.target_names)

In this example we gonna use the renowned iris flower data

from sklearn.datasets import load_iris
iris = load_iris()
X = iris.data
y = iris.target

3.2 Data spliting using train_test_split: Single fold

Here we use train_test_split to randomly split 60% data for training and the rest for testing: image

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X,y,train_size=0.6,random_state=123)
#random_state: int, similar to R set_seed function

3.3 Data spliting using K-fold

image

from sklearn.model_selection import KFold
kf10 = KFold(n_splits=10,shuffle=True,random_state=20)
for train_index, test_index in kf10.split(iris.target):
    X_train = X[train_index]
    y_train = y[train_index]
    X_test = X[test_index]
    y_test = y[test_index]
    
    model.fit(X_train, y_train) #Training the model, not running now
    y_pred = model.predict(X_test)
    print(f"Accuracy for the fold no. {i} on the test set: {accuracy_score(y_test, y_pred)}")

3.4 Data spliting using Stratified K-fold

image

Here is the reuslt if using K-Fold:

image

Here is the result of using Stratified K-Fold:

image

from sklearn.model_selection import StratifiedKFold
kf = StratifiedKFold(n_splits=10, shuffle=True, random_state=123)
i = 1

for train_index, test_index in kf.split(iris.target):
    X_train = X[train_index]
    y_train = y[train_index]
    X_test = X[test_index]
    y_test = y[test_index]
    
    model.fit(X_train, y_train) #Training the model
    y_pred = model.predict(X_test)
    print(f"Accuracy for the fold no. {i} on the test set: {accuracy_score(y_test, y_pred)}")    

Key Points

  • sklearn, data partition


Evaluation Metrics with Scikit-Learn

Overview

Teaching: 20 min
Exercises: 0 min
Questions
  • How do we measure the accuracy of ML model

Objectives
  • Learn different metrics with sklearn

4 Evaluation Metrics

4.1 Regression model Evaluation Metrics

4.1.1 Correlation Coefficient (R) or Coefficient of Determination (R2):

image

from sklearn import metrics
metrics.r2_score(y_test,y_pred)

4.1.2 Root Mean Square Error (RMSE) or Mean Square Error (MSE)

image

from sklearn import metrics
metrics.mean_squared_error(y_test,y_pred,squared=False) # RMSE
metrics.mean_squared_error(y_test,y_pred,squared=True) # MSE

4.2. Classification model Evaluation Metrics

4.2.1 Confusion Matrix

For binary output (classification problem with only 2 output type, also most popular):

image

4.2.2 Accuracy

The most common metric for classification is accuracy, which is the fraction of samples predicted correctly as shown below:

image

from sklearn import metrics
metrics.accuracy_score(y_test,y_pred)

4.2.3 Precision

Precision is the fraction of predicted positives events that are actually positive as shown below:

image

4.2.4 Recall

Recall (also known as sensitivity) is the fraction of positives events that you predicted correctly as shown below:

image

4.2.5 F1 score

The f1 score is the harmonic mean of recall and precision, with a higher score as a better model. The f1 score is calculated using the following formula:

image

More information on Precision, Recall and F1 score can be found here

metrics.precision_recall_fscore_support(y_test,y_pred,average='binary')

4.2.6 AUC-ROC curve

image

image

ROC Interpretation

image

Code to calculate FPR, TPR:

from sklearn.metrics import roc_curve
fpr, tpr, thresholds = roc_curve(y_test,y_pred)

Code to calculate AUC score:

from sklearn.metrics import roc_auc_score
auc_score = roc_auc_score(y_test,y_pred)

We will go into detail how to plot AUC-ROC curve in the next chapter with a classification problem

Key Points

  • sklearn, metrics


Training Machine Learning model using Regression Method

Overview

Teaching: 20 min
Exercises: 0 min
Questions
  • How to train a Machine Learning model using Regression method

Objectives
  • Learn to use different Regression algorithm for Machine Learning training

5 Supervised Learning training with Regression

5.1 For continuous output

5.1.1 Train model using Linear Regression with 1 predictor

Let use the airquality data in previous episodes:

import pandas as pd
import numpy as np
from sklearn.impute import KNNImputer
from sklearn.model_selection import train_test_split
from sklearn import metrics

data_df = pd.DataFrame(pd.read_csv('https://raw.githubusercontent.com/vuminhtue/Machine-Learning-Python/master/data/r_airquality.csv'))

imputer = KNNImputer(n_neighbors=2, weights="uniform")
data_knnimpute = pd.DataFrame(imputer.fit_transform(data_df))
data_knnimpute.columns = data_df.columns

X_train, X_test, y_train, y_test = train_test_split(data_knnimpute['Temp'],
                                                    data_knnimpute['Ozone'],
                                                    train_size=0.6,random_state=123)

Fit a Linear model using method=lm

from sklearn.linear_model import LinearRegression
model_linreg = LinearRegression().fit(X_train[:,None],y_train)

Apply trained model to testing data set and evaluate output using R-squared:

y_pred = model_linreg.predict(X_test[:,None])
metrics.r2_score(y_test,y_pred) # R^2
metrics.mean_squared_error(y_test,y_pred,squared=False) #RMSE

5.1.2 Train model using Multi-Linear Regression (with 2 or more predictors)

From the above model, the R2=0.39:

The reason is that we only build the model with 1 input Temp. In this section, we will build the model with more input Solar Radiation, Wind, Temperature:

X_train, X_test, y_train, y_test = train_test_split(data_knnimpute[['Temp','Wind','Solar.R']],
                                                    data_knnimpute['Ozone'],
                                                    train_size=0.6,random_state=123)
model_linreg = LinearRegression().fit(X_train,y_train)
y_pred2 = model_linreg.predict(X_test)

metrics.r2_score(y_test,y_pred2)
metrics.mean_squared_error(y_test,y_pred2,squared=False)

Output is therefore better with smaller RMSE and higher Rsquared at 0.5

5.1.3 Train model using Polynomial Regression

From Multi-Linear Regression, the best R2=0.5 using 3 predictors. We can slightly improve this by using Polynomial Regression image

In this study, let use polynomial regression with degree of freedom=2

from sklearn.preprocessing import PolynomialFeatures
poly = PolynomialFeatures(degree=2)
X_train_poly = poly.fit_transform(data_knnimpute[['Temp','Wind','Solar.R']])
X_train, X_test, y_train, y_test = train_test_split(X_train_poly,
                                                    data_knnimpute['Ozone'],
                                                    train_size=0.6,random_state=123)
model_linreg_poly = LinearRegression().fit(X_train,y_train)
y_pred_poly = model_linreg_poly.predict(X_test)
print(metrics.r2_score(y_test,y_pred_poly))
print(metrics.mean_squared_error(y_test,y_pred_poly,squared=False))

The R2=0.58 shows improvement using polynomial regression!

5.2 For categorical output

5.2.1 Train model using Logistic Regression

image

image

In this example, we create a sample data set and use logistic regression to solve it. The example is taken from here

Load library and create sample data set:

from sklearn.datasets import make_classification

# generate sample data
X, y = make_classification(n_samples=1000, n_classes=2, random_state=1)

Partitioning Data to train/test:

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, random_state=2)

Train model using Logistic Regression

from sklearn.linear_model import LogisticRegression
model_LogReg = LogisticRegression().fit(X_train, y_train)
y_pred = model_LogReg.predict(X_test)

from sklearn.linear_model import LogisticRegression
model_LogReg = LogisticRegression().fit(X_train, y_train)
# predict output:
y_pred = model_LogReg.predict(X_test)
# predict probabilities
lr_probs = model_LogReg.predict_proba(X_test)

Evaluate output with accurary level:

from sklearn import metrics
metrics.accuracy_score(y_test,y_pred)

We retrieve the accuracy = 0.834

Now compute AUC-ROC and plot curve

from sklearn.metrics import roc_curve, roc_auc_score
import matplotlib.pyplot as plt
import numpy as np

# generate a no skill prediction (majority class)
ns_probs = np.zeros(len(y_test))

# calculate scores
ns_auc = roc_auc_score(y_test, ns_probs)
lr_auc = roc_auc_score(y_test, lr_probs[:,1])
# summarize scores
print('No Skill: ROC AUC=%.3f' % (ns_auc))
print('Logistic: ROC AUC=%.3f' % (lr_auc))
# calculate roc curves
ns_fpr, ns_tpr, _ = roc_curve(y_test, ns_probs)
lr_fpr, lr_tpr, _ = roc_curve(y_test, lr_probs[:,1])
# plot the roc curve for the model
plt.plot(ns_fpr, ns_tpr, linestyle='--', label='No Skill')
plt.plot(lr_fpr, lr_tpr, marker='.', label='Logistic')
# axis labels
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
# show the legend
plt.legend()
# show the plot
plt.show()

image

An alternative way to plot AUC-ROC curve, using additional toolbox “scikit-plot”

pip install scikit-plot

The shorter code for using this library:

import scikitplot as skplt
skplt.metrics.plot_roc(y_test, lr_probs)
plt.show()

image

Key Points

  • Regression training


Training Machine Learning model using Tree-based model

Overview

Teaching: 20 min
Exercises: 0 min
Questions
  • How to train a Machine Learning model using Tree-based model

Objectives
  • Learn to use different Tree-based algorithm for Machine Learning training

Supervised Learning training

Train model using Decision Tree

Spliting algorithm

More information on how to apply the spliting algorithm to split the data can be found here

Pros & Cons

image

Implementation

Here we will use iris data

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split

iris = load_iris()
X = iris.data
y = iris.target
X_train, X_test, y_train, y_test = train_test_split(X,y,train_size=0.6,random_state=123)

Next we will train using DecisionTree with gini splitting algorithm:

from sklearn.tree import DecisionTreeClassifier
model_DT = DecisionTreeClassifier(max_depth=3,criterion="gini").fit(X_train,y_train)

Once done, we can visualize the tree:

from sklearn import tree
tree.plot_tree(model_DT)

However, in order to have a nicer plot:

import graphviz
dot_data = tree.export_graphviz(model_DT, out_file=None,                      
                      filled=True, rounded=True,
                      feature_names=iris.feature_names,
                      special_characters=True)  
graph = graphviz.Source(dot_data) 
graph

image

Apply decision tree model to predic output of testing data

from sklearn import metrics
y_pred_DT = model_DT.predict(X_test)
metrics.accuracy_score(y_test,y_pred_DT)

The accuracy=0.95

More information on Decision Tree can be found here

Train model using Random Forest

image

image

Pros & Cons of Random Forest

image

Implementation of Random Forest

from sklearn.ensemble import RandomForestClassifier
model_RF = RandomForestClassifier(n_estimators=20,criterion="gini").fit(X_train,y_train)
y_pred_RF = model_RF.predict(X_test)
metrics.accuracy_score(y_test,y_pred_RF)

The accuracy=0.97

In this example, we use n_estimators=20 to grow n number of trees in the forest. We can see that Random Forest result has better prediction than Decision Tree.

More information on Random Forest can be found here

Key Points

  • Decision Tree, Random Forest


Training Machine Learning model using Ensemble approach

Overview

Teaching: 20 min
Exercises: 0 min
Questions
  • How to overcome limitation of single ML model?

Objectives
  • Learn to use different Ensemble ML algorithm for Machine Learning training

7.1 Why Ensemble:

Ensemble is a method in Machine Learning that combine decision from several ML models to obtain optimum output. This espisode get information from here

image Source: Patheos.com

Ensemble approaches can reduce variance & Avoid Overfitting by combining results of multiple classifiers on different sub-samples

image

Figure. Bias & Variance Tradeoff

7.2 Train model using Ensemble Approach

Ensemble methods use multiple learning algorithms to obtain better predictive performance than could be obtained from any of the constituent learning algorithms alone. Unlike a statistical ensemble in statistical mechanics, which is usually infinite, a machine learning ensemble consists of only a concrete finite set of alternative models, but typically allows for much more flexible structure to exist among those alternatives. Here we will be learning several ensemble models:

image

7.3 Train model using Bagging (Bootstrap Aggregation)

7.3.1 Detail explaination of Bagging

There are 3 steps in Bagging

image

Step 1: Here you replace the original data with new sub-sample data using bootstrapping.

Step 2: Train each sub-sample data using ML algorithm

Step 3: Lastly, you use an average value to combine the predictions of all the classifiers, depending on the problem. Generally, these combined values are more robust than a single model.

7.3.2 Implementation of Bagging

Here we use iris data set:

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split

iris = load_iris()
X = iris.data
y = iris.target
X_train, X_test, y_train, y_test = train_test_split(X,y,train_size=0.6, random_state = 123)

First apply Bagging with DecisionTree model, Bagging’s parameter can be found here:

from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import BaggingClassifier
model_DT = DecisionTreeClassifier()

model_bag_DT = BaggingClassifier(base_estimator=model_DT, n_estimators=100,
                            bootstrap=True, n_jobs=-1,
                            random_state=123)
model_bag_DT.fit(X_train, y_train)

model_bag_DT.score(X_train,y_train),model_bag_DT.score(X_test,y_test)

The output accuracy from Bagging with DecisionTree for train/testing have : (1.0, 0.9666666666666667)

7.4 Train model using Boosting

http://uc-r.github.io/public/images/analytics/gbm/boosted_stumps.gif

image

More information on Boosting can be found here

7.4.1 Adaptive Boosting: Adaboost

Implementation of Adaboost

from sklearn.ensemble import AdaBoostClassifier
model_AD = AdaBoostClassifier(n_estimators=100, learning_rate=0.03).fit(X_train, y_train)

model_AD.score(X_train,y_train),model_AD.score(X_test,y_test)

The output accuracy from AdaBoost for train/testing have : (0.9333333333333333, 0.8333333333333334)

7.4.2 Gradient Boosting Machines:

from sklearn.ensemble import GradientBoostingClassifier
model_GBM = GradientBoostingClassifier(n_estimators=100).fit(X_train,y_train)

model_GBM.score(X_train,y_train),model_GBM.score(X_test,y_test)

The output accuracy from GradientBoosting for train/testing have : (1.0, 0.9333333333333333)

7.5 Compare Bagging and Boosting technique:

image

7.6 Conclusions

Key Points

  • Bagging, Boosting


Training Machine Learning model using Model based Prediction

Overview

Teaching: 20 min
Exercises: 0 min
Questions
  • What is model based prediction algorithm in ML?

Objectives
  • Learn to use different Model based prediction for Machine Learning training

8.1 Naive Bayes

image image

image

8.1.1 Implementation Naive Bayes

Split data

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split

iris = load_iris()
X = iris.data
y = iris.target
X_train, X_test, y_train, y_test = train_test_split(X,y,train_size=0.6, random_state = 123)

Train data using Naive Bayes

from sklearn.naive_bayes import GaussianNB
model_NB = GaussianNB().fit(X_train,y_train)
model_NB.score(X_train,y_train)
model_NB.score(X_test,y_test)

In addition to GaussianNB, sklearn also includes: MultinomialNB, ComplementNB, BernoulliNB, CategoricalNB. More information on Naive Bayes using sklearn can be found here

8.2 Linear Discriminent Analysis

image

8.2.1 Implementation LDA

Using the same iris data set, the LDA model is built:

from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
model_LDA = LinearDiscriminantAnalysis().fit(X_train,y_train)
model_LDA.score(X_train,y_train)
model_LDA.score(X_test,y_test)

8.2.2 Ensemble approach (Bagging) with LDA

from sklearn.ensemble import BaggingClassifier
model_LDAbag = BaggingClassifier(base_estimator = model_LDA,n_estimators=100,
                                 bootstrap=True, n_jobs=-1,
                                 random_state=123)
model_LDAbag.fit(X_train,y_train)
model_LDAbag.score(X_train,y_train)
model_LDAbag.score(X_test,y_test)

Key Points

  • Naive Bayes, Linear Discriminent Analyst


Regularization and Variable Selection

Overview

Teaching: 20 min
Exercises: 0 min
Questions
  • Why do we need Regularization and Variable Selection in ML model

Objectives
  • Learn how to apply Regularization and Variable selection in ML model

image

9 Regularization

=> in which: β represents the coefficient estimates for different variables or predictors(x)

The residual sum of squares RSS is the loss function of the fitting procedure. And we need to determine the optimal coefficients 𝛽 to minimize the loss function

image

This procedure will adjust the β based on the training data. If there is any noise in training data, the model will not perform well for testing data. Thus, Regularization comes in and regularizes/shrinkage these 𝛽 towards zero.

There are 3 main types of Regularization.

9.1 Ridge Regression

image

𝜆: Regularization Penalty, to be selected that the model minimized the error

The Ridge Regression loss function contains 2 elements: (1) RSS is actually the Ordinary Least Square (OLS) function for MLR and (2) The regularization term with 𝜆:

image

9.1.1 Implementation

Setting up training/testing model using the Stanford’s prostate cancer data

import pandas as pd
import numpy as np
data=pd.read_csv("https://raw.githubusercontent.com/vuminhtue/Machine-Learning-Python/master/data/prostate_data.csv")
ind_train = data["train"]=="T"
data = data.drop(["train"],axis=1)
X_train = data.drop(["lpsa"],axis=1)[ind_train]
X_test = data.drop(["lpsa"],axis=1)[~ind_train]
y_train = data["lpsa"][ind_train]
y_test = data["lpsa"][~ind_train]

Predict using Ridge Regression method and Cross Validation approach:

from sklearn.linear_model import RidgeCV
from sklearn.metrics import mean_squared_error as mse

n_lambda = 100
lambdas = np.logspace(-2,6, n_lambda)

MSE_train = []
MSE_test = []
coefs = []

for ld in lambdas:
    ridgecv = RidgeCV(alphas = [ld], normalize = True)
    model_RR = ridgecv.fit(X_train, y_train)
    y_predRR_cv_train = model_RR.predict(X_train)
    y_predRR_cv_test  = model_RR.predict(X_test)    
    MSE_train.append(mse(y_train,y_predRR_cv_train))
    MSE_test.append(mse(y_test,y_predRR_cv_test))    
    coefs.append(model_RR.coef_)

coef_df = pd.DataFrame(coefs)
coef_df.columns = X_train.columns

Plotting the Mean Square Error for Training and Testing dataset based on 𝜆 variation

import matplotlib.pyplot as plt

fig, ax = plt.subplots(1, 2, figsize=(16, 8), constrained_layout=False)

ax1 = plt.subplot(221)
ax1.scatter(np.log10(lambdas), MSE_train,color="red")
ax1.set_title("Training Set")
ax2 = plt.subplot(222)
ax2.scatter(np.log10(lambdas), MSE_test,color="red")
ax2.set_title("Testing Set")

ax1.set_xlabel("log($\\lambda$)")
ax2.set_xlabel("log($\\lambda$)")
ax1.set_ylabel('MSE')
ax2.set_ylabel('MSE')

plt.show()

image

Plotting the coefficient of different predictors based on 𝜆


ax = plt.gca()
for i in range(0,coef_df.columns.size):
    ax.plot(np.log10(lambdas), coef_df.iloc[:,i])
    
ax.legend(coef_df.columns)
#ax.set_xscale('log')
plt.xlabel("log($\\lambda$)")
plt.ylabel('Coefficients')
plt.title('Ridge Regression Coefficients')
plt.axis('tight')
plt.show()

image

The plot shows different coefficients for all predictors with 𝜆 variation.

9.2 LASSO: Least Absolute Shrinkage & Selection Operator

image

9.2.1 Implementation

Predict using Lasso method:

from sklearn.linear_model import Lasso

n_lambda = 100
lambdas1 = np.logspace(-6,0, n_lambda)

MSE_train = []
MSE_test = []
coefs = []
for ld in lambdas1:
    lassocv = Lasso(alpha=ld)
    model_LS = lassocv.fit(X_train, y_train)
    y_predLS_cv_train = model_LS.predict(X_train)
    y_predLS_cv_test = model_LS.predict(X_test)
    MSE_train.append(mse(y_train,y_predLS_cv_train))
    MSE_test.append(mse(y_test,y_predLS_cv_test))
    coefs.append(model_LS.coef_)    

Plotting the Mean Square Error for Training and Testing dataset based on 𝜆 variation

fig, ax = plt.subplots(1, 2, figsize=(16, 8), constrained_layout=False)


ax1 = plt.subplot(221)
ax1.scatter(np.log10(lambdas1), MSE_train,color="red")
ax1.set_title("Training Set")
ax2 = plt.subplot(222)
ax2.scatter(np.log10(lambdas1), MSE_test,color="red")
ax2.set_title("Testing Set")

ax1.set_xlabel("log($\\lambda$)")
ax2.set_xlabel("log($\\lambda$)")
ax1.set_ylabel('MSE')
ax2.set_ylabel('MSE')

plt.show()

image

Plotting the coefficient of different predictors based on 𝜆

coef_df = pd.DataFrame(coefs)
coef_df.columns = X_train.columns

ax = plt.gca()
for i in range(0,coef_df.columns.size):
    ax.plot(np.log10(lambdas1), coef_df.iloc[:,i])
    
ax.legend(coef_df.columns,bbox_to_anchor = (1.05, 0.6))
#ax.set_xscale('log')
plt.xlabel("log($\\lambda$)")
plt.ylabel('Coefficients')
plt.title('LASSO Coefficients')
plt.axis('tight')
plt.show()

image

The plot shows different coefficients for all predictors with 𝜆 variation. Depending on 𝜆 values that the β varying and it can be 0 at certain point.

9.3 Elastic Nets

Elastic Nets Regularization is a method that includes both LASSO and Ridge Regression. Its formulation for the loss function is as following: image

9.3.1 Implementation

from sklearn.linear_model import ElasticNet

MSE_train = []
MSE_test = []
coefs = []
for ld in lambdas1:
    Elastic_cv = ElasticNet(alpha=ld,l1_ratio=0.5)
    model_EN = Elastic_cv.fit(X_train, y_train)
    y_predEN_cv_train = model_EN.predict(X_train)
    y_predEN_cv_test = model_EN.predict(X_test)
    MSE_train.append(mse(y_train,y_predEN_cv_train))
    MSE_test.append(mse(y_test,y_predEN_cv_test))
    coefs.append(model_EN.coef_)

Key Points

  • Regularization, Ridge Regression, LASSO, Elastic Nets


Dimension Reduction

Overview

Teaching: 20 min
Exercises: 0 min
Questions
  • What happen when there are lots of covariates?

Objectives
  • Learn how to apply PCA in ML model

10 Principal Component Analysis

10.1 PCA formulation

in which, the covariance value between 2 data sets can be computed as: image

- Given mxm matrix, we can find m eigenvectors and m eigenvalues
- Eigenvectors can only be found for square matrix.
- Not every square matrix has eigenvectors
- A square matrix A and its transpose have the same eigenvalues but different eigenvectors
- The eigenvalues of a diagonal or triangular matrix are its diagonal elements.
- Eigenvectors of a matrix A with distinct eigenvalues are linearly independent.

Eigenvector with the largest eigenvalue forms the first principal component of the data set … and so on …*

10.2 Implementation

Here we gonna use iris data set:

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

import numpy as np
import pandas as pd
iris = load_iris()
X = iris.data
y = pd.DataFrame(iris.target)
y['Species']=pd.Categorical.from_codes(iris.target, iris.target_names)
X_train, X_test, y_train, y_test = train_test_split(X,y,train_size=0.6,random_state=123)

X_train_scaled = StandardScaler().fit_transform(X_train)
X_test_scaled = StandardScaler().fit_transform(X_test)

10.2.1 Compute PCA using sklearn:

from sklearn.decomposition import PCA
pca = PCA(n_components=4)
PCs = pca.fit_transform(X_train_scaled)
PCs = pd.DataFrame(PCs,columns = ['PC1','PC2','PC3','PC4'])

We can see that PCs computed from sklearn package are similar to newpca computed from using eigen vectors

10.2.2 Explained Variance

The explained variance tells you how much information (variance) can be attributed to each of the principal components.

pca.explained_variance_ratio_

In this example: the PC1(0.74) and PC2 (0.21) consume 0.95 percent of explained variance. Therefore, using 2 Principal Components should be good enough

10.2.3 Application of PCA model in Machine Learning:

from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score as acc_score

pca = PCA(n_components=2) #We choose number of principal components to be 2

X_train_pca = pca.fit_transform(X_train_scaled)
X_test_pca = pd.DataFrame(pca.transform(X_test_scaled))
X_test_pca.columns=['PC1','PC2']

print(pca.explained_variance_ratio_)

# Use random forest to train model
model_RF = RandomForestClassifier(n_estimators=20,criterion="gini",random_state=1234).fit(X_train_pca, y_train['Species'])
y_pred_RF = model_RF.predict(X_test_pca)
acc_score(y_test['Species'],y_pred_RF)

Plotting the testing result with indicator of Wrong prediction

import matplotlib.pyplot as plt

ax = plt.gca()

targets = np.unique(y_pred_RF)
colors = ['r', 'g', 'b']

for target, color in zip(targets,colors):
    indp = y_pred_RF == target
    ax.scatter(X_test_pca.loc[indp, 'PC1'], X_test_pca.loc[indp, 'PC2'],c = color)

# Ploting the Wrong Prediction
ind = y_pred_RF!=np.array(y_test['Species'])
ax.scatter(X_test_pca.loc[ind, 'PC1'],X_test_pca.loc[ind, 'PC2'],c = 'black')

#axis control
ax.legend(['setosa','versicolor','virginica','Wrong Prediction'])  
ax.set_title("Testing set from Random Forest using PCA 2 components")
ax.set_xlabel('PC1')
ax.set_ylabel('PC2')

plt.show()

image

Key Points

  • PCA


Neural Network

Overview

Teaching: 20 min
Exercises: 0 min
Questions
  • How to use Neural Network in Machine Learning model

Objectives
  • Learn how to use ANN in ML model

11. Neural Network

image image

image

Here, x1,x2....xn are input variables. w1,w2....wn are weights of respective inputs.
b is the bias, which is summed with the weighted inputs to form the net inputs. 
Bias and weights are both adjustable parameters of the neuron.
Parameters are adjusted using some learning rules. 
The output of a neuron can range from -inf to +inf.
The neuron doesn’t know the boundary. So we need a mapping mechanism between the input and output of the neuron. 
This mechanism of mapping inputs to output is known as Activation Function.
import matplotlib.pyplot as plt
import numpy as np

xrange = np.linspace(-2, 2, 200)

plt.figure(figsize=(7,6))

plt.plot(xrange, np.maximum(xrange, 0), label = 'ReLU')
plt.plot(xrange, np.tanh(xrange), label = 'Hyperbolic Tangent')
plt.plot(xrange, 1 / (1 + np.exp(-xrange)), label = 'Sigmoid/Logistic')
plt.plot(xrange, xrange, label = 'Linear')
plt.plot(xrange, np.heaviside(xrange, 0.5), label = 'Step')
plt.legend()
plt.title('Neural network activation functions')
plt.xlabel('Input value (x)')
plt.ylabel('Activation function output')

plt.show()

image

Between the input and the output layer, there can be one or more non-linear layers, called hidden layers. Figure below shows a one hidden layer MLP with scalar output.

image

image

The advantages of Multi-layer Perceptron:

The disadvantages of Multi-layer Perceptron:

11.1. Type of Neural Network Multi-Layer Perceptron in sklearn

There are 2 main types of MLP in sklearn, depending on the model output:

11.2. Implementation with Classification problem

Here we use iris data for Classification problem

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler

import numpy as np
import pandas as pd
iris = load_iris()
X = iris.data
y = pd.DataFrame(iris.target)
y['Species']=pd.Categorical.from_codes(iris.target, iris.target_names)
X_train, X_test, y_train, y_test = train_test_split(X,y,train_size=0.6,random_state=123)

scaler = MinMaxScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

The Class MLPClassifier implements a multi-layer perceptron (MLP) algorithm that trains using Backpropagation. There are lots of parameters in MLPClassifier:

More information can be found here

from sklearn.neural_network import MLPClassifier
model_NN = MLPClassifier(hidden_layer_sizes = (50,20),solver='lbfgs',activation='relu',random_state=123).fit(X_train_scaled, y_train['Species'])
model_NN.score(X_test_scaled,y_test['Species'])

11.3. Implementation with Regression problem

Here we use airquality data from Regression espisode:

import pandas as pd
import numpy as np
from sklearn.impute import KNNImputer
from sklearn.model_selection import train_test_split

data_df = pd.DataFrame(pd.read_csv('https://raw.githubusercontent.com/vuminhtue/Machine-Learning-Python/master/data/r_airquality.csv'))

imputer = KNNImputer(n_neighbors=2, weights="uniform")
data_knnimpute = pd.DataFrame(imputer.fit_transform(data_df))
data_knnimpute.columns = data_df.columns

X_train, X_test, y_train, y_test = train_test_split(data_knnimpute[['Temp','Wind','Solar.R']],
                                                    data_knnimpute['Ozone'],
                                                    train_size=0.6,random_state=123)

Fit MLPRegressor model

from sklearn.neural_network import MLPRegressor
model_NN = MLPRegressor(hidden_layer_sizes = (50,20),solver='lbfgs',activation='relu',max_iter=1000).fit(X_train,y_train)
model_NN.score(X_test,y_test)

11.4. Tips on using MLP

Key Points

  • ANN


Support Vector Machine

Overview

Teaching: 20 min
Exercises: 0 min
Questions
  • How to use Support Vector Machine in Machine Learning model

Objectives
  • Learn how to use SVM in ML model

12. Support Vector Machine

12.1. Applications of Support Vector Machine:

image

12.2. Explanation

image

image

image

image

12.3. SVM’s kernel

12.3.1. For linear separable data, it is quite straight forward to create a hyperplane to distinguish them

image

12.3.2. For linearly non-separable data, SVM makes use of kernel tricks to make it linearly separable.

image

The following kernel trick compared different kernel ‘linear’ , ’poly’ , ‘rbf’ , ‘sigmoid’:

image

12.4. Implementation

Here we use the regular iris dataset with Classification problem

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler

import numpy as np
import pandas as pd
iris = load_iris()
X = iris.data
X = X[:,2:4]
y = iris.target

X_train, X_test, y_train, y_test = train_test_split(X,y,train_size=0.6,random_state=123)

Fit Support Vector Classifier model

from sklearn.svm import SVC
from mlxtend.plotting import plot_decision_regions
import matplotlib.pyplot as plt
names = ["Linear SVM", "RBF SVM", "Poly SVM", "Sigmoid SVM"]
classifiers = [
    SVC(kernel="linear"),
    SVC(kernel="rbf"),
    SVC(kernel="poly"),
    SVC(kernel="sigmoid")]

i = 1
figure = plt.figure(figsize=(27, 5))
cm = plt.cm.jet

for name, clf in zip(names, classifiers):
    ax = plt.subplot(1,4, i)
    clf.fit(X_train, y_train)
    ax = plot_decision_regions(X=X_train, 
                      y=y_train,
                      clf=clf)
    ax.set_xlabel(iris.feature_names[2], size=14)
    ax.set_ylabel(iris.feature_names[3], size=14)
    ax.set_title(name, size=20)
    handles, labels = ax.get_legend_handles_labels()
    ax.legend(handles,iris.target_names)
    i+=1
plt.show()

image

In this model, C is the regularization parameter Default C=1. The strength of the regularization is inversely proportional to C. Must be strictly positive.

12.5. Tips on using SVM

12.6. Pros of SVM

12.7. Cons of SVM

Key Points

  • SVM


K-Nearest Neighbour

Overview

Teaching: 20 min
Exercises: 0 min
Questions
  • How to use K-Nearest Neighbour in Machine Learning model

Objectives
  • Learn how to use KNN in ML model

13. K-Nearest Neighbour

image

13.1. Explanation

image

image

13.2. Implementation

Here we gonna use the iris dataset again:

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split

import numpy as np
import pandas as pd
iris = load_iris()
X = iris.data
y = iris.target

X_train, X_test, y_train, y_test = train_test_split(X,y,train_size=0.6,random_state=123)

Train the model using KNN model with 3 nearest neighbors

from sklearn.neighbors import KNeighborsClassifier
model_KNN = KNeighborsClassifier(n_neighbors=3).fit(X_train,y_train)

model_KNN.score(X_train,y_train)
model_KNN.score(X_test,y_test)

image

13.3. Other similar models from sklearn.neighbors:

Key Points

  • KNN


Unsupervised Learning

Overview

Teaching: 20 min
Exercises: 0 min
Questions
  • What is Unsupervised Learning in Machine Learning model

Objectives
  • Learn how to use K-mean clustering in ML model

14. Unsupervised Learning

image image

image

image

image

image

image

image

14.1.2. Example with K=3

image

image

14.1.3. Implementation

Here we use the iris data set with only predictors

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split

import numpy as np
import pandas as pd
iris = load_iris()
X = iris.data

Apply Kmeans and plotting

from sklearn.cluster import KMeans
import matplotlib.pyplot as plt

model_KMeans = KMeans(n_clusters=3)
model_KMeans.fit(X)

plt.scatter(X[:,2],X[:,3],c=model_KMeans.labels_)
plt.xlabel(iris.feature_names[2])
plt.ylabel(iris.feature_names[3])
plt.title('KMeans clustering with 3 clusters')
plt.show()

image

14.1.4. How to find optimal K values:

14.1.4.1. Elbow approach

The optimal K-values can be found from the Elbow using method=”wss”:

wss = []
for k in range(1,10):
    model = KMeans(n_clusters=k).fit(X)
    wss.append(model.inertia_)
    
plt.scatter(range(1,10),wss)
plt.plot(range(1,10),wss)
plt.xlabel("Number of Clusters k")
plt.ylabel("Within Sum of Square")
plt.title("Optimal number of clusters based on WSS Method")
plt.show()

image

14.1.4.2. Gap-Statistics approach

image

E*n: expectation under a sample size of n from the reference distribution image

image

Installation:

This version of Gap Statistics is not official. Until the moment of writing this documentation, no official Gap Statistics has been released in Python. We use the version from milesgranger’s github

pip install git+git://github.com/milesgranger/gap_statistic.git
pip install gapstat-rs

Implement Gap-Statistics:

from gap_statistic import OptimalK

optimalK = OptimalK(n_jobs=1) # No parallel
n_clusters = optimalK(X[:,1:4], cluster_array=np.arange(1, 15))
print('Optimal clusters: ', n_clusters)

Plot Gap-Statistics:

import matplotlib.pyplot as plt
plt.plot(optimalK.gap_df.n_clusters, optimalK.gap_df.gap_value, linewidth=3)
plt.scatter(optimalK.gap_df[optimalK.gap_df.n_clusters == n_clusters].n_clusters,
            optimalK.gap_df[optimalK.gap_df.n_clusters == n_clusters].gap_value, s=250, c='r')
plt.grid(True)
plt.xlabel('Cluster Count')
plt.ylabel('Gap Value')
plt.title('Gap Values by Cluster Count')
plt.show()

image

14.2. Comparison between different clustering methods in sklearn:

image

Key Points

  • K-mean


Mini-Project

Overview

Teaching: 10 min
Exercises: 180 min
Questions
  • What do you learn from Machine Learning workshop using scikit-learn?

Objectives
  • Learn how to apply Machine Learning into your real project

15. MINI PROJECT

Description of Mini Project:

Requirement:

Data

Method

In the ipynb solution file I would like to see the following:

Key Points

  • Self-project