258. 计算 dense 和 conv 权重的 Xavier 和 He 初始化 scale
只有当激活值在逐层传递过程中既不爆炸也不消失时,网络才能训练良好。Xavier 和 He 初始化根据层的 fan_in 和 fan_out 来选择随机权重的分布范围。Conv 层需要计算每个 kernel 位置,这是人们经常遗忘的部分。
编写 init_scale(shape, scheme)。shape 是一个 tuple:对于 dense 权重为 (out, in),对于 conv 权重为 (out, in, k1, k2, ...)。令 r = shape[2:] 的乘积(对于 dense 为 1)。fan_in = in * r, fan_out = out * r。
返回一个 float:
- "xavier_uniform": U(-a, a) 的边界 a, a = sqrt(6 / (fan_in + fan_out))
- "xavier_normal": std = sqrt(2 / (fan_in + fan_out))
- "he_uniform": 边界 a = sqrt(6 / fan_in)
- "he_normal": std = sqrt(2 / fan_in)
def init_scale(shape, scheme)示例 1
输入: init_scale((4, 2), "he_normal")
输出: 1.0
示例 2
输入: shape = (256, 128), scheme = 'xavier_uniform'
输出: 0.125
示例 3
输入: shape = (10, 30), scheme = 'xavier_normal'
输出: 0.223607
约束条件
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 6 tests to be accepted.
提示 1
For conv weights every kernel position counts toward the fans, not just the channel counts.
提示 2
Compute r as the product of shape[2:], set fan_in = shape[1] * r and fan_out = shape[0] * r, then apply the formula for the chosen scheme.
提示 3
Uniform schemes use 6 in the numerator and normal schemes use 2, Xavier divides by fan_in + fan_out and He by fan_in only; np.prod(()) is 1, so dense shapes work too.
常见错误
- 有 Bug 的版本仅使用了前两个维度。
理解思路
如果初始权重太大,激活值会逐层爆炸;如果太小,则会逐渐消失。Xavier 和 He 初始化根据每个单元接收的输入数量 (fan_in) 和每个输入连接到的单元数量 (fan_out) 来选择随机权重的分布范围。对于 conv 权重,每个 kernel 位置都计为一个输入,因此感受野大小会同时乘以两个 fan。
conv shape (16, 8, 3, 3)。r = 3 * 3 = 9, fan_in = 8 * 9 = 72, fan_out = 16 * 9 = 144. He normal std = sqrt(2 / 72) = sqrt(1 / 36) = 0.1667. Xavier uniform bound = sqrt(6 / (72 + 144)) = sqrt(6 / 216) = 0.1667. 对于 dense (4, 2) 权重, He normal std = sqrt(2 / 2) = 1.
Xavier uniform sqrt(6 / (fan_in + fan_out)), Xavier normal sqrt(2 / (fan_in + fan_out)), He uniform sqrt(6 / fan_in), He normal sqrt(2 / fan_in)
He 适用于 ReLU 网络;Xavier 适用于 tanh 或 linear 层。每个深度学习框架都会默认应用这些方法。