Skip to content
ImagineWorld

Multiple Linear Regression

node_idnode-book_building-statistical-models-in-python_chapter-07-multiple-linear-regression
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num7
chapter_titleMultiple Linear Regression
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

In the last chapter, we discussed simple linear regression (SLR) using one variable to explain a target variable. In this chapter, we will discuss multiple linear regression (MLR), which is a model that leverages multiple explanatory variables to model a response variable. Two of the major conundrums facing multivariate modeling are multicollinearity and the bias-variance trade-off. Following an overview of MLR, we will provide an induction into the methodologies used for evaluating and minimizing multicollinearity. We will then discuss methods for leveraging the bias-variance trade-off to our benefit as analysts. Finally, we will discuss handling multicollinearity using Principal Component Regression (PCR) to minimize overfitting without removing features but rather transforming them instead.

In this chapter, we’re going to cover the following main topics:

  • Multiple linear regression
  • Feature selection
  • Shrinkage methods
  • Dimension reduction

In the previous chapter, we discussed SLR. With SLR, we were able to predict the value of a variable (commonly called the response variable, denoted as y) using another variable (commonly called the explanatory variable, denoted as x). The SLR model is expressed by the following equation where is the intercept term and is the slope of the linear model.

While this is a useful model, in many problems, multiple explanatory variables could be used to predict the response variable. For example, if we wanted to predict home prices, we might want to consider many variables, which may include lot size, the number of bedrooms, the number of bathrooms, and overall size. In this situation, we can expand the previous model to include these additional variables. This is called MLR. The MLR model can be expressed with the following equation.

Like the previous equation, represents an intercept. In this equation, in addition to the intercept value, we have a parameter for each explanatory variable. Each explanatory variable is denoted as x with a numerical subscript. We can include as many explanatory variables as desired in the model, which is why the equation shows a final subscript of.

Impacts of data sizes on MLR

In general, we can include as many explanatory variables as desired in the model. However, there are some realistic limits. One of these potential limits is the number of samples relative to the number of explanatory variables. MLR tends to work best when the number of samples (N) is much less than the number of explanatory variables (P). As P approaches N, the model becomes difficult to estimate. If P is large compared to N, it would be wise to consider dimension reduction, which will be discussed later in this chapter.

Let’s look at an example. The Python package scikit-learn contains several datasets for practice with modeling. We will utilize the diabetes dataset, which includes vital measurements and quantitative measures of the disease progression after one year. More information about this dataset can be found at this link: https://scikit-learn.org/stable/datasets/toy_dataset.html#diabetes-dataset.We will attempt to model the relationship between the vital statistics and the disease progression.

The explanatory variables in this dataset are age, bmi, bp, s1, s2, s3, s4, s5, and s6. The response variable is a measurement of disease progression. This is how we would express this model mathematically:

As discussed previously, we have a for each variable in the model.

Transformations on the diabetes dataset

The explanatory variables in this dataset have been transformed from the original measurements. Referring to the dataset user’s guide, we can see that each variable has been mean-centered and scaled. In addition, the sex variable has been converted from a categorical variable into a numerical variable.

Up until this point, we have only considered continuous variables in our model, that is, variables that can have any value on the number line. Thinking back to Chapter 2*, Distributions of Data*, the variables we have considered before now have been ratio data. However, the linear regression model is not limited to using continuous variables. We can include categorical variables in the model. Recall from Chapter 2*, Distributions of Data*, categorical variables are associated with groups of items. In statistical learning, the groups are generally called levels of the variable. For example, if we had five students, three with MS degrees, one with a PhD degree, and one with a BS degree, we would say that the student categorical variable has three levels: BS, MS, and PhD. Let’s look at how we include categorical variables in the model.

We will include the categorical variable in the model by including additional terms. Specifically, we will add the number of levels () minus one additional term. For the student example with three levels, we would add two additional terms. Using one less than the number of levels will allow us to choose one level as a reference (or baseline) and compare the other levels to that reference level. We include the terms in the model just like the other terms. Let’s say in this example, we are modeling income level, and in addition to the education levels, we have the experience of the individuals. Then, we would construct our model like this:

With the addition of the beta terms, we also must make a data transformation. We will have to create dummy variables for each of the non-reference levels in the categorical variable. This process is called the dummification of the categorical variable. In dummification, we create a column for each non-reference level and insert ones where the level occurs in the original variable and zeros where it does not appear in the original variable. This process is demonstrated in Figure 7*.1*.

Figure 7.1 – Dummification of a categorical variable

The original variable contains the BS, MS, and PhD levels. BS is chosen as the reference level and two dummy variables are created for the levels MS and PhD. This process of creating additional columns for categorical variables is called encoding. There are many types of variable encodings and encoding is a widely used technique in statistical learning and machine learning.

Categorical levels are shifts by a constant

Let’s look a little deeper at the impact of categorical variables on the linear regression model. Earlier, we discussed how categorical variables are encoded with dummy variables that take on values of zero and one. Essentially, that means that we are switching the associated terms, depending on the level, which will shift the response by a constant. For example, in the income model, when we want to calculate the income of an individual with a BS degree, the model resolves to the following:

