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 * 房龄
β₀ = 50000: Theoretically, the baseline price of a "house" with area 0, bedrooms 0, and age 0.β₁ = 3000: With the number of bedrooms and age held constant, for each additional square meter of area, the house price rises by 3000 yuan on average.β₂ = 10000: With area and age held constant, one additional bedroom raises the price by 10000 yuan on average.β₃ = -2000: With area and number of bedrooms held constant, each additional year of age lowers the price by 2000 yuan on average.
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:
Yis a column vector containing all the target values.Xis the design matrix whose first column is usually all 1s (corresponding to the intercept termβ₀), and each subsequent column corresponds to a feature.βis a column vector containing all the regression coefficients.εis the error term vector.
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
(
"Dataset shape:"
,
df.
shape
)
(
"\nFirst 5 rows of data:"
)
(
df.
head
(
)
)
(
"\nFeature descriptions:"
)
(
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
(
df.
info
(
)
)
(
"\nBasic statistical description:"
)
(
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
)
(
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
)
(
"=== Model Performance Evaluation ==="
)
(
f
"Training set MSE: {train_mse:.4f}, R²: {train_r2:.4f}"
)
(
f
"Test set MSE: {test_mse:.4f}, R²: {test_r2:.4f}"
)
5. View the learned model parameters
(
"\n=== Model Parameters ==="
)
(
f
"Intercept (β₀): {model.intercept_:.4f}"
)
(
"Regression coefficients (β₁, β₂, ...):"
)
for
feature
,
coef
in
zip
(
X.
columns
,
model.
coef_
)
:
(
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
(
)
- bar.
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:
- Linear relationship: There is a linear relationship between the independent and dependent variables.
- Independence: Observations are independent of each other.
- Homoscedasticity: The variance of the error term remains constant across all observations.
- Normality: The error term follows a normal distribution.
- 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:
- Which feature has thepositive impactgreatest? (Judge based on the coefficient value)
- Which feature has anegative impact?
- How to interpret
AveRooms(average number of rooms)'s coefficient? Please describe it in a complete sentence.
Exercise 2: Diagnose Multicollinearity
- Compute features
Xthe correlation matrix of (df.corr())。 - Find feature pairs with an absolute correlation greater than 0.7. They may have multicollinearity.
- (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
- From the
sklearn.datasetsload another regression dataset from , such asload_diabetes(the diabetes dataset). - Repeat the modeling steps in this article: data exploration, splitting, training, evaluation, and visualization.
- Compare the model's performance on the two datasets and think about possible reasons.