Skip to content
ImagineWorld

Simple Linear Regression

node_idnode-book_building-statistical-models-in-python_chapter-06-simple-linear-regression
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num6
chapter_titleSimple Linear Regression
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

In previous chapters, we worked with distributions of single variables. Now we will discuss the relationships between variables. In this chapter and the next chapter, we will investigate the relationship between two or more variables using linear regression. In this chapter, we will discuss simple linear regression within the framework of Ordinary Least Squares (OLS) regression. Simple linear regression is a very useful tool for estimating continuous values from two linearly related variables. We will provide an overview of the intuitions and calculations behind regression errors. Next, we will provide an overview of the pertinent assumptions of linear regression. After that, we will analyze the output summary of OLS in statsmodels, and finally, we will address the scenarios of serial correlation and model validation. As highlighted, our main topics in this chapter follow this framework:

  • Simple linear regression using OLS
  • Coefficients of correlation and determination
  • Required model assumptions
  • Test for significance
  • Handling model errors
  • Validating models

We will study one of the simplest machine learning models – simple linear regression. We will provide its overview within the context of OLS, where the objective is to minimize the sum of the square of errors. It is a straightforward concept related to a dependent variable (quantitative response) and its independent variable, where their relationship can be drawn as a straight line, approximately. Mathematically, a simple linear regression model can be written in the following form:

Here, is the intercept term and is the slope of the linear model. The error term is denoted as in the preceding linear model. We can see that in an ideal case where the error term is zero, represents the value of the dependent variable at. Within the range of the independent variable, represents the increase in the outcome corresponding to a unit change in In literature, the independent variable can be called the explanatory variable, predictor, input, or feature and the dependent variable can be called the response variable, output, or target. The question is raised, “If we have a sample from a dataset with points), how do we determine a line of best fit using the intercept term and the slope?” By estimating these terms, we will fit the best line through the data to show the linear relationship between the independent variable and the dependent variable.

Figure 6.1 – The relationship between x and y – Line of best fit

In the preceding plot example, the blue points are actual values representing the relationship between the independent variable and the dependent variable. The red line is the line of best fit through all these data points. Our objective now is to formulate the predicted line (the line of best fit):

Take a closer look at the relationship between the predicted values and the true values. In order to find the line of best fit, we will minimize the vertical distances, meaning that we will minimize the errors between the points and the line through the data. In other words, we will minimize the sum of square errors, which is computed by the following:

Figure 6.2 – Errors between data points and the line through the data

Here,

where is the observed value and is the predicted value of the response variable for the observation. The sum of the square of errors is given by:

To minimize S, we will take the partial derivatives with respect to and Then, we see:

Therefore, it is easy to see that:

This implies:

Because and, we can rewrite the slope and intercept as follows:

,

In Python, we can implement the following code to find and as follows:

def least_squares_method(x,y):
x_mean=x.mean()
y_mean=y.mean()
beta1 = ((x-x_mean)*(y-y_mean)).sum(axis=0)/ ((x-x.mean())**2).sum(axis=0)
beta0 = y_mean-(beta1*x_mean)
return beta0, beta1

Coefficients of correlation and determination

Section titled “Coefficients of correlation and determination”

In this section, we will discuss two related notions – coefficients of correlation and coefficients of determination.

A coefficient of correlation is a measure of the statistical linear relationship between two variables and can be computed using the following formula:

The reader can go here – https://shiny.rit.albany.edu/stat/corrsim/ – to simulate the correlation relationship between two variables.

Figure 6.3 – Simulated bivariate distribution

By observing the scatter plots, we can see the direction and the strength of the linear relationship between the two variables and their outliers. If the direction is positive (r>0), then both variables increase or decrease together.

Figure 6.4 – Simulated bivariate distribution

If the direction is negative, then one variable increases while the other decreases. We illustrate this in the following scatter plot:

Figure 6.5 – Simulated bivariate distribution

The coefficient of correlation exists as a value between -1 and 1. When r =1, we have a perfect positive correlation, and when r = -1, we have a perfect negative correlation. Observe that the value of the coefficient of correlation does not change if, for example, the variable and the variable are switched or if all values of either variable are linearly scaled. In general, correlation does not imply causation.

The coefficient of determination is just, where is the coefficient of correlation, which is a proportion of the variation in the variable, explained by the variable. The value of is between 0 and 1, with the linear relationship between the two variables becoming stronger as its value approaches 1. The value of can also be computed using the following formula:

