This lesson is being piloted (Beta version)

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