线性回归(一元):
① 、一元线性回归是分析只有一个自变量线性相关关系的方法,此处可以理解为:线性回归法是一种求最佳拟合线 y=a+bx 的数学方法(也叫“最小二乘回归法”)。
②、误差平方和(SSE): 该名称定义为“各个(y的实际值与 通过最佳拟合线得出的y的预测值 的差值)²的和“
SSE为最小时,便是最小拟合线。
过程推导:
假设有函数 (初始对二者随机赋值)
损失函数:
是样本点的实际值,是预测值
然后利用梯度下降求出 为何值时损失函数 的值最小
分别对 和 求偏导:
迭代:
代入求出每次迭代后的损失函数的值
不断迭代直到损失函数的值小于所规定的,将此时的和 代入
即可得到所求直线。
例题示例:
假设我们的数据集如下:
x | y |
1 | 2 |
2 | 4 |
3 | 6 |
4 | 8 |
5 | 10 |
我们随机初始化 和 ,学习率 ,目标是让模型以最小化平方误差的方式来预测未知房屋的价格。
步骤 1:计算当前模型的预测值和实际值之间的误差。
将模型中的参数和 带入到 中,得到:
将样本数据代入上式,得到误差函数:
步骤2:计算梯度
利用误差函数求导的公式,我们可以得到:
步骤3:使用梯度更新参数
我们根据梯度下降的公式来更新参数:
根据上述公式,我们可以进行参数的更新:
因此,本例子在第一轮迭代之后,更新后的参数值为 和 。
继续迭代直到达到所规定的终止条件。
代码:
import numpy as np
import matplotlib.pyplot as plt
# 初始化参数
theta_0 = 0
theta_1 = 0
alpha = 0.01
num = 1000 # 迭代次数
X = [1, 2, 3, 4, 5]
Y = [2, 4, 6, 8, 10]
# 损失函数
def J(theta_0, theta_1, X, Y):
error = 0
m = len(X)
for i in range(m):
error += (theta_0 + theta_1 * X[i] - Y[i]) ** 2
return error / (2 * m)
# 梯度函数
def gradient_descent(theta_0, theta_1, X, Y, alpha, num):
m = float(len(X)) # m用作除数
for i in range(num):
sum_theta_0 = 0
sum_theta_1 = 0
for j in range(len(X)):
sum_theta_0 += theta_0 + theta_1*X[j] - Y[j]
sum_theta_1 += (theta_0 + theta_1*X[j] - Y[j])*X[j]
theta_0 = theta_0 - alpha * sum_theta_0 / m
theta_1 = theta_1 - alpha * sum_theta_1 / m
return theta_0, theta_1
# 运行梯度下降算法并打印结果
theta_0, theta_1 = gradient_descent(theta_0, theta_1, X, Y, alpha, num)
print("theta_0 = ", theta_0)
print("theta_1 = ", theta_1)
# 可视化训练数据和拟合直线
plt.scatter(X, Y, color='r')
plt.plot(X, [theta_0 + theta_1*x for x in X])
plt.xlabel('X')
plt.ylabel('Y')
plt.show()