一、多变量线性回归(Multivariate Linear Regression)
为什么需要多变量?
现实问题中,一个目标可能受多个因素影响,比如预测房价时:
- x1x_1x1:面积
- x2x_2x2:卧室数量
- x3x_3x3:房龄
- .........
假设函数(Hypothesis Function)
在单变量线性回归基础上推广为:
hθ(x)=θ0+θ1x1+θ2x2+⋯+θnxn
h_\theta(x) = \theta_0 + \theta_1 x_1 + \theta_2 x_2 + \cdots + \theta_n x_n
hθ(x)=θ0+θ1x1+θ2x2+⋯+θnxn
向量形式更简洁:
hθ(x)=θTx
h_\theta(x) = \theta^T x
hθ(x)=θTx
其中:
- θ=[θ0,θ1,⋯ ,θn]T\theta = [\theta_0, \theta_1, \cdots, \theta_n]^Tθ=[θ0,θ1,⋯,θn]T(参数向量)
- x=[1,x1,x2,⋯ ,xn]Tx = [1, x_1, x_2, \cdots, x_n]^Tx=[1,x1,x2,⋯,xn]T( x0=1x_0 = 1x0=1 以统一偏置项)
模型核心思想:
和单变量回归一样,我们要最小化代价函数:
J(θ)=12m∑i=1m(hθ(x(i))−y(i))2
J(\theta) = \frac{1}{2m} \sum_{i=1}^{m} \left( h_\theta(x^{(i)}) - y^{(i)} \right)^2
J(θ)=2m1i=1∑m(hθ(x(i))−y(i))2
然后通过梯度下降法或正规方程法求解。
Python 示例代码(数据模拟)
import numpy as np
# 模拟数据:面积、卧室数,房价
X = np.array([[2104, 3],
[1600, 3],
[2400, 3],
[1416, 2],
[3000, 4]])
y = np.array([399.9, 329.9, 369.0, 232.0, 539.9]).reshape(-1, 1)
m = len(y)
# 添加偏置项 x0 = 1
X = np.c_[np.ones((m, 1)), X] # shape = (m, n+1)
theta = np.zeros((X.shape[1], 1)) # 初始参数
二、特征缩放(Feature Scaling)
特征数值差距大时(如面积 [50,200][50, 200][50,200] vs 房龄 [1,30][1, 30][1,30],梯度下降可能收敛非常慢,因此需要对输入进行缩放。
方法:均值归一化(mean normalization)
xi:=xi−μisi x_i := \frac{x_i - \mu_i}{s_i} xi:=sixi−μi
- μi\mu_iμi:第 iii 个特征的平均值
- sis_isi:标准差或最大最小差
使得所有特征都落在类似于 [−1,1][-1, 1][−1,1] 范围内
Python 实现:
def feature_normalize(X):
mu = np.mean(X, axis=0)
sigma = np.std(X, axis=0)
X_norm = (X - mu) / sigma
return X_norm, mu, sigma
# 只对 x1~xn 归一化,排除 x0
X[:, 1:], mu, sigma = feature_normalize(X[:, 1:])
三、向量化梯度下降(Vectorized Gradient Descent)
成本函数:
J(θ)=12m(Xθ−y)T(Xθ−y) J(\theta) = \frac{1}{2m}(X\theta - y)^T(X\theta - y) J(θ)=2m1(Xθ−y)T(Xθ−y)
梯度公式(向量化):
θ:=θ−αmXT(Xθ−y) \theta := \theta - \frac{\alpha}{m} X^T(X\theta - y) θ:=θ−mαXT(Xθ−y)
其中:
- XXX 是 m×(n+1)m \times (n+1)m×(n+1) 的训练样本矩阵
- yyy 是 m×1m \times 1m×1 的目标值列向量
Python 实现:
def compute_cost(X, y, theta):
m = len(y)
return (1 / (2 * m)) * np.sum((X @ theta - y) ** 2)
def gradient_descent(X, y, theta, alpha, num_iters):
m = len(y)
J_history = []
for _ in range(num_iters):
error = X @ theta - y
gradient = (1 / m) * X.T @ error
theta -= alpha * gradient
J_history.append(compute_cost(X, y, theta))
return theta, J_history
四、梯度下降的收敛性分析
如何判断收敛?
- 绘制 J(θ)J(\theta)J(θ) 随迭代次数的变化图
- 若代价函数持续下降 → 收敛良好
- 若 震荡 / 上升 → 学习率 α\alphaα 太大,需调小
调整学习率建议:
现象 | 原因 | 解决方法 |
---|---|---|
收敛很慢 | 学习率太小 | 增加 α\alphaα |
震荡甚至发散 | 学习率太大 | 减小 α\alphaα |
五、正规方程法(Normal Equation)
不使用梯度下降,直接求解析解:
解法公式:
θ=(XTX)−1XTy \theta = (X^T X)^{-1} X^T y θ=(XTX)−1XTy
Python 实现:
def normal_equation(X, y):
return np.linalg.inv(X.T @ X) @ X.T @ y
theta_ne = normal_equation(X, y)
正规方程特点:
优点 | 缺点 |
---|---|
不需选择学习率 | 不能用于特征非常多的情况(矩阵求逆开销大) |
不需迭代,一次求解 | 对数据量大、特征维度高时效率较低 |
六、可视化训练过程(损失下降)
import matplotlib.pyplot as plt
theta, J_history = gradient_descent(X, y, theta, alpha=0.1, num_iters=400)
plt.plot(J_history)
plt.xlabel("Iterations")
plt.ylabel("Cost J(θ)")
plt.title("Cost Reduction over Time")
plt.grid(True)
plt.show()