GNGiseldo Neo and Alana NeoBooks
Linear Regression with Python4 / 19

Linear Regression in Statistics and ML

Linear regression is a technique used in both statistics and machine learning, applied in distinct yet complementary ways in each field. This chapter explores how linear regression is used and adapted across different contexts, highlighting its capabilities, limitations, and integration into more advanced methods.

3.1 Statistical Concepts

In statistics, linear regression is used to model the relationship between a dependent variable and one or more independent variables, as well as to make statistical inferences about the underlying relationships among them and perform statistical prediction of future values (Montgomery, Peck, and Vining 2021).

Statistical inference refers to the branch of statistics concerned with analyzing, interpreting, and describing data collected from a sample in order to make generalizations about a larger population. This process involves using methods and techniques that allow for point or interval estimation and hypothesis testing regarding population parameters based on sample information.

Statistical inference is grounded in probability theory, which makes it possible to handle the variability and uncertainty present in data. The main inference techniques include point estimation, interval estimation, and hypothesis testing, which are employed to make predictions or draw conclusions about population characteristics that are not directly observed.

The validity of statistical inferences depends on several factors, such as sample size, sampling method, and the precision of the statistical tools used. Therefore, when making inferences, it is necessary to consider potential errors and biases that may affect the results and conclusions obtained.

Statistical prediction, on the other hand, refers to the process of estimating or forecasting future values of a variable based on historical data and mathematical or statistical models. This procedure involves analyzing patterns and trends in the observed data and applying specific techniques, such as linear regression, time series analysis, and machine learning models, among others.

Predictive models are built through quantitative methods that use available information to generate future scenarios. These models are verified and validated through evaluation processes that measure their accuracy and effectiveness. Predictability may be direct or inferred, depending on the nature of the data and the methodology employed.

Prediction is an essential component of decision-making in numerous fields, including economics, meteorology, public health, and business management. Thus, the primary goal of statistical prediction is to provide a rational basis for expectations about future events, enabling more appropriate and efficient planning.

Uses of Regression Inference: Through hypothesis testing, confidence intervals, and analysis of variance, statisticians can determine the significance of relationships between variables and the contribution of each independent variable to the model (Weisberg 2013).

Prediction: Linear regression is widely used to predict continuous values across various fields, such as economics, biology, and the social sciences (Kutner et al. 2004).

Associated Statistical Methods

Residual Normality Analysis

Analyzing residuals (or errors) is essential for verifying model assumptions, such as homoscedasticity and normality of the errors.

Normality of residuals is one of the assumptions of linear regression. Residuals are the differences between the observed values and the values predicted by the regression model. The formula for calculating a residual is shown below:

Residual=yi−y^i\textit{Residual} = y_i - \hat{y}_i

where:

  • yiy_i is the observed value of the dependent variable;

  • y^i\hat{y}_i is the value predicted by the regression model.

To inspect the residuals, we can use two types of plots:

  • A histogram of the residuals

  • A Q-Q plot of the residuals

Let us first create a regression model and display its errors. We will use all the data for training rather than splitting the dataset into training and test sets, since our goal here is not to evaluate how well this model generalizes to new data.

import numpy as np
from sklearn.linear_model import LinearRegression

# Generate random data
np.random.seed(42)
x = np.random.rand(100)
y = 2 * x + 1 + np.random.normal(0, 0.2, 100)

# Train the model
model = LinearRegression()
model.fit(x.reshape(-1, 1), y)

# Predictions and errors
errors = y - model.predict(x.reshape(-1, 1))
errors

The output is an array containing the error for each observation.

array([ 0.00883089, -0.0153981 ,  ....,  0.13233854])

Histogram of Residuals

A histogram can be used to assess the normality of the residuals. The following code generates a histogram plot of the residuals.

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sn
from sklearn.linear_model import LinearRegression

# Generate random data
np.random.seed(42)
x = np.random.rand(100)
y = 2 * x + 1 + np.random.normal(0, 0.2, 100)

# Train the model
model = LinearRegression()
model.fit(x.reshape(-1, 1), y)

# Predictions and errors
errors = y - model.predict(x.reshape(-1, 1))

# Display plot
sn.histplot(errors, bins=20, kde=True)
plt.xlabel('Errors')
plt.ylabel('Frequency')
plt.title('Histogram of Errors')
plt.show()

Console Output

Figure 3.1. Console Output

We can visually observe that the histogram of the residuals follows a distribution similar to the normal distribution.

