Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Multiple Linear Regression

Multiple Linear Regression

In the previous article, we explored simple linear regression, which helped us understand how one feature (independent variable) affects a target (dependent variable). However, real-world problems are often more complex. For example, when predicting house prices, we cannot look only at area; we also need to consider the number of bedrooms, location, age of the house, and other factors. At this point, we need Multiple Linear Regression。

Simply put, multiple linear regression is a natural extension of simple linear regression; it allows us to analyze the simultaneous influence ofmultiple independent variableson a dependent variable. This article will take you from scratch to a comprehensive understanding of the core concepts, mathematical principles, implementation methods, and practical applications of multiple linear regression.


I. What Is Multiple Linear Regression?

1.1 Core Concepts

Multiple linear regression is a statistical method used to establish a linear relationship betweenmultiple independent variables(also called features or explanatory variables) anda continuous dependent variable(also called the target or response variable).

A vivid analogy: Imagine you are a chef adjusting the taste of a soup (the target). Simple linear regression is like adjusting saltiness only by the amount of salt. Multiple linear regression is like simultaneously controlling the amounts of salt, sugar, chili, soy sauce, and other seasonings (features) to collectively determine the final flavor. Multiple regression lets you analyze the specific contribution of each seasoning to the taste.

1.2 Model Formula

The mathematical expression of the multiple linear regression model is as follows:

y = β₀ + β₁x₁ + β₂x₂ + ... + βₙxₙ + ε

Let's break down each part of this formula:

sign before positive numbers Name Meaning
y Dependent variable The target value we want to predict (e.g., house price).
x₁, x₂, ..., xₙ Independent variables Features used to predict y (e.g., area, number of bedrooms, age of the house).
β₀ Intercept term When all independent variables are 0,y the baseline predicted value of .
β₁, β₂, ..., βₙ Regression coefficients The weight of each independent variable xᵢ . It means:with other features held constant,xᵢ for every 1-unit increase in ,y changes on average by βᵢ units. This is the core of multiple regression analysis.
ε Error term Random fluctuations the model cannot explain (e.g., measurement error, unknown factors).

Example of interpreting the formula: Suppose our model for predicting house price (y) is: 房价 = 50000 + 3000 * 面积 + 10000 * 卧室数 - 2000 * 房龄


II. How to "Train" a Multiple Linear Regression Model?

"Training" a model essentially means finding an optimal set of regression coefficients based on our existing data (β₀, β₁, ..., βₙ)so that the model's predicted values are as close as possible to the true values. This process is usually done through the least squares method .

2.1 Objective: Minimize the Loss Function

We use The residual sum of squares is used as the loss function to measure the model's prediction error. RSS = Σ(yᵢ - ŷᵢ)² Whereyᵢ is the i -th true value,ŷᵢ is the model's predicted value for the i -th sample.

The training objective is to find a set of coefficients that minimizes the value of RSS.

2.2 Solution Process (Matrix Form)

When there are many features, matrix operations can represent and solve the model more efficiently. The model can be written as: Y = Xβ + ε Where:

By derivation using the least squares method, the optimal solution (closed-form solution) for the coefficients β can be obtained as: β = (XᵀX)⁻¹XᵀY This formula is theoretically perfect, but in actual programming we usually use numerical optimization libraries (such as scikit-learn) to compute efficiently and stably; it automatically handles complex operations such as matrix inversion.


III. Implementing Multiple Linear Regression with Python

Let's use a complete example with the popular machine learning library scikit-learn to build a multiple linear regression model.

3.1 Environment Setup and Data Loading

First, make sure the necessary libraries are installed, and load a sample dataset.

Example

Import the necessary libraries

import

numpy

as

np

import

pandas

as

pd

import

matplotlib.

pyplot

as

plt

from

sklearn.

model_selection

import

train_test_split

from

sklearn.

linear_model

import

LinearRegression

from

sklearn.

metrics

import

mean_squared_error

,

r2_score

from

sklearn.

datasets

import

fetch_california_housing

A classic multivariate dataset

Load the California housing dataset

california

=

fetch_california_housing

(

)

df

=

pd.

DataFrame

(

california.

data

,

columns

=

california.

feature_names

)

df

[

'MedHouseVal'

]

=

california.

target

Add the target column: median house price

print

(

"Dataset shape:"

,

df.

shape

)

print

(

"\nFirst 5 rows of data:"

)

print

(

df.

head

(

)

)

print

(

"\nFeature descriptions:"

)

print

(

california.

DESCR

[

:

500

]

)

Print part of the description

3.2 Data Exploration and Preprocessing

Before modeling, it is essential to understand the basics of the data.

Example

1. View basic information about the data

print

(

df.

info

(

)

)

print

(

"\nBasic statistical description:"

)

print

(

df.

describe

(

)

)

2. Split features (X) and target (y)

X

=

df.

drop

(

'MedHouseVal'

,

axis

=

1

)

Feature matrix: contains all columns except house price

y

=

df

[

'MedHouseVal'

]

Target vector: house price

3. Split into training and test sets (70% train, 30% test)

X_train

,

X_test

,

y_train

,

y_test

=

train_test_split

(

X

,

y

,

test_size

=

0.3

,

random_state

=

42

)

print

(

f

"\nNumber of training samples: {X_train.shape[0]}, number of test samples: {X_test.shape[0]}"

)

3.3 Creating, Training, and Evaluating the Model

Now we create a linear regression model, "fit" it with the training data, and evaluate its performance on the test set.

Example

1. Create a model instance

model

=

LinearRegression

(

)

2. Train the model (fit the data)

model.

fit

