This tutorial provides a comprehensive introduction to Multiple Linear Regression (MLR) using Python, a versatile programming language with powerful libraries for statistical analysis. MLR is a widely used statistical technique that models the relationship between a dependent variable and multiple independent variables. This tutorial guides you through the fundamental concepts of MLR, its applications, and practical implementation in Python using libraries like NumPy, pandas, and statsmodels.
Introduction
Multiple Linear Regression is a statistical method used to examine the relationship between a dependent variable and two or more independent variables. It extends simple linear regression, which studies the relationship between a dependent variable and a single independent variable. In MLR, the goal is to understand how multiple independent variables collectively influence the variation in the dependent variable.
Suppose you have a dataset with \(n\) observations and \(k\) independent variables. The matrix notation for the multiple linear regression model is as follows:
Matrix of Independent Variables (Design Matrix):
Let \(X\) be the design matrix, with dimensions \(n \times (k+1)\).
The first column of \(X\) is typically a column of ones, representing the intercept term.
The remaining columns correspond to the values of the independent variables for each observation.
The multiple linear regression model can be expressed in matrix notation as:
\[ Y = X\beta + \varepsilon \]
This equation captures the relationship between the dependent variable \(Y\), the design matrix \(X\), the coefficient vector \(\beta\), and the error vector \(\varepsilon\). The goal of regression analysis is to estimate the coefficients in \(\beta\) that minimize the sum of squared errors (least squares method). This estimation can be expressed in matrix form as:
\[ \hat{\beta} = (X^TX)^{-1}X^TY \]
where \(\hat{\beta}\) represents the estimated coefficients. Matrix notation provides a concise and efficient way to represent and solve regression problems, especially with multiple variables.
Multiple Linear Regression Analysis from Scratch
Below is an example of performing multiple regression from scratch in Python with four predictors, including summary statistics and R² values:
Code
import numpy as npimport pandas as pdfrom scipy import stats# Set seed for reproducibilitynp.random.seed(123)# Generate sample datan =100# Number of observationsX = np.random.normal(size=(n, 4)) # Four predictorsX = pd.DataFrame(X, columns=['X1', 'X2', 'X3', 'X4'])true_beta = np.array([2, 3, -1, 0.5, 2]) # True coefficients (intercept first)X_with_intercept = np.c_[np.ones(n), X] # Design matrix with intercepterror = np.random.normal(0, 2, n) # Error termy = X_with_intercept @ true_beta + error # Dependent variable# Calculate coefficients using normal equationXTX = X_with_intercept.T @ X_with_interceptbeta_hat = np.linalg.inv(XTX) @ X_with_intercept.T @ y# Calculate residuals and R-squaredy_hat = X_with_intercept @ beta_hatresiduals = y - y_hatSS_residual = np.sum(residuals**2)SS_total = np.sum((y - np.mean(y))**2)R_squared =1- (SS_residual / SS_total)# Calculate standard errors and p-valuesdf = n -len(beta_hat) # Degrees of freedomsigma_sq_hat = SS_residual / df # Residual variance estimatevar_cov = sigma_sq_hat * np.linalg.inv(XTX) # Variance-covariance matrixse = np.sqrt(np.diag(var_cov)) # Standard errorst_values = beta_hat / se # t-statisticsp_values =2* stats.t.sf(np.abs(t_values), df=df) # p-values# Create summary tablesummary_df = pd.DataFrame({'Estimate': np.round(beta_hat, 4),'Std.Error': np.round(se, 4),'t.value': np.round(t_values, 4),'p.value': np.where(p_values <0.001, '<0.001', np.round(p_values, 4))}, index=['(Intercept)', 'X1', 'X2', 'X3', 'X4'])# Display resultsprint("Multiple Regression Results from Scratch")print("="*40)print(summary_df)print(f"\nResidual standard error: {np.round(np.sqrt(sigma_sq_hat), 3)} on {df} degrees of freedom")print(f"Multiple R-squared: {np.round(R_squared, 4)}")
Multiple Linear Regression Analysis in Python
In this section, we explore how to perform MLR in Python using the statsmodels library, interpret the results, and visualize the findings. We will also cover model diagnostics, performance evaluation, and relative importance of predictors.
Check and Install Required Packages
Code
import importlib.utilimport sys# List of required packagespackages = ['numpy', 'pandas', 'statsmodels', 'scikit-learn', 'matplotlib', 'seaborn']# Check and install missing packages# Check and install missing packagesfor package in packages:ifnot importlib.util.find_spec(package):try:import pip pip.main(['install', package])exceptImportError:print(f"Failed to install {package}. Pip is not available.")
Code
import pandas as pdimport numpy as npimport statsmodels.api as smimport statsmodels.formula.api as smfimport matplotlib.pyplot as pltimport seaborn as snsfrom statsmodels.stats.outliers_influence import variance_inflation_factorfrom sklearn.metrics import r2_score
We aim to create an MLR model incorporating predictors such as DEM (Digital Elevation Model), Slope, MAT (Mean Annual Temperature), MAP (Mean Annual Precipitation), and NDVI (Normalized Difference Vegetation Index) to predict soil organic carbon (SOC).
Code
# Create a DataFrame with selected variablesdf = mf[['SOC', 'DEM', 'Slope', 'MAT', 'MAP', 'NDVI']]# Fit an MLR modelX = df[['DEM', 'Slope', 'MAT', 'MAP', 'NDVI']]X = sm.add_constant(X) # Add intercepty = df['SOC']mlr_01 = sm.OLS(y, X).fit()# Display summaryprint(mlr_01.summary())
Create a Regression Summary Table
The statsmodels library provides a detailed summary of the regression model. For a custom summary table, you can extract relevant statistics:
This tutorial provided a comprehensive overview of Multiple Linear Regression using Python, a powerful tool for modeling relationships between multiple variables. We covered data preparation, model building, and evaluation using statsmodels. By fitting MLR models, we interpreted coefficients to understand predictor impacts on the response variable. Diagnostic plots and statistical tests validated model assumptions.
MLR is crucial in fields like finance, economics, and social sciences, enabling informed predictions and insights into complex variable interactions. To further enhance your models, explore advanced topics like feature engineering, interaction terms, and regularization. This tutorial serves as a foundation for applying MLR to your datasets, uncovering patterns and relationships that drive meaningful insights.