263. 通过 sigmoid 层链测量梯度消失
重要性 这就是为什么深度网络从 sigmoid 转向 ReLU,以及为什么 LSTM 会添加加性 cell path 的原因。
堆叠 sigmoid 会导致浅层学习非常缓慢。你可以通过逐层计算梯度来理解其中的原因。
编写 sigmoid_chain_grads(x, weights)。这是一个标量链:a_0 = x,对于列表中的每个权重 w_l,a_l = sigmoid(w_l * a_{l-1})。返回一个长度为 L + 1 的 float 数组 g,其中 g[l] = d a_L / d a_l,因此 g[L] = 1。使用 d a_l / d a_{l-1} = w_l * s_l * (1 - s_l),其中 s_l = a_l。
def sigmoid_chain_grads(x, weights)Where the sigmoid stops passing gradient
The dashed curve is the slope σ'(x) = σ(x)(1 − σ(x)). It peaks at 0.25 at x = 0, so a chain of sigmoid layers multiplies gradients by at most 0.25 each.
- input
- 0.00
- sigmoid
- 0.5
- slope of sigmoid
- 0.25
示例 1
输入: sigmoid_chain_grads(1.0, [1.0, 1.0])
输出: about [0.0431, 0.2194, 1.0]
示例 2
输入: x = 0.5, weights = [2.0, 2.0, 2.0, 2.0, 2.0, 2.0]
输出: [0.000614, 0.001561, 0.005108, 0.018566, 0.069657, 0.26362, 1.0]
示例 3
输入: x = 0.0, weights = [4.0, -3.0, 5.0]
输出: [-0.457384, -0.457384, 1.022227, 1.0]
约束条件
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 7 tests to be accepted.
提示 1
在前向传播时存储所有的 a_l,然后从末尾开始反向乘以局部导数。
提示 2
sigmoid'(z) = s(1 - s)。
提示 3
链式法则:将局部导数相乘。
提示 4
g 的条目数比 weights 多一个。
常见错误
- 在 d(w a)/da 中忘记了权重 w。
- 在 s(1 - s) 中使用了输入 a_{l-1} 而不是输出
a_l。
理解思路
到达浅层的梯度是每一层局部斜率的乘积。sigmoid 的斜率最大为 0.25,因此使用普通权重时,十层网络可能会将梯度乘以大约 0.25^10,即百万分之一左右。这就像在长队中传递悄悄话,每个人说话的声音都比前一个人小四倍。
x = 1, w = 1 两次。a1 = sigmoid(1) = 0.731, a2 = sigmoid(0.731) = 0.675. d a2 / d a1 = 0.675 * 0.325 = 0.219. d a1 / d x = 0.731 * 0.269 = 0.197. So d a2 / d x = 0.219 * 0.197 = 0.041.
g[l - 1] = g[l] * w_l * a_l * (1 - a_l), with g[L] = 1
为了在深度 CNN 和 transformer 中阻止这种缩减,ReLU、残差连接和精心的初始化都被采用了。