Here, is the sum of the square of errors and is the total sum of the square of the difference between the actual value and the average value. In statsmodels, from the output of the OLS regression results, the value of determination can be obtained. This output is discussed in the next sections of this chapter.

Like the parametric tests we discussed in Chapter 4*, Parametric Tests*, linear regression is a parametric method and requires certain assumptions to be met for the results to be valid. For linear regression, there are four assumptions:

  • A linear relationship between variables
  • The normality of the residuals
  • The homoscedasticity of the residuals
  • Independent samples

Let’s discuss each of these assumptions individually.

A linear relationship between the variables

Section titled “A linear relationship between the variables”

When thinking about fitting a linear model to data, our first consideration should be whether the model is appropriate for the data. When working with two variables, the relationship between the variables should be assessed with a scatter plot. Let’s look at an example. Three scatter plots are shown in Figure 6*.6*. The data is plotted, and the actual function used to generate the data is drawn over the data points. The leftmost plot shows data exhibiting a linear relationship. The middle plot shows data exhibiting a quadratic relationship. The rightmost plot shows two uncorrelated variables.

Figure 6.6 – Three scatter plots depicting three distinct relationships between two variables

Of the example data in Figure 6*.6*, a linear model would only be appropriate for the leftmost data. In this example, we have the benefit of knowing the actual relationship of the two variables, but, in real problems, you will have to determine whether a linear model is appropriate. Once we have assessed whether a linear model is appropriate and fitted a linear model, we can assess the two assumptions that depend on the model residuals.

In the previous two chapters, we discussed normality at length and looked at several examples of data that are normally distributed and several examples that were not normally distributed. In this case, we are making the same assessment, but it is for the model residuals rather than for the variables. In fact, unlike the previous parametric methods, the variables themselves do not need to be normally distributed, only the residuals. Let’s look at an example. We will fit a linear model on two variables, each of which exhibits a skewed distribution. As can be seen in Figure 6*.7*, even though each variable has a skewed distribution, the variables are linearly correlated.

Figure 6.7 – Distributions of X, Y, and their scatter plots

Now, let’s look at the residuals from the model fit. The residuals from the model fit are shown in Figure 6*.8*. As we expect, the residuals from this model fit appear to be normally distributed. This model appears to meet the assumption of normally distributed residuals.

Figure 6.8 – Residuals from model fit

With the assumption of normally distributed residuals verified, let’s move on to the assumption of homoscedasticity of the residuals.

Not only should the residuals be normally distributed, but the residuals should also have constant variance over the linear model. Homoscedasticity refers to the residuals having equal scatter. Conversely, residuals that do exhibit equal spread are said to be heteroscedastic. Homoscedasticity is generally assessed by plotting the residuals against the model predictions with a scatter plot. The residuals should appear to be randomly distributed with a mean of 0 and equally dispersed along the x axis. Figure 6*.9* shows a scatter plot of the model residuals against the predicted value of Y. These residuals appear to exhibit homoscedasticity.

Figure 6.9 – Scatter plot of model residuals versus prediction

There are a few common ways the homoscedasticity of the residuals could be violated:

  • The residuals show a systematic change in variance
  • There is an extreme outlier

Two examples of these violations are shown in Figure 6*.10*. The left plot shows an extreme outlier, and the right plot shows non-constant variance in the residuals. In both cases, the model assumptions are violated.

Figure 6.10 – Example residuals that exhibit poor behavior

When the residuals show a systematic pattern, it may be an indication that another type of model would be more appropriate, or it may be helpful to apply a transformation to one or both variables. When an extreme outlier is present, it may be worth verifying and investigating the data point to ensure it should be included in the analysis. In the next section, we will discuss how extreme outliers impact the model fit.

We have discussed sample independence in previous chapters. There are no graphics or statistics that can be used to determine whether samples are independent. Assessing sample independence requires careful analysis of the sampling method and the populations from which the samples are drawn. For example, a common type of data that violates the independence assumption is time-series data. Time-series data is a type of data that is sampled over time, making it serially correlated. We will discuss analysis methods for time-series data in later chapters.

In this section, we discussed the linear regression model assumptions. In the next section, we will discuss how to validate a linear model, which will again utilize the model residuals.

Testing for significance and validating models

Section titled “Testing for significance and validating models”

Up to this point in the chapter, we have discussed the concepts of the OLS approach to linear regression modeling; the coefficients in a linear model; the coefficients of correlation and determination; and the assumptions required for modeling with linear regression. We will now begin our discussion on testing for significance and model validation.

To test for significance, let us load statsmodels macrodata data set so we can build a model that tests the relationship between real gross private domestic investment, realinv, and real private disposable income, realdpi:

import numpy as np
import pandas as pd
import seaborn as sns
import statsmodels.api as sm
import matplotlib.pyplot as plt
from statsmodels.nonparametric.smoothers_lowess import lowess
df = sm.datasets.macrodata.load().data

Least squares regression requires a constant coefficient in order to derive the intercept. In the least squares equation,, the first column of the design matrix, X, requires a set of ones. However, this constant must be added in directly, which we do with statsmodels’ add_constant function here:

df = sm.add_constant(df, prepend=False)
df_mod = df[['realinv','realdpi','const']]

The input data does not need to be normally distributed for least squares regression. However, it is assumed that the residuals of the model are normally distributed. However, it is useful to see the spread of the data to get an understanding of their statistics, such as the mean, median, and range, and whether there are outliers present. If the residual analysis after the modeling suggests there may be some issues, having inspected the model variables will help the analyst understand potential root causes.

Figure 6.11 – Visualizing the distributions of the realinv and realdpi variables

When visualizing the relationship between realinv and realdpi, we can see a strong linear relationship, but also a potential serial correlation in the data as there appears to be a somewhat cyclical oscillation in the data, which becomes stronger toward the extreme values, seen in the upper right of the plot.

Figure 6.12 – Visualizing the relationship between the realinv and realdpi variables

We will analyze the potential serial correlation seen in the preceding plot after a few more steps. First, let us fit the input variable and coefficient to the model:

ols_model = sm.OLS(df_mod['realdpi'], df_mod[['const','realinv']])
compiled_model = ols_model.fit()

Next, we will want to print out a summary of the model performance so we can begin to gauge the significance of the terms involved:

print(compiled_model.summary())

Referring to the results in Figure 6*.13*, we can see that the 95% confidence interval for neither the intercept, const, nor the input variable, realinv, contains zero. Therefore, in addition to the significant p-values for these variables, we can conclude they are significant contributors to the target at the coefficients provided. Now that we have confirmed there is statistical significance for both the intercept and the input variable and their coefficients, we want to know the level of correlation to the target they represent. We can see the R-squared statistic is 0.944. Because the two variables are the constant and the input variable, this R-squared statistic explains only the input variable.

R-squared versus adjusted r-squared

For multivariate regression, we would look at the adjusted r-squared value, which we can also see is the same – in the univariate/simple regression case – as the r-squared value.

The correlation of determination – also called goodness of fit – of 0.944 means real gross private domestic investment explains 94.4% of the variance in real private disposable income.

We can see based on the table that the intercept and the realinv variable are both significant in predicting the target with very low p-values. We can also see that neither of the 95% confidence intervals contains 0, which backs up the relevancy of their p-values. However, the confidence interval for the constant (intercept) suggests there may be a risk of uncertainty in the model and that more variables may be needed to reduce that uncertainty and improve model performance. Stated differently, we could say a higher level of uncertainty in the constant indicates the model has variance left to be explained and that the current model is overly biased.

It is important to acknowledge that based on the fact that data was observed over a 50-year period and random sampling was not performed, it is possible the residuals will have a serial correlation. We observe a possibility of serial correlation in the Durbin-Watson test statistic of 0.095, which suggests the residuals exhibit positive autocorrelation. The Durbin-Watson statistic tests whether there is autocorrelation at the first time lag. This means the Durbin-Watson tests whether the change in values between each data point is correlated with the value of the previous data point. If that correlation exists, it is considered lag-one autocorrelation.

Durbin-Watson test statistic

As a rule of thumb, a Durbin-Watson test statistic below roughly 2.0 (many consider 1.5 to 2.0 to be reasonable) is considered a flag for positive autocorrelation, while a value above roughly 2.0 (many consider 2.0 to 2.5 to be reasonable) indicates possible negative autocorrelation. Procedurally, a table lookup is required to identify the critical values against which the test statistic should be measured. The process follows the same steps for any hypothesis test with respect to comparing the test statistic against the critical value. The Durbin-Watson test is typically interpreted as a one-tailed test as inference from a two-tailed test is not particularly useful. A version of the Durbin-Watson table can be found at https://www.real-statistics.com/statistics-tables/durbin-watson-table/. This table produces the critical values for positive autocorrelation. To find the critical values for negative autocorrelation, the positive critical values can be subtracted from 4.