(

X_train

,

y_train

)

3. Make predictions with the trained model

y_train_pred

=

model.

predict

(

X_train

)

y_test_pred

=

model.

predict

(

X_test

)

4. Evaluate model performance

Mean squared error (MSE) — smaller is better

train_mse

=

mean_squared_error

(

y_train

,

y_train_pred

)

test_mse

=

mean_squared_error

(

y_test

,

y_test_pred

)

Coefficient of determination (R²) — closer to 1 is better, indicating stronger explanatory power

train_r2

=

r2_score

(

y_train

,

y_train_pred

)

test_r2

=

r2_score

(

y_test

,

y_test_pred

)

print

(

"=== Model Performance Evaluation ==="

)

print

(

f

"Training set MSE: {train_mse:.4f}, R²: {train_r2:.4f}"

)

print

(

f

"Test set MSE: {test_mse:.4f}, R²: {test_r2:.4f}"

)

5. View the learned model parameters

print

(

"\n=== Model Parameters ==="

)

print

(

f

"Intercept (β₀): {model.intercept_:.4f}"

)

print

(

"Regression coefficients (β₁, β₂, ...):"

)

for

feature

,

coef

in

zip

(

X.

columns

,

model.

coef_

)

:

   

print

(

f

"  {feature}: {coef:.4f}"

)

3.4 Interpreting Results and Visualization

Understand the meaning of the coefficients and evaluation metrics.

Example

Visualization: Actual vs Predicted (test set)

plt.

figure

(

figsize

=

(

8

,

6

)

)

plt.

scatter

(

y_test

,

y_test_pred

,

alpha

=

0.5

)

plt.

plot

(

[

y.

min

(

)

,

y.

max

(

)

]

,

[

y.

min

(

)

,

y.

max

(

)

]

,

'r--'

,

lw

=

2

)

Draw the ideal diagonal line

plt.

xlabel

(

'Actual House Price'

)

plt.

ylabel

(

'Predicted House Price'

)

plt.

title

(

'Multiple Linear Regression: Actual vs Predicted (Test Set)'

)

plt.

grid

(

True

,

linestyle

=

'--'

,

alpha

=

0.7

)

plt.

show

(

)

Visualization: Feature importance (approximated by the magnitude of the absolute coefficient values)

features

=

X.

columns

coefs

=

model.

coef_

plt.

figure

(

figsize

=

(

10

,

6

)

)

bars

=

plt.

barh

(

features

,

np.

abs

(

coefs

)

)

Use absolute values to compare the magnitude of influence

plt.

xlabel

(

'Absolute Regression Coefficient'

)

plt.

title

(

'Magnitude of Feature Influence on House Price (Based on Absolute Coefficient Values)'

)

Add value labels to the bar chart

for

bar

,

coef

in

zip

(

bars

,

coefs

)

:

    width

=

bar.

get_width

(

)

    plt.

text

(

width +

0.01

,

bar.

get_y

(

)

get_height

(

)

/

2

,

f

'{coef:.4f}'

,

va

=

'center'

)

plt.

grid

(

True

,

axis

=

'x'

,

linestyle

=

'--'

,

alpha

=

0.7

)

plt.

tight_layout

(

)

plt.

show

(

)


IV. Considerations and Challenges of Multiple Linear Regression

4.1 Key Assumptions

The validity of the linear regression model rests on several statistical assumptions:

  1. Linear relationship: There is a linear relationship between the independent and dependent variables.
  2. Independence: Observations are independent of each other.
  3. Homoscedasticity: The variance of the error term remains constant across all observations.
  4. Normality: The error term follows a normal distribution.
  5. No multicollinearity: There should be no high correlation among the independent variables.

4.2 Common Challenges and Responses

Challenges Description Possible consequences Response methods
Multicollinearity Features are highly correlated with each other. Coefficient estimates are unstable, making it difficult to interpret the influence of individual features. 1. Use a correlation matrix to check for and remove highly correlated features.
 2. 使用主成分分析(PCA)降维。       

 3. 使用正则化方法(如岭回归)。 |

| Overfitting | The model is too complex, fitting the training data noise perfectly and performing poorly on the test set. | Test set error is much larger than training set error. | 1. Collect more data.
2. Use fewer features (feature selection).
3. Use regularization. | | Nonlinear relationship | The relationship in the data is inherently nonlinear. | The model's predictive ability is poor, with a low R² value. | 1. Transform the features (e.g., polynomial features, logarithmic transformation).
2. Use a nonlinear model (e.g., decision tree, neural network). |


V. Hands-On Exercises: Reinforce Your Understanding

Now it's your turn to practice! Please complete the following exercises in order to reinforce your understanding of multiple linear regression.

Exercise 1: Interpret the Model

Using the model coefficients output by the code above, answer the following questions:

  1. Which feature has thepositive impactgreatest? (Judge based on the coefficient value)
  2. Which feature has anegative impact?
  3. How to interpret AveRooms(average number of rooms)'s coefficient? Please describe it in a complete sentence.

Exercise 2: Diagnose Multicollinearity

  1. Compute features X the correlation matrix of (df.corr())。
  2. Find feature pairs with an absolute correlation greater than 0.7. They may have multicollinearity.
  3. (Optional) Try removing one of the highly correlated features from the model, retrain, and observe how the coefficients and R² score change.

Exercise 3: Try a New Dataset

  1. From the sklearn.datasets load another regression dataset from , such as load_diabetes(the diabetes dataset).
  2. Repeat the modeling steps in this article: data exploration, splitting, training, evaluation, and visualization.
  3. Compare the model's performance on the two datasets and think about possible reasons.