Significance Tests: tt-tests and FF-tests are used to evaluate the significance of individual regression coefficients and of the model as a whole (Draper and Smith 1998).

Multicollinearity: The Variance Inflation Factor (VIF) is a common measure for identifying multicollinearity among independent variables (Gujarati and Porter 2012).

3.2 ML Concepts

In machine learning, linear regression is used both as a standalone model and as a building block in more complex methods. It is frequently the starting point for developing predictive models due to its simplicity and interpretability (Bishop 2006).

  • Regression Algorithms: Linear regression can be enhanced with regularization techniques, such as Lasso and Ridge, to address overfitting and multicollinearity (Hastie, Tibshirani, and Friedman 2009).

  • Learning Pipelines: Linear regression is often used in machine learning pipelines, where it is combined with feature selection, cross-validation, and hyperparameter tuning techniques (Kuhn and Johnson 2013).

Challenges and Advances

  • Scalability: In big data contexts, linear regression is adapted to process large volumes of data efficiently through distributed computing frameworks such as Apache Spark (Zaharia et al. 2016).

  • Explainability: The simplicity of linear regression makes it valuable for Explainable Artificial Intelligence (XAI), providing an interpretable baseline for comparison against more complex models (Rudin 2019).

  • Integration with Deep Learning: Although deep learning is generally associated with nonlinear problems, linear regression can be used in the output layers of neural networks to produce continuous predictions (Goodfellow, Bengio, and Courville 2016).

3.3 Calculating the Coefficients

Ordinary Least Squares (OLS) and Gradient Descent are two popular approaches for computing the coefficients of a regression model. While OLS is more closely associated with statistics, Gradient Descent is more closely associated with ML. Thanks to today’s abundant computing power, Gradient Descent has become a standard tool across major statistical and data science software ecosystems (such as Python and R). Below, we explore the differences between these two approaches.

3.3.1 Ordinary Least Squares (OLS)

  • Objective: OLS aims to find the coefficients that minimize the sum of squared residuals—that is, the squared differences between the observed values and the predicted values (Montgomery, Peck, and Vining 2021).

  • Method: It uses direct mathematical formulas that yield an analytical (closed-form) solution. For a multiple linear regression model, the coefficients are computed via matrix inversion:

    β=(XTX)−1XTy\beta = (X^TX)^{-1}X^Ty

    where XX is the matrix of independent variables and yy is the vector of the dependent variable (Kutner et al. 2005).

  • Requirements: Works well for small to medium-sized datasets where matrix inversion is computationally feasible. It assumes there are no severe multicollinearity issues and that the data fits in memory.

  • Efficiency: Fast and efficient for moderately sized problems thanks to its closed-form analytical solution.

  • Drawbacks: Does not scale well to very large datasets or a large number of variables due to the computational cost of matrix inversion (Hastie, Tibshirani, and Friedman 2009).

3.3.2 Gradient Descent

  • Objective: Finds the coefficients by iteratively minimizing the cost function, adjusting the coefficients in the direction of the negative gradient of the cost function (Bishop 2006).

  • Method: Starts with an initial set of coefficient values and updates them in small steps in the direction that most reduces the error. The coefficient update rule is given by:

    βj=βj−α∂J∂βj\beta_j = \beta_j - \alpha \frac{\partial J}{\partial \beta_j}

    where α\alpha is the learning rate and ∂J∂βj\frac{\partial J}{\partial \beta_j} is the gradient of the cost function with respect to βj\beta_j (Goodfellow, Bengio, and Courville 2016).

  • Requirements: Scalable to large datasets, as it can process one sample at a time (in Stochastic Gradient Descent) or the entire dataset at once (Batch Gradient Descent).

  • Flexibility: Can be easily adapted to include regularization (such as Lasso or Ridge) and handles large volumes of data and features effectively.

  • Drawbacks: Choosing an appropriate learning rate can be challenging, and convergence may be slow or get trapped in local minima for non-convex problems. It requires more tuning and experimentation (Ruder 2016).

The Ordinary Least Squares (OLS) regression method is commonly used in statistical software such as Stata, SPSS, and jamovi. On the other hand, Gradient Descent is more frequently employed in machine learning libraries, such as scikit-learn in Python, for optimizing regression models.

Summary

  • OLS is a direct method that provides an analytical solution to linear regression problems and is efficient for small to medium-sized datasets.

  • Gradient Descent is an iterative method that is more flexible and scalable for large datasets, though it may require tuning hyperparameters such as the learning rate.

In the following chapters, we will explore the OLS technique in greater detail for calculating regression coefficients.