And when we want to calculate the income of an individual with an MS degree, the model resolves to the following:

This means that levels of categories only shift the output of the model from the reference level by a constant, the beta associated with the level.

Returning to our previous example, our dataset includes a categorical variable: the sex of the patient. The dataset includes two levels for sex. We will choose one level to serve as a reference and we will create a dummy variable for the other level. With this knowledge, let’s fit this data to a linear regression model and discuss the assumptions of multiple linear regression.

Whenever we fit a parametric model, we should verify that the model assumptions are met. As discussed in the previous chapter, if the model assumptions are not met, the model may provide misleading results. In the previous chapter, we discussed the four assumptions for simple linear regression:

  • A linear relationship between the response variable and explanatory variables
  • Normality of the residuals
  • Homoscedasticity of the residuals
  • Independent samples

These assumptions also apply here, but in this new modeling context, we have an additional assumption: no or little multicollinearity. Multicollinearity occurs when two or more of the explanatory variables in an MLR model are highly correlated. The presence of multicollinearity impacts the statistical significance of the independent variables. Ideally, all the explanatory variables will be uncorrelated (or linearly independent). However, we can accept a small amount of multicollinearity without much impact on the model.

Let’s evaluate the model on each of these assumptions.

To check for linear relationships between the response variable and the explanatory variable, we can look at scatter plots of each variable against the response variable. Based on the plots in Figure 7*.2*, several of the variables, including bmi, bp, s3, s4, and s5, possibly exhibit a linear relationship with the response variable.

Figure 7.2 – Scatter plots of the response variable against the explanatory variables

While it would be ideal if any of the variables showed a strong linear relationship with the response variable, in an MLR model, we have the benefit of the combination of variables. We can add variables that appear to be more useful and remove variables that do not appear to be useful. This is called feature selection, which we will cover in the next section.

Recall from the previous chapter that we expect the residuals from a well-fitted model to appear randomly distributed. We could look at this with a histogram or a QQ plot. The residuals from our model are shown in Figure 7*.3*.

Figure 7.3 – Residual value

Based on the histogram in Figure 7*.3*, we cannot reject the possibility that the residuals are normally distributed. In general, when evaluating this assumption, we are checking for egregious violations. It turns out that the linear regression is relatively robust against this assumption. However, that does not mean this assumption can be ignored.

In the previous chapter, we also discussed homoscedasticity. For a well-fitted model, we expect that the residuals should exhibit homoscedasticity. The plot in Figure 7*.4* shows the scatter plot of the residuals against the values predicted by the model.

Figure 7.4 – Scatter plot of model residuals for the predicted versus actual values

There does not appear to be a clear pattern of changing variance or a significant outlier that would violate the assumption of homoscedasticity. If there had been a pattern, that would have been a sign that one or more of the variables may need to be transformed, or a sign of a non-linear relationship between the response and the explanatory variables.

In the last chapter, we discussed independent sampling and its impact on this type of model. However, we cannot make a certain determination on whether the samples are independent without knowing the sampling methodology. Since we do not know the sampling strategy for this dataset, we will assume this assumption is met and proceed with the model. In a real modeling setting, this assumption should never be taken for granted.

The new assumption for MLR is that there is little or no multicollinearity in the explanatory variables. Multicollinearity is a situation that occurs when two or more variables are strongly linearly correlated. We commonly use the variance inflation factor (VIF) to detect multicollinearity. The VIF is a measurement of how much the coefficient of an explanatory variable is influenced by other explanatory variables. A lower VIF is better where the minimum value is 1, meaning there is no correlation. We generally consider a VIF of 5 or more to be too high. When a high VIF is detected in a set of explanatory variables, we repeatedly remove the variable with the highest VIF until the VIF values for each variable are below 5. Let’s look at an example with our current data. The process of removing variables with high VIFs is shown in Figure 7*.5*.

Figure 7.5 – Removing high VIF variables from a dataset

Figure 7*.5* shows the process of removing variables with a high VIF from the diabetes dataset. The leftmost table in the figure shows the original dataset where the highest VIF is 59.2, which corresponds to variable S1. Then, we remove this variable from the dataset and recalculate the VIF. Now we see that the highest VIF is 7.8, corresponding to variable s4. We remove this variable and recalculate the VIF. Now, all VIFs are below 5, indicating that there is a low correlation between the remaining variables. With these variables removed, we need to fit the model again.

With the model fit and the assumptions of the model verified, let’s look at the fit results and discuss how to interpret the results.

Fitting the model, we get the following results from statsmodels. The output is divided into three sections:

  • The top section contains high-level statistics about the model
  • The middle section contains details about the model coefficients
  • The bottom section contains diagnostic tests about the data and the residuals

Let’s walk through each section of this model.

Figure 7.6 – Results from statsmodels OLS regression

High-level statistics and metrics (top section)

Section titled “High-level statistics and metrics (top section)”

In the top section of the fit results, we have model-level information. The left side of the top section contains information about the model such as the degrees of freedom (df) and the number of observations. The right side of the top section contains model metrics. Model metrics are useful for comparing models. We will discuss more about model metrics in the section on feature selection.

The middle section contains details about the model coefficients (the terms in the equations listed previously). For the purposes of this section, we will focus on two columns in the middle section: coef and P>|t|. The coef column is the model coefficient estimated for the model equation (the estimate of or termed ). The column labeled P>|t| is the p-value for a significance test for the coefficient. We are interested in both columns for interpreting the model. Let’s start with the p-value column.

The null hypothesis for this test is that the value of the parameter is equal to zero. Recall the following from Chapter 3*,* Hypothesis Testing:

  • A p-value below the significance threshold means we reject the null hypothesis
  • A p-value above the significance threshold means that we fail to reject the null hypothesis

In this example, we would reject the null hypothesis for the bmi variable, but we fail to reject the null hypothesis for the age variable. Once we have determined the significant variables, we can move on to interpreting the meaning of the significant variables. We will not be able to provide an interpretation of the other variables because we cannot reject that their coefficient values might be zero. If the coefficient value is zero, then the variable makes no contribution to the model. Let’s look at how to interpret the coefficients.

Often, when we construct a model, we want to understand how the parts of the model affect the output. In an MLR model, this comes down to understanding the coefficients of the model. We have two types of variables, continuous and categorical, and the associated coefficients have different meanings.

Interpreting continuous variable coefficients

Section titled “Interpreting continuous variable coefficients”

For the continuous variables, such as BMI, as the value of the variable increases, so does its significance to the output of the model. A unit increase in the value of the variable is associated with an increase in the mean of the dependent variable by the size of the coefficient with all other variables held constant. Let’s take the bmi variable as an example. Since the coefficient of the bmi variable is approximately 526, we would say, “A unit increase in bmi would be associated with a 526 increase in the mean of the diabetes measurement with all other variables held constant.” Of course, the coefficients can also take on negative values.

Interpreting categorical variable coefficients

Section titled “Interpreting categorical variable coefficients”

For the categorical variables, such as sex, recall that, unlike the continuous variables, the values of the categorical are dummy-encoded, and therefore can only take on two values: zero and one. Also, recall that one level was chosen to be the reference level. In this case, sex level 0 is the reference level, and we can compare this reference to sex level 1. When we use the reference level, the coefficient will not affect the output of the model. Thus, the categorical-level change is associated with a change in the mean of the dependent variable by the size of the coefficient with all other variables held constant. Since the coefficient of the sex variable is approximately -22, we would say, “The level of sex is associated with a decrease of 22 in the mean of the diabetes measurement compared to the reference level with all other variables held constant.”

The bottom section of the fit results contains diagnostic statistics for the data and residuals. Glancing over the list, several should be from Chapter 6*, Simple Linear Regression*. The Durbin-Watson test is a test for serial correlation (data sampled sequentially over time). A result around 2 is not indicative of serial correlation. The skew and kurtosis are measurements of the shape of the distribution of the residuals. These results indicate almost no skew, but possibly some kurtosis. These are likely small deviations from the normal distribution and are not cause for concern as we saw in the plots earlier.

In this section, we looked at our first model that can use multiple explanatory variables to predict a response variable. However, we noticed that several of the variables included in the model were not statistically significant. For this model, we only selected features by removing any features that had high VIF scores, but there are other methods to consider when choosing features. In the next section, we will discuss comparing models and feature selection.

The are many factors that influence the success or failure of a model, such as sampling, data quality, feature creation, and model selection, several of which we have not covered. One of those critical factors is feature selection. Feature selection is simply the process of choosing or systematically determining the best features for a model from an existing set of features. We have done some simple feature selection already. In the previous section, we removed features that had high VIFs. In this section, we will look at some methods for feature selection. The methods presented in this section fall into two categories: statistical methods for feature selection and performance-based methods for feature selection. Let’s start with statistical methods.

Statistical methods for feature selection rely on the primary tool that we have used throughout the previous chapters: statistical significance. The methods presented in this sub-section will be based on the statistical properties of the features themselves. We will cover two statistical methods for feature selection: correlation and statistical significance.

The first statistical method we will discuss is correlation. We have discussed correlation in this chapter and in previous chapters; recall that correlation is a description of the relationship between two variables. Variables can be positively correlated, uncorrelated, or negatively correlated. In terms of feature selection, we want to remove features that are uncorrelated with the response variable. A feature that is uncorrelated with the response variable does not have a relationship with the response variable. Thus, an uncorrelated feature would not be a good predictor of the response variable.

Recall from Chapter 4*, Parametric Tests*, that we can use Pearson’s correlation coefficient to measure the linear correlation between two variables. In fact, we can calculate the correlation coefficient between all features and the target variable. After performing those calculations, we can construct a correlation ranking as shown in Figure 7*.7*.

Figure 7.7 – Feature correlation ranking

When evaluating features based on correlation, we are most interested in features with a high absolute correlation. For example, the correlation ranking in Figure 7*.7* shows the following:

  • bmi and s5 exhibit a strong correlation with the response variable
  • bp, s4, s6, and s3 exhibit moderate correlation with the response variable
  • s1, age, and s2 exhibit a weak correlation with the response variable

