40. 推导线性模型的均方误差梯度
每个回归训练器都会进行数百万次此类梯度的计算。正确处理系数 2 和除以 n 的操作至关重要。
编写 mse_grad(X, y, w, b)。预测值为 X @ w + b。损失函数为 mean((pred - y) ** 2)。返回 (grad_w, grad_b)。
def mse_grad(X, y, w, b)示例 1
输入: X = [[1], [2]], y = [1, 2], w = [0], b = 0
输出: grad_w [-5] and grad_b -3
示例 2
输入: X = [[1.0], [2.0]], y = [2.0, 4.0], w = [2.0], b = 0.0
输出: ([0.0], 0.0)
约束条件
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 3 tests to be accepted.
提示 1
Differentiate mean((pred - y)^2): the residual r = pred - y appears with a factor of 2, and the mean gives a division by n.
提示 2
Compute r = X @ w + b - y, then grad_w is 2 times X.T @ r divided by n, and grad_b is 2 times the mean of r.
提示 3
Use n = len(y), not the number of features, and return grad_b as a plain float, for example float(2.0 * r.mean()).
理解思路
对于线性模型,均方误差的梯度指明了调整每个权重以减小平均平方误差的方向。每个残差 r = pred - y 会贡献 2 * r 倍的输入,而平均值操作则除以 n。
X = [[1], [3]], y = [2, 2], w = [1], b = 0. Predictions [1, 3], residuals [-1, 1]. grad_w = (2 / 2) * (1 * -1 + 3 * 1) = 2. grad_b = (2 / 2) * (-1 + 1) = 0. 因此权重应该减小,而偏置已经处于平衡状态。
r = X w + b - y; grad_w = (2 / n) * X^T r; grad_b = (2 / n) * sum(r). 丢掉系数 2 会使每个梯度减半,使用固定学习率训练时可能会掩盖这一点,但梯度检查会发现问题。忘记 1 / n 会导致步长随 batch size 增大而增大。这是线性回归的核心梯度,同样的模式也出现在任何使用 MSE 训练的网络的输出层中。