Although we have a Durbin-Watson statistic that suggests serial correlation may be present in the data, we will confirm significance by comparing the Durbin-Watson statistic to its corresponding positive autocorrelation table lookup using the table found at the preceding link. We have n=203 samples in our dataset but will use n=200 on the table lookup since this value is likely accurate enough to assess, and 203 does not exist in the table. At the 0.05 level of significance, which is used by default with the Durbin-Watson statistic produced in statsmodels ’ OLS regression, we find the bounds for the k=1 input variable to be [1.758, 1.779]. A value within this range should be interpreted as inconclusive. A value less than the lower bound indicates the presence of enough evidence to reject the null hypothesis and thus conclude there is statistically significant positive autocorrelation. A value greater than the upper bound indicates there is not enough evidence to reject the null hypothesis and thus there is no autocorrelation. Based on the results of our model, we can conclude with a 95% level of confidence that there is evidence of positive serial correlation in our residuals.

Figure 6.13 – OLS regression model output for realdpi

At this point, an analyst may want to consider addressing the serial correlation before moving forward. However, for the purpose of following the process of end-to-end model validation, we will move forward to the next steps.

Diagnostic plots for analyzing model errors

Section titled “Diagnostic plots for analyzing model errors”

As mentioned,, where in regression, is the predicted mean for given and is the error term – also called the residual term, which is calculated as the observed value for a data point minus the predicted value for that data point. The residuals in least squares linear regression must approximate a normal distribution centered around the mean with a standard deviation. The method for deriving the residuals for a fitted model is to subtract the predicted value from the actual value for each observation. Four common visualizations for inspecting the fit of a least squares regression model are as follows:

  • Residuals versus fitted plots, used to inspect the requirement of a linear relationship between the input and target variables
  • Quantile plots, used to inspect the assumption of residuals being normally distributed
  • Scale-location plots, used to inspect the assumption of homoscedasticity, or the homogenous distribution of variation
  • Residuals versus leverage influence plots, which help identify the impact outliers may have on model fit

To produce these plots, we can use the following Python code implementation:

model_residuals = compiled_model.resid
fitted_value = compiled_model.fittedvalues
standardized_residuals = compiled_model.resid_pearson # Residuals, normalized to have unit variance.
sqrt_standardized_residuals = np.sqrt(np.abs(compiled_model.get_influence().resid_studentized_internal))
influence = compiled_model.get_influence()
leverage = influence.hat_matrix_diag
cooks_distance = compiled_model.get_influence().cooks_distance[0]
fig, ax = plt.subplots(2, 2, figsize=(10,8))
# Residuals vs. Fitted
ax[0, 0].set_xlabel('Fitted Values')
ax[0, 0].set_ylabel('Residuals')
ax[0, 0].set_title('Residuals vs. Fitted')
locally_weighted_line1 = lowess(model_residuals, fitted_value)
sns.scatterplot(x=fitted_value, y=model_residuals, ax=ax[0, 0])
ax[0, 0].axhline(y=0, color='grey', linestyle='--')
ax[0,0].plot(locally_weighted_line1[:,0], locally_weighted_line1[:,1], color = 'red')
# Normal Q-Q
ax[0, 1].set_title('Normal Q-Q')
sm.qqplot(model_residuals, fit=True, line='45',ax=ax[0, 1], c='blue')
# Scale-Location
ax[1, 0].set_xlabel('Fitted Values')
ax[1, 0].set_ylabel('Square Root of Standardized Residuals')
ax[1, 0].set_title('Scale-Location')
locally_weighted_line2 = lowess(sqrt_standardized_residuals, fitted_value)
sns.scatterplot(x=fitted_value, y=sqrt_standardized_residuals, ax=ax[1, 0])
ax[1,0].plot(locally_weighted_line2[:,0], locally_weighted_line2[:,1], color = 'red')
# Residual vs. Leverage Influence
ax[1, 1].set_xlabel('Leverage')
ax[1, 1].set_ylabel('Standardized Residuals')
ax[1, 1].set_title('Residuals vs. Leverage Influence')
locally_weighted_line3 = lowess(standardized_residuals, leverage)
sns.scatterplot(x=leverage, y=standardized_residuals, ax=ax[1, 1])
ax[1, 1].plot(locally_weighted_line3[:,0], locally_weighted_line3[:,1], color = 'red')
ax[1, 1].axhline(y=0, color='grey', linestyle='--')
ax[1, 1].axhline(3, color='orange', linestyle='--', label='Outlier Demarkation')
ax[1, 1].axhline(-3, color='orange', linestyle='--')
ax[1, 1].legend(loc='upper right')
leverages = []
for i in range(len(cooks_distance)):
if cooks_distance[i] > 0.5:
leverages.append(leverage[i])
ax[1, 1].annotate(str(i) + " Cook's D > 0.5",xy=(leverage[i], standardized_residuals[i]))
if leverages:
ax[1, 1].axvline(min(leverages), color='red', linestyle='--', label="Cook's Distance")
for i in range(len(standardized_residuals)):
if standardized_residuals[i] > 3 or standardized_residuals[i] < -3:
ax[1, 1].annotate(i,xy=(leverage[i], standardized_residuals[i]))
fig.tight_layout()

