1. 梯度下降法(Gradient Descent)
梯度下降法是一种迭代优化算法,用于最小化线性回归模型的损失函数。其基本思想是通过沿着损失函数梯度的反方向调整模型参数,以找到最优的参数值,使损失函数达到最小。
1.1 使用API实现梯度下降法
import numpy as np
from sklearn.linear_model import SGDRegressor
from sklearn.preprocessing import StandardScaler
# 准备数据
X = np.array([[1, 3], [2, 4], [5, 8]])
y = np.array([6, 8, 21])
# 特征缩放
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# 创建SGDRegressor模型
model_sgd = SGDRegressor(learning_rate='constant', eta0=0.01, max_iter=1000)
model_sgd.fit(X_scaled, y)
# 打印参数
print("使用梯度下降法得到的参数:", model_sgd.coef_, model_sgd.intercept_)
2. 正规方程(Normal Equation)
正规方程是通过解析求解的方法,直接得到线性回归模型的最优参数值。与梯度下降法不同,正规方程不需要选择学习率,并且在数据集较小的情况下通常表现良好。
2.1 使用API实现正规方程
import numpy as np
from sklearn.linear_model import LinearRegression
# 准备数据
X = np.array([[1, 3], [2, 4], [5, 8]])
y = np.array([6, 8, 21])
# 创建LinearRegression模型
model_normal = LinearRegression()
model_normal.fit(X, y)
# 打印参数
print("使用正规方程得到的参数:", model_normal.coef_, model_normal.intercept_)
总结
梯度下降法和正规方程是线性回归中常用的两种优化算法。梯度下降法是一种迭代优化算法,通过不断调整参数来最小化损失函数。正规方程是一种解析求解的方法,直接得到最优参数值。