Linear Regression (Linear Regression)
Linear Regression is one of the most fundamental and widely used algorithms in machine learning.
Linear Regression is the most basic machine learning algorithm used to predict continuous values. It assumes a linear relationship between the target variable y and the feature variable x, and attempts to find the best-fit line to describe this relationship.
y = w * x + b
Where:
-
yis the predicted value -
xis the feature variable -
wis the weight (slope) -
bis the bias (intercept)
The goal of linear regression is to find the optimal w and b, such that the predicted value y has the smallest error with respect to the true value. A commonly used error function is the Mean Squared Error (MSE):
MSE = 1/n * Σ(y_i - y_pred_i)^2
Where:
- y_i is the actual value.
- y_pred_i is the predicted value.
- n is the number of data points.
Our goal is to minimize the MSE by adjusting w and b.
How to Solve Linear Regression?
1. Least Squares Method
The least squares method is a commonly used approach for solving linear regression. It finds the optimal (w) and (b) by solving the following equations.
The goal of the least squares method is to minimize the Residual Sum of Squares (RSS), whose formula is:
[ \text{RSS} = \sum_{i=1}^n (y_i - \hat{y}_i)^2 ]
Where:
\( y_i \)is the actual value.\( \hat{y}_i \)is the predicted value, computed by the linear regression model\( \hat{y}_i = w x_i + b \).
By minimizing the RSS, we can obtain the following normal equations:
[ \begin{cases} w \sum_{i=1}^n x_i^2 + b \sum_{i=1}^n x_i = \sum_{i=1}^n x_i y_i \ w \sum_{i=1}^n x_i + b n = \sum_{i=1}^n y_i \end{cases} ]
Matrix Form
Write the normal equations in matrix form:
[ \begin{bmatrix} \sum_{i=1}^n x_i^2 & \sum_{i=1}^n x_i \ \sum_{i=1}^n x_i & n \end{bmatrix} \begin{bmatrix} w \ b \end{bmatrix} = \begin{bmatrix} \sum_{i=1}^n x_i y_i \ \sum_{i=1}^n y_i \end{bmatrix} ]
Solution Method
By solving the above matrix equation, we can obtain the optimal \( w \) and \( b \):
[ \begin{bmatrix} w \ b \end{bmatrix} = \begin{bmatrix} \sum_{i=1}^n x_i^2 & \sum_{i=1}^n x_i \ \sum_{i=1}^n x_i & n \end{bmatrix}^{-1} \begin{bmatrix} \sum_{i=1}^n x_i y_i \ \sum_{i=1}^n y_i \end{bmatrix} ]
2. Gradient Descent
The goal of gradient descent is to minimize the loss function \( J(w, b) \) . For linear regression problems, the Mean Squared Error (MSE) is typically used as the loss function:
[ J(w, b) = \frac{1}{2m} \sum_{i=1}^m (y_i - \hat{y}_i)^2 ]
Where:
\( m \)is the number of samples.\( y_i \)is the actual value.\( \hat{y}_i \)is the predicted value, computed by the linear regression model\( \hat{y}_i = w x_i + b \).
The gradient is the partial derivative of the loss function with respect to the parameters, indicating the direction of change of the loss function in the parameter space. For linear regression, the gradient is computed as follows:
[ \frac{\partial J}{\partial w} = -\frac{1}{m} \sum_{i=1}^m x_i (y_i - \hat{y}_i) ]
[ \frac{\partial J}{\partial b} = -\frac{1}{m} \sum_{i=1}^m (y_i - \hat{y}_i) ]
Parameter Update Rule
Gradient descent updates the parameters through the following rule \( w \) and \( b \):
[ w := w - \alpha \frac{\partial J}{\partial w} ]
[ b := b - \alpha \frac{\partial J}{\partial b} ]
Where:
\( \alpha \)is the learning rate, which controls the step size of each update.
Steps of Gradient Descent
- Initialize the parameters: initialize
\( w \)and\( b \)to values (usually set to 0 or random values). - Compute the loss function: Compute the value of the loss function under the current parameters
\( J(w, b) \)。 - Compute gradients: Compute the partial derivative of the loss function with respect to
\( w \)and\( b \). - Update parameters: Update according to the gradient
\( w \)and\( b \)。 - Iterate Repeatedly: Repeat steps 2 to 4 until the loss function converges or the maximum number of iterations is reached.
Implementing Linear Regression in Python
Below we demonstrate how to implement linear regression in Python through a simple example.
1. Import the Necessary Libraries
Example
import
numpy
as
np
import
matplotlib.
pyplot
as
plt
from
sklearn.
linear_model
import
LinearRegression
2. Generate Simulated Data
Example
import
numpy
as
np
import
matplotlib.
pyplot
as
plt
from
sklearn.
linear_model
import
LinearRegression
Generate some random data
np.
random
.
seed
(
0
)
x
=
2
- np.
random
.
rand
(
100
,
1
)
y
=
4
3
- x + np.
random
.
randn
(
100
,
1
)
Visualize the data
plt.
scatter
(
x
,
y
)
plt.
xlabel
(
'x'
)
plt.
ylabel
(
'y'
)
plt.
title
(
'Generated Data From Runoob'
)
plt.
show
(
)
The display is shown as follows:

