一、多变量线性回归(Multivariate Linear Regression)
为什么需要多变量?
现实问题中,一个目标可能受多个因素影响,比如预测房价时:
- x 1 x_1 x1:面积
- x 2 x_2 x2:卧室数量
- x 3 x_3 x3:房龄
- . . . ... ...
假设函数(Hypothesis Function)
在单变量线性回归基础上推广为:
h θ ( x ) = θ 0 + θ 1 x 1 + θ 2 x 2 + ⋯ + θ n x n 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 ) = θ T x 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 , x 1 , x 2 , ⋯ , x n ] T x = [1, x_1, x_2, \cdots, x_n]^T x=[1,x1,x2,⋯,xn]T( x 0 = 1 x_0 = 1 x0=1 以统一偏置项)
模型核心思想:
和单变量回归一样,我们要最小化代价函数:
J ( θ ) = 1 2 m ∑ i = 1 m ( 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)
x i : = x i − μ i s i x_i := \frac{x_i - \mu_i}{s_i} xi:=sixi−μi
- μ i \mu_i μi:第 i i i 个特征的平均值
- s i s_i si:标准差或最大最小差
使得所有特征都落在类似于 [ − 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) / sigmareturn X_norm, mu, sigma# 只对 x1~xn 归一化,排除 x0
X[:, 1:], mu, sigma = feature_normalize(X[:, 1:])
三、向量化梯度下降(Vectorized Gradient Descent)
成本函数:
J ( θ ) = 1 2 m ( X θ − y ) T ( X θ − y ) J(\theta) = \frac{1}{2m}(X\theta - y)^T(X\theta - y) J(θ)=2m1(Xθ−y)T(Xθ−y)
梯度公式(向量化):
θ : = θ − α m X T ( X θ − y ) \theta := \theta - \frac{\alpha}{m} X^T(X\theta - y) θ:=θ−mαXT(Xθ−y)
其中:
- X X X 是 m × ( n + 1 ) m \times (n+1) m×(n+1) 的训练样本矩阵
- y y y 是 m × 1 m \times 1 m×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 - ygradient = (1 / m) * X.T @ errortheta -= alpha * gradientJ_history.append(compute_cost(X, y, theta))return theta, J_history
四、梯度下降的收敛性分析
如何判断收敛?
- 绘制 J ( θ ) J(\theta) J(θ) 随迭代次数的变化图
- 若代价函数持续下降 → 收敛良好
- 若 震荡 / 上升 → 学习率 α \alpha α 太大,需调小
调整学习率建议:
现象 | 原因 | 解决方法 |
---|---|---|
收敛很慢 | 学习率太小 | 增加 α \alpha α |
震荡甚至发散 | 学习率太大 | 减小 α \alpha α |
五、正规方程法(Normal Equation)
不使用梯度下降,直接求解析解:
解法公式:
θ = ( X T X ) − 1 X T y \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 @ ytheta_ne = normal_equation(X, y)
正规方程特点:
优点 | 缺点 |
---|---|
不需选择学习率 | 不能用于特征非常多的情况(矩阵求逆开销大) |
不需迭代,一次求解 | 对数据量大、特征维度高时效率较低 |
六、可视化训练过程(损失下降)
import matplotlib.pyplot as plttheta, 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()