线性回归

1. 符号表示

y(x, w) = w_0 + w_1x_1 + \ldots + w_Dx_D

\mathbf{x} = (x_1, \ldots, x_D)^T

\mathbf{w} = (w_0, w_1, \ldots, w_D)

x_i \in \mathbb{R},\ w_i \in \mathbb{R},\ y_i \in \mathbb{R}

f(X) = w_0 + \sum_{i=1}^{D} x_i w_i

2. 具体实例

y = wx + b

  • y: 资产值
  • X = \{\text{个人努力},\ \text{年龄},\ \text{知识储备},\ \text{阅历}\}

已知 :

\begin{cases} x = 0.5,\ y = 2 \\ x = 1.5,\ y = 4 \end{cases}

可得 y = 2x + 1 的图像如下 :

image.png
image.png

3. 计算损失函数

image.png

\left\{ \begin{array}{l} x^1, \hat{y}^1 \\ x^2, \hat{y}^2 \\ \vdots \\ x^N, \hat{y}^N \end{array} \right\} \quad \stackrel{\text{预测}}{\longrightarrow} \quad \left\{ \begin{array}{l} \hat{y}^1 = w x^1 + b \\ \hat{y}^2 = w x^2 + b \\ \vdots \\ \hat{y}^N = w x^N + b \end{array} \right\}

损失函数

\begin{aligned} \text{loss} &= \mathcal{L} \\ &= \frac{1}{N} \sum_{i=1}^{N} \left( f(x_i) - y_i \right)^2 \\ &= \frac{1}{N} \sum_{i=1}^{N} \left( w x_i + b - y_i \right)^2 \\ &= \frac{1}{N} \sum_{i=1}^{N} \left( w^2 x_i^2 + 2 w x_i (b - y_i) + (b - y_i)^2 \right) \end{aligned}

在实际机器学习中,几乎从不手动展开 MSE 损失,因为:

  • 求导时直接用链式法则更简单, 不需要先展开再求导。
  • 展开后形式复杂,且无助于理解或计算。
  • 自动微分框架(如 PyTorch)会自动处理,无需手动展开。
image.png

4. 梯度下降

我们要最小化这个损失,所以对 每个参数求导:
w 求导:
\frac{\partial \mathcal{L}}{\partial w} = \frac{2}{N} \sum_{i=1}^N (wx_i + b - y_i) \cdot x_i
b 求导:
\frac{\partial \mathcal{L}}{\partial b} = \frac{2}{N} \sum_{i=1}^N (wx_i + b - y_i)

无论是 w 还是 b,都遵循同样的梯度下降规则:

\begin{aligned} w_{\text{new}} &= w - \text{lr} \cdot \frac{\partial \mathcal{L}}{\partial w} \\ b_{\text{new}} &= b - \text{lr} \cdot \frac{\partial \mathcal{L}}{\partial b} \end{aligned}

在梯度下降(Gradient Descent)中,参数更新公式为:

w_{\text{new}} = w - \text{lr} \cdot \nabla_w \mathcal{L}

b_{\text{new}} = b - \text{lr} \cdot \nabla_b \mathcal{L}

  • w:当前模型参数(如权重)
  • lr(learning rate):步长, 控制我们沿着梯度反方向走多远
  • \nabla_w \mathcal{L}:损失函数 \mathcal{L}w 的梯度(指示“上升最快的方向”)
  • \nabla_b \mathcal{L}:损失函数 \mathcal{L}b 的梯度(指示“上升最快的方向”)

可见 b 不是“常量”——它是可训练参数,只是初始值可能设为 0 或其他值。

完整图解
image.png

5. 梯度下降算法的收敛条件

✅ 正确答案:
理论上,当梯度 \nabla_w \mathcal{L} = 0\nabla_b \mathcal{L} = 0 时,达到(局部)极小值点,此时可以停止迭代。

也就是说:目标是让梯度变为 0(或足够接近 0),而不是“不变”。

🔍 详细解释

1. 为什么是“梯度为 0”?

梯度 \nabla \mathcal{L} 表示损失函数在当前参数处的最陡上升方向。
梯度下降的更新规则是:

w \leftarrow w - \text{lr} \cdot \nabla_w \mathcal{L}

  • \nabla_w \mathcal{L} = 0\nabla_b \mathcal{L} = 0 时,参数不再更新,说明已经到达一个驻点(stationary point)。
    • 对于凸函数(如线性回归的 MSE),这个驻点就是全局最小值。
    • 对于非凸函数(如神经网络),可能是局部最小值、鞍点等。
2. “梯度不变” ≠ 收敛!

如果梯度“不变”但不为 0(例如一直保持某个非零常数),说明:

  • 学习率太大导致震荡;
  • 或优化器陷入循环;
  • 并没有收敛!
3. 实际中如何判断停止?

由于浮点精度限制,几乎不可能精确达到梯度 = 0,所以实践中用以下任一条件停止:
✅ 常用停止准则:

image.png

在 PyTorch/TensorFlow 中,通常靠“最大 epoch 数”或“验证损失不再下降”来停。

4. 线性回归的特殊情况

对于线性回归 + MSE 损失 :

  • 损失函数是严格凸函数(如果数据满秩)
  • 有唯一全局最小值
  • 理论上梯度下降会收敛到 \nabla_w \mathcal{L} = 0, \nabla_b \mathcal{L} = 0

但实际仍因浮点误差,使用“梯度足够小”作为停止条件。

✅ 总结
image.png
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容