The following output contains four common diagnostic plots.

Figure 6.14 – Linear regression diagnostic plots

One requirement of least squares regression is a linear relationship between the input and target variables. Suffice it to say a strongly correlated relationship exists between the input and target variables. This plot helps the analyst assess the linearity between the two.

We should expect the fitted line – representing the model – to be horizontal, representing the strength of the linear relationship between the input and target variable across all data points. The residuals should be roughly evenly spread around the line in reasonable proximity. If these attributes cannot be confirmed, a non-linear relationship may exist between the two variables. A transformation of at least one of the variables – if the variable is skewed – may help resolve this type of issue. However, it could also be that a non-parametric model is more appropriate, which is often the case when categorical features – or encoded categorical features – are present.

Our model produced a plot that does not display evenly spread residuals forming around a horizontal line. Rather, the line is concaved down, which suggests a polynomial or non-parametric regression may be more appropriate. Additionally, the residuals form a pattern toward the right end of the line that suggests there may be some serial correlation in the data as it exhibits some sinusoidal behavior. We were able to identify the presence of serial correlation using the Durbin-Watson statistic. This is likely due to the fact the data was not randomly sampled and was collected over a long period of time.

Assessment of normality for the QQ plot follows the same procedure as assessing normality using the QQ plot in Chapter 4*, Parametric Tests*. The primary purpose of this plot is to assess the required assumption of the normal distribution of errors. Minor deviation of the residuals from the 45-degree line in the plot is normal, but extreme skewness or deviation from the line may indicate a poor fit. Such a scenario could indicate poor statistical power. In the event of skewness, data transformation – such as a log transformation – could be useful to resolve the issue. Dropping outliers may be another suitable solution. However, rather than dropping outliers outright, it is advisable to ensure there was not an error in data handling that could be resolved to make the outliers conform.

In the QQ plot for our model’s residuals, we can see some moderate left-side skewness and extreme right-side skewness, which suggests the three values in the right tail could be extreme outliers. Aside from this, we can assume that overall, the residual error is approximately normally distributed.

The scale-location plot of the square root of the standardized residuals helps analysts use visual inspection to determine whether there is homoscedasticity – or non-constant variance – of the residuals, which is required for a least squares regression model. The plot visualizes the square root of the absolute value of the standardized residuals. Analyzing homoscedasticity can sometimes be useful for identifying potential issues related to sample independence, another requirement of least-squares regression. However, the Durbin-Watson test should be given more weight for testing this assumption.

In assessing our model, we can see the line has some deviation from being perfectly horizontal. Additionally, the residuals, while seeming to have a large amount of constant variance, nonetheless at times exhibit patterns, which conflicts with the behavior of homoscedasticity. Furthermore, there appear to be three very notable outliers. Based on this information, we can reasonably assume a risk of heteroscedasticity – or constant variance – exists within the model’s residuals.

Assessing the residuals versus leverage influence is another approach to assessing model fit. In addition to gauging leverage, this plot also shows when Cook’s distance is beyond a reasonable level.