3. Linear Regression with Scikit-learn
Example
import
numpy
as
np
import
matplotlib.
pyplot
as
plt
from
sklearn.
linear_model
import
LinearRegression
Generate some random data
np.
random
.
seed
(
0
)
x
=
2
- np.
random
.
rand
(
100
,
1
)
y
=
4
3
- x + np.
random
.
randn
(
100
,
1
)
Create the linear regression model
model
=
LinearRegression
(
)
Fit the model
model.
fit
(
x
,
y
)
Output the model parameters
(
f
"Slope (w): {model.coef_[0][0]}"
)
(
f
"Intercept (b): {model.intercept_[0]}"
)
Predict
y_pred
=
model.
predict
(
x
)
Visualize the fitting results
plt.
scatter
(
x
,
y
)
plt.
plot
(
x
,
y_pred
,
color
=
'red'
)
plt.
xlabel
(
'x'
)
plt.
ylabel
(
'y'
)
plt.
title
(
'Linear Regression Fit'
)
plt.
show
(
)
Output result:
斜率 (w): 2.968467510701019
截距 (b): 4.222151077447231
The display is shown as follows:

We can use the score() method to evaluate model performance, returning the R^2 value.
Example
import
numpy
as
np
from
sklearn.
linear_model
import
LinearRegression
Generate some random data
np.
random
.
seed
(
0
)
x
=
2
- np.
random
.
rand
(
100
,
1
)
y
=
4
3
- x + np.
random
.
randn
(
100
,
1
)
Create the linear regression model
model
=
LinearRegression
(
)
Fit the model
model.
fit
(
x
,
y
)
Calculate the model score
score
=
model.
score
(
x
,
y
)
(
"Model score:"
,
score
)
The output is:
模型得分: 0.7469629925504755
4. Manually Implement Gradient Descent
Example
import
numpy
as
np
import
matplotlib.
pyplot
as
plt
from
sklearn.
linear_model
import
LinearRegression
Generate some random data
np.
random
.
seed
(
0
)
x
=
2
- np.
random
.
rand
(
100
,
1
)
y
=
4
3
- x + np.
random
.
randn
(
100
,
1
)
Initialize the parameters
w
=
0
b
=
0
learning_rate
=
0.1
n_iterations
=
1000
gradient descent
for
i
in
range
(
n_iterations
)
:
y_pred
=
w * x + b
dw
=
(
2
/
len
(
x
)
)
- np.
sum
(
x *
(
y - y_pred
)
)
db
=
(
2
/
len
(
x
)
)
- np.
sum
(
y - y_pred
)
w
=
w - learning_rate * dw
b
=
b - learning_rate * db
Output the final parameters
(
f
"Manually implemented slope (w): {w}"
)
(
f
"Manually implemented intercept (b): {b}"
)
Visualize the fitting results of the manual implementation
y_pred_manual
=
w * x + b
plt.
scatter
(
x
,
y
)
plt.
plot
(
x
,
y_pred_manual
,
color
=
'green'
)
plt.
xlabel
(
'x'
)
plt.
ylabel
(
'y'
)
plt.
title
(
'Manual Gradient Descent Fit'
)
plt.
show
(
)
Output result:
手动实现的斜率 (w): 2.968467510701028
手动实现的截距 (b): 4.222151077447219
The display is shown as follows:
