BLOGLLM Logo
Go Pro
Guest
Not signed in
所有博客课程练习面试准备系列标签书签价格
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboard游戏
Articles
练习 / Neural networks2 of 18 in topic

258. 计算 dense 和 conv 权重的 Xavier 和 He 初始化 scale

EasyNeural networks

只有当激活值在逐层传递过程中既不爆炸也不消失时,网络才能训练良好。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。

Worked example

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 层。每个深度学习框架都会默认应用这些方法。

主题
Neural networks
相似题目
  • 全连接层的反向传播Easy
  • 计算 MLP 的参数量Easy
  • Find where early stopping haltsEasy
  • 运行 MLP 前向传播并保留每一层的 activationEasy
所有 Neural networks 道题目
反馈
258 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def init_scale(shape, scheme):
# your code here
pass
​

Run 会在浏览器中检查这些用例,无需登录。 Submit 会检查所有 6 个测试。

Ctrl/按 + 回车 运行
© BlogLLM, Bengaluru, India关于条款隐私退款DMCA联系我们RSS