Leverage is used to identify the distance of an individual point from all other points. High leverage for a residual likely means the corresponding data point is an outlier strongly influencing the model to fit less approximately to the overall data and instead give more weight to that specific value. Residuals should be between -2 and 2 to not be considered potential outliers. Values between +/-2.5 to 3 suggest data points are extreme outliers. Overall, this plot is useful for separating outliers that have no significant negative impact on the model from the ones that do.

Cook’s distance is a measurement that uses both an observation’s leverage and its residual value. As the leverage is higher, its calculated Cook’s distance is higher. In general, a Cook’s distance value greater than 0.5 means a residual has leverage that is negatively impacting the model through over-representation – essentially, an outlier. Cook’s distance is included in the code and flags the residuals that have distances greater than 0.5. Cook’s distance is particularly useful because removing outliers may not have a significant impact on the model. However, if the outlier has a high Cook’s distance value, that is a strong indication that resolving the outlier will benefit the model. Cook’s distance is calculated for each data point by removing it from the model and calculating the difference in error divided by the mean squared error multiplied by the number of model coefficients plus one. Its formulation follows:

where is the j th estimate of the response and is the value of the j th fitted value with the i th value removed. p is the number of coefficients in the model and is the variance of the residuals for all observations, including those removed, also called the squared error.

In the plot for our model, we can observe three extreme outliers. However, we can also see no value of Cook’s distance is greater than 0.5. As with the scale-location plot, the standardized residuals should follow even distribution around a smoothed line that is horizontal, which indicates a constant variance. We can see from our model’s output that this is not the case.

Alone, each plot can be considered enough to negate the validity of a model. However, it is useful to consider all plots since a model may still be useful if there is only some deviance from expectations in the diagnostic plots. Some approaches to resolving issues with residuals are as follows:

  • Investigating and resolving any data collection issues that may produce outliers or data inconsistencies
  • Removing outliers outright
  • Improving the sampling approach using methods such as using random or stratified sampling
  • Performing data transformations, such as a log or square root transformation
  • Including additional input variables that can help explain the target variable or any serial correlation that may be present

If uncertain of the presence of serial correlation in the residuals, a useful next step is to analyze a Partial Autocorrelation Function (PACF) plot to assess whether serial correlation exists in the model at a significant level, which could explain issues with the model’s residuals.

ACF and PACF

The PACF provides a partial correlation between the value of a point and previous points, called lags, by controlling for the lags between. Controlling the lags between is where the term “partial” comes from. If a specific point at lag zero in a dataset is correlated strongly with the value of the third lagging point, there would be a significant correlation with a lag of 3, but not a lag of 2 or 1. In time-series modeling, the PACF is used to directly derive the autoregressive orders, denoted as AR(n) where n is the lag. The Autocorrelation Function (ACF), which is used for determining moving average orders, denoted as MA(n), considers the correlation between data points at lag zero and all previous lagging points without controlling for the relationships between them. Stated alternatively, autocorrelation in an ACF plot at lag 3 will provide autocorrelation across points 0 through 3 whereas correlation in a PACF plot at lag 3 will provide autocorrelation only between point 0 and point 3, excluding the impact of values at lags 1 and 2.

We can execute the following code to generate the PACF plot with a 95% confidence interval using the most recent 50 data points, ordered by index positioning – in this case, by date:

from statsmodels.graphics.tsaplots import plot_pacf
plot_pacf(compiled_model.resid, alpha=0.05, lags=50);

Figure 6.15 – Partial autocorrelation plot for the model residuals

In the PACF plot in Figure 6*.15*, we see very strong and significant correlations at lags 0 and 1. We observe a low level of significant correlation (approximately -0.25) for lags 2 and 36, extending beyond the 95% confidence interval. What this tells us is we might be better off modeling the dataset with a first-order autoregressive (AR(1)) time-series model than a linear regression model.

Answering regression questions with a least squares method when there is a presence of significant autocorrelation creates inherit risk. There are methods to adjust the results of a model when there is autocorrelation detected, such as taking a first-order difference – or another type of low-pass filter - or applying the Cochrane-Orcutt, Hildreth-Lu, or Yule-Walker adjustments. However, it is ideal to perform a time-series analysis, as the results of that type of modeling are more robust to time-dependent patterns. We will introduce time series in Chapter 10, Introduction to Time Series, where we discuss simple and complex methods for approximating time series to produce more useful results.

