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

Linear Regression (Linear Regression)

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:

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:

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:

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:

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:

Steps of Gradient Descent

  1. Initialize the parameters: initialize \( w \) and \( b \) to values (usually set to 0 or random values).
  2. Compute the loss function: Compute the value of the loss function under the current parameters \( J(w, b) \)。
  3. Compute gradients: Compute the partial derivative of the loss function with respect to \( w \) and \( b \) .
  4. Update parameters: Update according to the gradient \( w \) and \( b \)。
  5. 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

random

.

rand

(

100

,

1

)

y

=

4

3

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

random

.

rand

(

100

,

1

)

y

=

4

3

random

.

randn

(

100

,

1

)

Create the linear regression model

model

=

LinearRegression

(

)

Fit the model

model.

fit

(

x

,

y

)

Output the model parameters

print

(

f

"Slope (w): {model.coef_[0][0]}"

)

print

(

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

random

.

rand

(

100

,

1

)

y

=

4

3

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

)

print

(

"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

random

.

rand

(

100

,

1

)

y

=

4

3

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

)

)

sum

(

x *

(

y - y_pred

)

)

    db

=

(

2

/

len

(

x

)

)

sum

(

y - y_pred

)

    w

=

w - learning_rate * dw

    b

=

b - learning_rate * db

Output the final parameters

print

(

f

"Manually implemented slope (w): {w}"

)

print

(

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: