Math-06.矩阵微积分-02.标量对向量求导

本页列出 ML 最高频的标量对向量求导公式(分子布局)。

段末注释:$\mathbf{a},\mathbf{x}$ 为列向量时,$\mathbf{a}^\top \mathbf{x}$ 为标量;对 $\mathbf{x}$ 求导得 $\mathbf{a}$。

系列入口00.系列规划 | 前置:01 总论


1. 基本公式(D3)

图 1 梯度方向:最速上升

设 $f: \mathbb{R}^d \to \mathbb{R}$,$\mathbf{x} \in \mathbb{R}^d$(列向量)。

$f(\mathbf{x})$ $\displaystyle\frac{\partial f}{\partial \mathbf{x}}$
$\mathbf{a}^\top \mathbf{x}$ $\mathbf{a}$
$\mathbf{x}^\top \mathbf{a}$ $\mathbf{a}$
$\mathbf{x}^\top \mathbf{x} = |\mathbf{x}|_2^2$ $2\mathbf{x}$
$\mathbf{x}^\top A \mathbf{x}$($A$ 对称) $2A\mathbf{x}$
$\mathbf{a}^\top \mathbf{x} \mathbf{x}^\top \mathbf{b}$ $\mathbf{a}(\mathbf{b}^\top \mathbf{x}) + \mathbf{b}(\mathbf{a}^\top \mathbf{x})$

矩阵标量 $f(W)$:$\partial f / \partial W$ 与 $W$ 同形,逐元素偏导。


2. MSE 线性回归(D6–D7)

图 2 MSE 对 w 的梯度

$$
L = \frac{1}{2n}|X\mathbf{w} - \mathbf{y}|_2^2 = \frac{1}{2n}(\mathbf{w}^\top X^\top X \mathbf{w} - 2\mathbf{y}^\top X \mathbf{w} + \text{const})
$$

$$
\frac{\partial L}{\partial \mathbf{w}} = \frac{1}{n} X^\top (X\mathbf{w} - \mathbf{y})
$$

令其为零 → 正规方程 $X^\top X \mathbf{w} = X^\top \mathbf{y}$(Math-03/03 秩)。


3. Logistic 单样本(D7)

$\hat{y} = \sigma(\mathbf{w}^\top \mathbf{x})$,BCE $L = -[y\log\hat{y}+(1-y)\log(1-\hat{y})]$:

$$
\frac{\partial L}{\partial \mathbf{w}} = (\hat{y} - y),\mathbf{x}
$$

形式与 MSE 残差类似,源于指数族 NLL(Math-00/50)。


4. 范数与正则(D7)

图 3 MSE 与 Logistic 梯度形式

$f$ $\nabla f$
$|\mathbf{x}|_2^2$ $2\mathbf{x}$
$|\mathbf{x}|_1$ $\mathrm{sign}(\mathbf{x})$(次梯度)
$|\mathbf{w}|_2^2$(weight decay) $2\mathbf{w}$

Math-03/06 范数Math-04/04 AdamW


5. 局限(D8)

图 4 注意转置

问题 说明
$A$ 非对称 $\mathbf{x}^\top A \mathbf{x}$ 梯度为 $(A+A^\top)\mathbf{x}$
分母布局文献 公式差转置
$\mathbf{w}$ 行向量写法 维度全反

6. PyTorch 验证(D12)

1
2
3
4
5
6
7
8
9
10
import torch

w = torch.randn(5, requires_grad=True)
x = torch.randn(5)
y = torch.tensor(1.0)
logit = (w * x).sum()
loss = torch.nn.functional.binary_cross_entropy_with_logits(logit, y)
loss.backward()
# 手推: (sigmoid(logit)-y)*x
print(w.grad)

7. 小结

熟记 $\mathbf{a}^\top\mathbf{x}$→$\mathbf{a}$$|\mathbf{x}|^2$→$2\mathbf{x}$MSE→$X^\top(Xw-y)/n$。下一篇:03 Jacobian 与链式法则

系列导航01 总论 | 04 反向传播

-------------本文结束感谢您的阅读-------------