Let us consider a first-order difference of the data. Regarding Figure 6*.16*, we first look at the ACF plot and original data for the input variable, realdpi. We can see an exponentially growing line (original data) that displays an exponentially dampening ACF plot. This ACF behavior is typical for trended data that often benefits from first-order differencing. The low autoregressive ordering identified in the PACF indicates this may be sufficient for a regression model to proceed. Had the ACF shown different behavior, such as sinusoidal (seasonal) autocorrelation, or the PACF shown more partial autocorrelation, we would have evidence against a first-order difference being a sufficient solution for resolving serial correlation and proceeding with least squares regression. ACFs and PACFs for least squares regression should ideally have no significantly correlated lags. However, when the ACF exhibits this behavior and the PACF shows no significance, or when the level of correlation is very low, regression may perform well. It is preferable to see no patterns or peaks in either plot. Regardless, in either case, model error should be assessed, in addition to the autocorrelation of the residuals, to determine if least squares regression performs as needed.

Using the diff() numpy function, we take a first-order, low-pass difference and plot the ACFs, PACFs, and line plots for the original and differenced data. We can see a significant reduction in autocorrelation as a result. As an aside, the post-differencing autocorrelation suggests an autoregressive moving average (ARMA) model of AR order 1 and MA order 1 may be better suited than least-squares regression. However, we will ignore this for the chapter and continue:

from statsmodels.graphics.tsaplots import plot_acf
from statsmodels.graphics.tsaplots import plot_pacf
fig, ax = plt.subplots(2,3, figsize=(15,10))
plot_acf(df_mod['realdpi'], alpha=0.05, lags=50, ax=ax[0,0])
ax[0,0].set_title('Original ACF')
plot_pacf(df_mod['realdpi'], alpha=0.05, lags=50, ax=ax[0,1])
ax[0,1].set_title('Original PACF')
ax[0,2].set_title('Original Data')
ax[0,2].plot(df_mod['realdpi'])
plot_acf(np.diff(df_mod['realdpi'], n=1), alpha=0.05, lags=50, ax=ax[1,0])
ax[1,0].set_title('Once-Differenced ACF')
plot_pacf(np.diff(df_mod['realdpi'], n=1), alpha=0.05, lags=50, ax=ax[1,1])
ax[1,1].set_title('Once-Differenced PACF')
ax[1,2].set_title('Once-Differenced Data')
ax[1,2].plot(np.diff(df_mod['realdpi'], n=1))

We get the following result:

Figure 6.16 – Plots for the realinv variable before and after first-order differencing

This gives us data that we may more suitably model using regression. However, when using differencing as a method to resolve serial correlation in a least squares regression model, we must also differentiate the input variable. Observe the input variable, realinv, before and after transformation. Here in Figure 6*.17*, we can see similar behavior as with realdpi:

Figure 6.17 – Plots for the realdpi variable before and after first-order differencing

We can now build a new regression model using the differenced data. It is important to note first-order differencing removed one data point from the dataset so one value must also be removed from the constant in the design matrix:

ols_model_1diff = sm.OLS(np.diff(df_mod['realdpi'], n=1), pd.concat([df_mod['const'].iloc[:-1], pd.Series(np.diff(df_mod['realinv'], n=1))], axis=1))
compiled_model_1diff = ols_model_1diff.fit()

The output of this model is notably different. We now see an r-squared value of 0.045. Looking at the differenced data, we can see there is a different variance in the differenced data for disposable income than there is for investment. This means that although the realinv variable is useful for predicting realdpi as it appears significant, there is a lot more influencing real disposable gross personal income. We observe that the new Durbin-Watson test statistic is now 2.487. Using the critical values from the table lookup earlier, [1.758, 1.779], we see the Durbin-Watson statistic is now above the upper limit. To check whether there is negative autocorrelation, we subtract these values from 4 to find the new limit range [2.221, 2.242]. Because the new statistic, 2.487, is greater than 2.221, we can confirm there is now negative autocorrelation in the model’s residuals. We can see based on the PACF plot, as well as the proximity to the critical value range, the autocorrelation is much less significant than before, but still present. It could be argued the autocorrelation of the residuals is now small enough to be considered resolved, however; as noted earlier, a Durbin-Watson statistic less than 2.5 can be considered normal. Nonetheless, least-squares regression remains risky compared to time-series modeling to generate our predictions. We begin an in-depth overview of this topic in Chapter 10*, Introduction to* Time Series.