While sex may appear to show no correlation with the response variable, Pearson’s correlation coefficient cannot be used with categorical features. From this correlation ranking, we can see that, at least, bmi, s5, and bp, are likely among the best features in this dataset for predicting the response. In fact, these features were considered statistically significant in our model. Now let’s discuss selection using statistical significance.

Assessing features using correlation is generally a good first step for feature selection. We can easily eliminate features that are uncorrelated with the response variable. However, depending on the problem, we could still be left with many features that are correlated with the response. We can further select features using the statistical significance of the feature in the context of a model. However, in recent years, these methods for feature selection have somewhat fallen out of favor in the community. For this reason, we will not focus on these methods, but will only describe them for understanding.

Recall when we fit the MLR model, the results included a test for statistical significance for each feature in the model. We can use that test to select features. There are three well-known algorithms for selecting features based on statistical significance: forward selection, backward selection, and stepwise regression. In forward selection, we start without any variables in the model and then iteratively add one variable at a time using the p-value to choose the best feature to add at each iteration. We stop once the p-values of any features in the model size are above a predefined threshold, such as 0.05. Backward selection takes the opposite approach. We start with all features in the model, then iteratively remove features one variable at a time using the p-value to determine the least important feature. The final algorithm is stepwise regression (also called bidirectional elimination). Stepwise regression is performed using both forward and backward tests. Start with no features in the model, then in each iteration, perform one forward selection step followed by one backward selection pass.

These selection methods were widely used in the past. However, in recent years, performance-based methods have become more widely used. Let’s discuss performance-based methods now.

Performance-based methods for feature selection

Section titled “Performance-based methods for feature selection”

The primary issue with the statistical feature selection methods mentioned previously is that they tend to create overfit models. An overfit model is a model that fits the given data exactly and fails to generalize to new data. Performance-based methods overcome overfitting using a method called cross-validation. In cross-validation, we have two datasets: a training dataset used to fit the model and a test dataset for evaluating the model. We can build models from multiple sets of features, fit all those potential models on the training set, and finally rank them based on the performance of the models on the testing set with a given metric.

Before we get into feature selection methods, let’s first discuss how to compare models. We use metrics to compare models. On a basic level, we can use metrics to help us determine whether one set of features is better than another set of features based on model performance. Many metrics can be used for comparing models. We will discuss two metrics, mean square error (MSE) and mean absolute percentage error (MAPE), which are, by far, two of the most commonly used metrics for regression models.

The MSE is given by the following formula, where N is the number of samples, is the response variable, and is the predicted value of the response variable.

In other words, take the differences between the response values and the predicted response values, square the differences, and finally take the mean of the squared differences. A small extension of this metric commonly used is the root mean squared error (RMSE), which is simply the square root of the MSE. The RMSE is used when it is desirable for the metric to have the same units as the response variable.

The MAPE is given by the following formula, where N is the number of samples, is the response variable, and is the predicted value of the response variable:

This formula is like the formula for the MSE, but instead of taking the mean of the squared error, we take the mean of the percent error. This makes the MAPE easier to interpret than the MSE, which is a distinct advantage over the MSE.

Now that we have discussed model validation and metrics, let’s put these concepts together to perform feature selection using model performance as an indicator.

Recursive feature elimination (RFE) is a method for selecting an optimal number of features in a model using a metric. Much like the backward selection method mentioned previously, the RFE algorithm starts with all features in the model, then removes features with the least influence on the model. At each step, cross-validation is performed. When RFE is completed, we will be able to see the cross-validation performance of the model over the various sets of features.

In this example, we use the linear regression implementation and RFE implementation from scikit-learn (sklearn), which is a primary package used for machine learning in the Python ecosystem. In the following code example, we set up RFE to use the MAPE as the scoring metric (make_scorer(mape ,greater_is_better=False)), remove one feature at each step (step=1), and indicate with cv=2 that it should score the model using two cross-validation sets:

linear_model = LinearRegression()
linear_model.fit(X, y)
rfecv = RFECV(
estimator=linear_model,
step=1,
cv=2,
scoring=make_scorer(mape ,greater_is_better=False),
min_features_to_select=1
)
rfecv.fit(X,y)

Once we fit the RFE object, we can look at the results to see how to model scored over the various sets of features. The performance of the model using the MAPE is shown in Figure 7*.8*.

Figure 7.8 – Linear regression performance over RFE steps, scoring with the MAPE

It’s clear that including all features produces the best-performing model but including all 10 features only provides a small increase over the performance of just five features. While the best-performing model contains all 10 features, we would still need to consider model assumptions and verify that the model is well fit.

In this section, we have looked at several methods for feature selection, including statistical methods and performance-based methods. We also discussed metrics and how to compare models, including the reason for splitting the data into training and validation sets. In the next section, we will look at linear regression shrinkage methods. These types of models use a method called regularization, which in some ways acts like model-based feature selection.