Let us assume, however, that for the sake of moving through the steps of regression model validation, we have no autocorrelation in our data. The next step will be to test our model.

Assuming an analyst has developed a model that produces strong results and appears useful based on the previously mentioned plots, the next step is to test the model. One conventional approach is to perform a train-and-test split on the data used for the original model where we fit all data. In the following code, we run a split with the train dataset having 75% of the data and the test dataset having 25%. The purpose is to assess whether there is a significant difference in performance between the two, as well as compared to the original model. The process follows the same steps as earlier. Acceptable differences are up to the analyst to decide, but in addition to assessing the differences between the metrics already discussed, the analyst should also note the coefficients for the slope and input variable, as these will be used to predict the target.

Here, we split the data. We use the shuffle argument to randomly shuffle the data so that if there is some order to the data, such as it being ordered by time, the data will be split randomly:

from sklearn.model_selection import train_test_split
train, test = train_test_split(df_mod, train_size=0.75, shuffle=True)

Now, we build a model using the training data:

ols_model_train = sm.OLS(train['realdpi'], train[['const','realinv']])
compiled_model_train = ols_model_train.fit()
print(compiled_model_train.summary())

Finally, we build a model using the testing data:

ols_model_test = sm.OLS(test['realdpi'], test[['const','realinv']])
compiled_model_test = ols_model_test.fit()
print(compiled_model_test.summary())

The idea here is that the two models should produce similar results on two different partitions of the data.

Another method for validating the model is to compare a metric against a naïve model. Let us use the mean absolute error (MAE). With this model metric, we could compare a naïve linear model’s errors where the error is each data point minus the average to the model’s predictions. A useful model MAE would need to be lower than the naïve model’s MAE. Here, we use the fit model to predict the inputs, then compare the model’s predictions to the naïve model’s predictions:

Below we can observe the MAE from the trained model:

438.5872081797031
from sklearn.metrics import mean_absolute_error
mae = mean_absolute_error(train['realdpi'], compiled_model_train.predict(train[['const','realinv']]))
mae

Here we can see the MAE from the naïve model, which makes no assumptions other than that the mean will continue to hold the true values:

import numpy as np
errors = []
for i in range(len(train)):
errors.append(abs(train['realdpi'].iloc[i] - train['realdpi'].mean()))
np.mean(errors)
#2065.440235457064

We can see the model compares favorably against the naïve model.

Another method that is popular to use is testing on a holdout dataset. For this, a model is constructed and trained on the training data. Then, using that model, we apply it to the test data. We would then compare the metric to that of the training data. Using the training model’s MAE of 438, we compare it to the following:

408.0253171549187
mae_test = mean_absolute_error(test['realdpi'], compiled_model_train.predict(test[['const','realinv']]))
mae_test

We can see that the error is lower for the test data than for the train data. However, since the train and test data are assumed to have different values and thus means, we should reassess that the naïve model still produces a higher MAE for the test data:

errors = []
for i in range(len(test)):
errors.append(abs(test['realdpi'].iloc[i] - test['realdpi'].mean()))
np.mean(errors)
#1945.5873125720873

Here we can see the model does provide better MAE than the naïve model at approximately the same rate on the test data as on the train data. Therefore, we expect that the linear regression model is better than the naïve model.

In this chapter, we discussed an overview of simple linear regression between one explanatory variable and one response variable. The topics we covered include the following:

  • The OLS method for simple linear regression
  • Coefficients of correlation and determination and their calculations and significance
  • The assumptions required for least squares regression
  • Methods of analysis for model and parameter significance
  • Model validation

We looked closely at the concept of the square of error and how the sum of squared errors is meaningful for building and validating linear regression models. Then, we walked through the four pertinent assumptions required to make linear regression a stable solution. After, we provided an overview of four diagnostic plots and their interpretations with respect to assessing the presence of various issues related to heteroscedasticity, linearity, outliers, and serial correlation. We then walked through an example of using the ACF and PACF to assess serial correlation and an example of using first-order differencing to remove serial correlation constraints from data and build an OLS model using the differenced data. Finally, we provided methods for testing and validating least square regression models.

In the next chapter, we will extend this concept to include more than one explanatory variable, a technique called multiple linear regression. We will also discuss various topics related to multiple linear regression, such as variable selection and regularization.