The bias-variance trade-off is a decision point all statistics and machine learning practitioners must balance when performing modeling. Too much of either renders results useless. To catch these when they become issues, we look at test results and the residuals. For example, assuming a useful set of features and the appropriate model have been selected, a model that performs well on validation, but poorly on a test set could be indicative of too much variance and conversely, a model that fails to perform well at all could have too much bias. In either case, both models fail to generalize well. However, while bias in a model can be identified in poor model performance from the start, high variance can be notoriously deceptive as it has the potential to perform very well during training and even during validation, depending on the data. High-variance models frequently use values of coefficients that are unnecessarily high when very similar results can be obtained from coefficients that are not. Further, in using coefficients that are not unnecessarily high, the model is more likely to be in bias-variance equilibrium, which provides it a better chance of generalizing well on future data. Additionally, more reliable insights into the influence of current factors on a given target are provided when model coefficients are not exaggerated, which aids in more useful descriptive analysis. This brings us to the concept of shrinkage.

Shrinkage is a method that reduces model variance by shrinking model parameter coefficients toward zero. The coefficients are derived by applying least squares regression to all variables considered for a model. The amount of shrinkage is based on the parameters’ contribution to least squares estimates; parameters that contribute to a high level of squared error will have their coefficients pushed toward zero or zeroed out altogether. In this case, shrinkage can be used for variable elimination. Variables that do not contribute to high squared error across the model fit will have a minimal reduction in coefficient value, thus being useful for model fitting, assuming the practical purpose of their inclusion is vetted. The reason shrinkage – also called regularization – is important is because it helps models include useful variables while preventing them from introducing too much variance and thus overfitting. Preventing excess variance is particularly useful for ensuring that models generalize well over time. Let’s look at some of the most common shrinkage techniques, ridge regression and Least Absolute Shrinkage and Selection Operator (LASSO) Regression.

Recall the formulation for the residual sum of squared errors (RSS) for multiple linear regression using least squares regression is as follows:

where n is the number of samples and p is the number of parameters. Ridge regression adds a scalar, λ, called a tuning parameter – which must be greater than or equal to 0 – that gets multiplied by the model parameter coefficient estimates,, to create a shrinkage penalty. This gets added back to the RSS equation such that the new least squares regression’s fitting procedure is now defined as follows:

When λ=0, the respective ridge regression penalty term is 0. However, as, the model coefficients shrink toward zero. The new fitting procedure can be rewritten as follows:

where RSS = is the squared norm (Euclidean norm) of the regression coefficients array, and X is the design matrix. Further simplification brings this to the following:

which can be rewritten in the closed form by using the tuning parameter’s scalar multiple of the identity matrix to derive the ridge regression coefficient estimates,, as follows:

Simply stated, the ridge regression coefficient estimates are the set of coefficients that minimizes the least squares regression output as follows:

Standardizing coefficients prior to applying ridge regression

Because ridge regression seeks to minimize the error for the entire dataset and the tuning parameter for doing so is applied within the norm normalization process of taking the root of summed squared terms, it is important to apply a standard scaler to each variable in the model so that all variables are on the same scale, prior to applying ridge regression. If this is not performed, ridge regression will almost certainly fail to be useful for helping the model generalize across datasets.

In summary, ridge regression reduces variance in a model by using the penalty, which penalizes the sum of squared coefficients. However, it is important to note the norm, and consequently, ridge regression, will never produce a zero-valued coefficient. Therefore, ridge regression is an excellent tool for reducing variance when the analyst seeks to use all terms in the model. However, ridge regression cannot be used for variable elimination. For variable elimination, we can use the LASSO regression shrinkage method, which uses the penalty to regularize coefficients with the norm, which uses the absolute value to shrink values to and including zero.

Let’s walk through an example of a ridge regression implementation in Python.

First, let’s load the Boston home prices dataset from scikit-learn. In the final line, we add the constant for the intercept. Note that this process can be repeated with comparable results, albeit with different input variables, using the California housing data set by running from sklearn.datasets import fetch_california_housing in place of from sklearn.datasets import load_boston:

from sklearn.metrics import mean_squared_error as MSE
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import load_boston
import statsmodels.api as sm
import pandas as pd
boston_housing = load_boston()
df_boston = pd.DataFrame(boston_housing.data, columns = boston_housing.feature_names)
df_boston['PRICE'] = boston_housing.target
df_boston = sm.add_constant(df_boston, prepend=False

The first three records are given here:

Figure 7.9 – First three records of the Boston housing data

We set PRICE as our target. Recall, ridge regression is most useful when there are either more parameters than samples or there is excessive variance. Let’s assume both of these assumptions are met:

X = df_boston.drop('PRICE', axis=1)
y = df_boston['PRICE']

As noted previously, data must be standardized for ingestion into the norm, so let’s apply that with scikit-learn ’s StandardScaler function:

sc = StandardScaler()
X_scaled = sc.fit_transform(X)

Next, let’s take a 75/25 train/test split of the data for the model. We use shuffle=True to randomly shuffle the data so we test with a random sample, which is more likely to be representative of the population:

X_train, X_test, y_train, y_test = train_test_split(
X_scaled, y, test_size=0.25, shuffle=True)

Now we can compare ordinary least squares (OLS) regression to OLS regression using coefficients regularized through ridge regression. In the imported function here, fit_regularized, we set the required argument for method to 'elastic_net'. We will discuss Elastic Net shortly, but for now, note the L1_wt argument applies ridge regression when set to 0. Alpha is the tuning parameter, λ, in the ridge regression penalty term. A small alpha allows for large coefficients and a large alpha pushes the coefficients toward zero. Here, we fit the training data to derive the mean squared error:

ols_model = sm.OLS(y_train, X_train)
compiled_model = ols_model.fit()
compiled_model_ridge = ols_model.fit_regularized(method = 'elastic_net', L1_wt=0, alpha=0.1,refit=True)
print('OLS Error: ', MSE(y_train,
compiled_model.predict(X_train)) )
print('Ridge Regression Error: ', MSE(y_train,
compiled_model_ridge.predict(X_train)))

We can see ridge regression has a slightly higher amount of error

OLS Error:  ``530.7235449265926

Ridge Regression Error:  ``533.2278083730833

Next, we fit the test data to see how the model generalizes on unseen data. We measure again with the mean squared error:

print('OLS Error: ', MSE(y_test, compiled_model.predict(X_test)) )
print('Ridge Regression Error: ', MSE(y_test, compiled_model_ridge.predict(X_test)))

We can see that the number of errors increased for both on the test data. However, the OLS regression produced a slightly higher error in proportion to the ridge regression approach:

OLS Error:  ``580.8138216493896

Ridge Regression Error:  ``575.5186673728349

Here, we can observe the OLS regression coefficients and the regularized coefficients in Figure 7*.10*:

Figure 7.10 – OLS regression coefficients before and after ridge regression regularization

Earlier in this section, we mentioned how variable coefficients with unnecessarily high values contribute to model variance, and in so doing, take away a model’s ability to generalize as well as it could were the coefficients reasonable. We demonstrated applying ridge regression to enact this. A very popular alternative to ridge regression, however, is LASSO regression. LASSO regression follows a similar procedure of adding a penalty term to the model’s residual sum of squared error and seeks to minimize the resulting value (error). However, LASSO uses the norm rather than. Consequently, it is possible to obtain absolute zero coefficient values as the tuning parameter reaches a sufficient size, thus functioning as a feature selection and shrinkage tool.

The LASSO equation seeks to minimize overall model error by shrinking each variable’s coefficient using the following method:

The only difference between LASSO and ridge regression is the penalty term.

Choosing λ

The value of the tuning parameter, λ, is best selected using cross-validation. While the tuning parameter can go to infinity, in theory, it is typical to start with values less than 1, such as at 0.1 increasing by increments of tenths up to 1. After, typically integer values are used.

Using the same data we used for ridge regression, we apply LASSO regression. Here, we set L1_wt=1, indicating the norm will be applied:

ols_model = sm.OLS(y_train, X_train)
compiled_model = ols_model.fit()
compiled_model_lasso = ols_model.fit_regularized(method='elastic_net', L1_wt=1, alpha=0.1,refit=True)

We will follow the same steps for LASSO as with ridge regression in that we first check the errors on the training data, then again on the test data to see how the models generalize:

print('OLS Error: ', MSE(y_train, compiled_model.predict(X_train)) )
print('LASSO Regression Error: ', MSE(y_train, compiled_model_lasso.predict(X_train)))

The output shows OLS regression slightly outperforming LASSO. This could be due to higher variance. However, practically speaking, the results are the same:

OLS Error: 530.7235449265926

LASSO Regression Error: 531.2440812254207

Now, we need to check the model’s performance on the holdout data:

print('OLS Error: ', MSE(y_test, compiled_model.predict(X_test)) )
print('LASSO Regression Error: ', MSE(y_test, compiled_model_lasso.predict(X_test)))

We can see the two models again have essentially the same error. However, with fewer features, the LASSO model may be easier to trust to generalize on future data. That may depend on the researcher’s level of subject knowledge, however:

OLS Error: 546.1338399374557

LASSO Regression Error: 546.716239805892

As with ridge regression, some of the coefficients have been minimized in the norm regularization process. However, we also see, using the same alpha value, four variables have been minimized to zero, thus eliminating them from the model altogether. Three of the features were comparatively shrunk almost to zero by ridge regression, but not ZN, which we see in Figure 7*.11* has been reduced to 0. The model error has been slightly improved, which may not appear significant, but when considering the elimination of four variables, we can consider the model to have more generalization with less dependence on exogenous variables.

Figure 7.11 – OLS regression coefficients before and after LASSO regression regularization

Elastic Net is another common shrinkage method that can be applied to manage a bias-variance trade-off. This method applies the tuning parameter to a combination of ridge and LASSO regression where the proportion of influence from either is determined by the hyperparameter α. The equation Elastic Net minimizes is as follows:

Naturally, depending on the values of α, Elastic Net can also generate absolute zero-valued coefficient parameter estimates where it cancels out the ridge regression penalty term. When all input variables are needed – for example, if they have already been pruned following procedures such as those outlined in the Feature selection section of this chapter – Elastic Net is most likely to outperform both ridge and LASSO regression, especially when there are highly correlated features in the dataset that must be included to capture necessary variance. In the next section, we will discuss dimension reduction. Specifically, we p rovide an in-depth overview of PCR, which uses Principal Component Analysis (PCA) to extract useful information from systems that contain correlated features required to evaluate the target.

First, let’s walk through a regression example using Elastic Net using the same data we used for ridge and LASSO regression. Following the previous Elastic Net minimizing equation, we set Lt_wt=0.5, meaning an equal, 50/50 balance between ridge and LASSO regression. Differently, however, we applied alpha=8 instead of 0.1 as we used in ridge and LASSO regression to gain an improvement over the OLS regression coefficients. Recall that as the tuning parameter approaches infinity, coefficients approach 0. Therefore, we can conclude based on the Elastic Net coefficients that 8 is a very high tuning parameter:

ols_model = sm.OLS(y_train, X_train)
compiled_model = ols_model.fit()
compiled_model_elastic = ols_model.fit_regularized(method='elastic_net', L1_wt=0.5, alpha=8,refit=True)

Let’s test the model on the training data:

print('OLS Error: ', MSE(y_train, compiled_model.predict(X_train)) )
print('Elastic Net Regression Error: ', MSE(y_train, compiled_model_elastic.predict(X_train)))

Here, we see Elastic Net has added errors into the model compared to OLS regression:

OLS Error: 530.7235449265926

Elastic Net Regression Error: 542.678919923863

Now let’s check the model errors for the holdout data:

print('OLS Error: ', MSE(y_test, compiled_model.predict(X_test)) )
print('Elastic Net Regression Error: ', MSE(y_test, compiled_model_elastic.predict(X_test)))

Observing the results in Figure 7*.12*, we can see how Elastic Net has traded variance – which increased the error on training – for bias, which has enabled the model to generalize better on holdout. We can see better results with Elastic Net than OLS regression on holdout. However, the improved error suggests the added bias provided a better chance of lower error, but is not something to be expected:

OLS Error: 546.1338399374557

Elastic Net Regression Error: 514.8301731640446

Here we can see the coefficients before and after Elastic Net’s implementation:

Figure 7.12 – OLS regression coefficients before and after Elastic Net regularization

We can see with a sufficiently large tuning parameter value (alpha=8), most of the coefficients with the balanced Elastic Net have been forced to absolute zero. The only coefficients remaining had comparatively large values with OLS regression. Notably, for the variables that remain with coefficients (RM and LSTAT), Elastic Net increased both coefficients where ridge regression and LASSO either reduced them slightly.

In this section, we will use a specific technique – PCR – to study MLR. This technique is useful when we need to deal with a multicollinearity data issue. Multicollinearity occurs when an independent variable is highly correlated with another independent variable, or an independent variable can be predicted from another independent variable in a regression model. A high correlation can affect the result poorly when fitting a model.

The PCR technique is based on PCA as used in unsupervised machine learning for data compression and exploratory analysis. The idea behind it is to use the dimension reduction technique, PCA, on these original variables to create new uncorrelated variables. The information obtained on these new variables helps us to understand the relationship and then apply the MLR algorithm to these new variables. The PCA technique can also be used in a classification problem, which we will discuss in the next chapter.

PCA is a dimension reduction technique based on linear algebra by linearly transforming data using linear combinations of original variables into a new coordinate system. These new linear combinations are called principal components (PCs). The difference between the PCA technique and the feature selection technique or shrinkage methods mentioned in previous sections is that the original independent variables are maintained but the new PC variables are transformed into a new coordinate space. In other words, PCA uses the original data to arrive at a new representation or a new structure. The number of PC variables is the same as the number of original independent variables, but these new PC variables are uncorrelated with each other. The PC variables are created and ordered from the most to the least amount of variability. The sum of variances is the same between the original independent variables and the newly transformed PC variables.

Before conducting PCA, we perform pre-processing for the dataset by subtracting the mean from each data point and normalizing the standard deviation of each independent variable. In a high-level structure, the goal of the PCA technique is to find vectors such that any data point,, in the dataset can be approximately represented as a linear combination:

for some constants with Assume that we have these vectors; then, each data point can be written as a vector in corresponding the projections:

In other words, if we have original independent variables, we will construct a dimensional transformation matrix that can map any data point onto a new -dimensional variable subspace with smaller than. It means that we have performed a dimension reduction by a linear transformation of the original independent variables. There are several applications of PCA, but here, we will cite a paper, Gene mirror geography within Europe, published in Nature (2008) (https://pubmed.ncbi.nlm.nih.gov/18758442/). Authors considered a sample of 3,000 European individuals genotyped at over half a million variable DNA sites in the human genome; then, each individual was represented using more than half a million genetic markers. This means that it produced a matrix with dimensions larger than 3,000 x 500,000. They performed a PCA on the dataset to find the most meaningful vectors, and (the first and second components), where each person only corresponds to two numbers. The authors plotted each person based on two numbers in a two-dimensional plane and then colored each point according to the country they came from.

Figure 7.13 – PCA analysis for gene mirror geography within Europe

Figure 7.14 – PCA analysis for gene mirror geography within Europe

Surprisingly, the PCA technique performed well in the plots by showing genetic similarities that are similar to the European map.

In the next part, we will discuss how to use PCA to conduct a PCR analysis in practice.

PCR – a hands-on salary prediction study

Section titled “PCR – a hands-on salary prediction study”

To conduct a PCR analysis, we first perform a PCA to obtain the PCs and then decide to keep the first PCs that contain the most explainable amount of variability. Here, is the dimensionality of the new PC variable space. Finally, we fit MLR on these new variables.

We will consider a hands-on salary prediction task from the open source Kaggle data – https://www.kaggle.com/datasets/floser/hitters – to illustrate the PCR method. If following along, please download the dataset from the Kaggle URL:

  1. Setting up and loading Import the necessary libraries to be used in this study and loading the Hitters data. For simplicity, we will drop all missing values in the dataset. There are 19 independent variables (16 numerical and 3 categorical) with the target ‘ Salary ’. The categorical independent variables ‘ League ’, ‘ Division ’, and ‘ NewLeague ’ are converted into dummy variables. We preprocess and standardize the features, and create a train and a test set before conducting the PCA step:
    # Import libraries
    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    from sklearn.preprocessing import scale
    from sklearn.linear_model import LinearRegression
    from sklearn.model_selection import KFold, cross_val_score, train_test_split
    from sklearn.metrics import mean_squared_error
    from sklearn.decomposition import PCA
    #location of dataset
    url = "/content/Hitters.csv"
    #read in data
    data = pd.read_csv(url).dropna() # to simply the analysis, we drop all missing values
    # create dummies variables
    dummies_variables = pd.get_dummies(data[['League', 'Division', 'NewLeague']])
    # create features and target
    target = data['Salary']
    feature_to_drop = data.drop(['Salary', 'League', 'Division', 'NewLeague'],axis=1).astype('float64')
    X = pd.concat([feature_to_drop, dummies_variables[['League_N', 'Division_W', 'NewLeague_N']]], axis=1)
    #scaled data - preprocessing
    X_scaled = scale(X)
    # train test split
    X_train, X_test, y_train, y_test = train_test_split(X_scaled, target, test_size=0.2, random_state=42)
  2. Generating As the next step, we generate all the PCs for the training set. This performance produces 19 new PC variables because there are 19 original independent variables:
    # First generate all the principal components
    pca = PCA()
    X_pc_train = pca.fit_transform(X_train)
    X_pc_train.shape
  3. Determining the best number of PCs to The next step is to perform a 10-fold cross-validation MLR and choose the best number of PCs to use by using the RMSE:
    # Define cross-validation folds
    cv = KFold(n_splits=10, shuffle=True, random_state=42)
    model = LinearRegression()
    rmse_score = []
    # Calculate MSE score - based on 19 PCs
    for i in range(1, X_pc_train.shape[1]+1):
    rmse = -cross_val_score(model, X_pc_train[:,:i], y_train, cv=cv, scoring='neg_root_mean_squared_error').mean()
    rmse_score.append(rmse)
    # Plot results
    plt.plot(rmse_score, '-o')
    plt.xlabel('Number of principal components in regression')
    plt.ylabel('RMSE')
    plt.title('Salary')
    plt.xlim(xmin=-1)
    plt.xticks(np.arange(X_pc_train.shape[1]), np.arange(1, X_pc_train.shape[1]+1))
    plt.show()
    Here’s the plot produced:

Figure 7.15 – Number of PCs

From this, we see that the best number of PCs is 6, corresponding with the lowest cross-validation RMSE.

  1. Retraining the model and We will use this number to train a regression model on the training data and make predictions on the test data:
    # Train regression model on training data
    model = LinearRegression()
    model.fit(X_pc_train[:,:6], y_train)
    pcr_score_train = -cross_val_score(model, X_pc_train[:,:6], y_train, cv=cv, scoring='neg_root_mean_squared_error').mean()
    # Prediction with test data
    X_pc_test = pca.fit_transform(X_test)[:,:6]
    pred = model.predict(X_pc_test)
    pcr_score_test = mean_squared_error(y_test, pred, squared=False)

Remark that PCR analysis is more difficult to interpret the results of than feature selection or shrinkage methods, and this analysis performance is better if the few first PCs capture the most explainable amount of variability.

In this chapter, we discussed the concept of MLR and topics aiding in its implementation. These topics included feature selection methods, shrinkage methods, and PCR. Using these tools, we were able to demonstrate approaches to reduce the risk of modeling excess variance. In doing so, we were able to also induce model bias so that models can have a better chance of generalizing on unseen data with minimal complications as frequently faced when overfitting.

In the next chapter, we will begin a discussion on classification with the introduction of logistic regression, which fits a sigmoid to a linear regression model to derive probabilities of binary class membership.