265. 实现 inverted dropout
Dropout 在训练期间会随机将 activations 置零。Inverted dropout 还会将保留下来的值乘以 1 / (1 - p),使得期望值保持不变,从而在推理阶段无需进行任何更改。
编写 dropout(x, p, training, rng)。在训练模式下,使用 rng.random(x.shape) >= p 构建 keep mask,并返回 x * mask / (1 - p)。非训练模式或 p == 0 时:原样返回 x(作为 float array)。
请务必只调用一次 shape 为 x.shape 的 rng.random,以确保结果匹配。
def dropout(x, p, training, rng)示例 1
输入: x = np.ones((2, 4)), p = 0.5, training = True, rng = np.random.default_rng(0)
输出: [[2.0, 0.0, 0.0, 0.0], [2.0, 2.0, 2.0, 2.0]]
示例 2
输入: x = [1.0, 2.0], p = 0.5, training = False, rng = np.random.default_rng(0)
输出: [1.0, 2.0]
示例 3
输入: round(float((np.asarray(dropout(np.ones(20000), 0.3, True, np.random.default_rng(1))) == 0).mean()), 1)
输出: 0.3
约束条件
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 4 tests to be accepted.
提示 1
mask = rng.random(x.shape) >= p.
提示 2
乘以并除以 1 - p。
常见错误
- 有 Bug 的版本忘记了 scaling,这会导致仅在训练期间缩小了 activations。
理解思路
Dropout 在训练期间随机关闭 activations,使得网络无法依赖任何单个单元,就像一支球队在随机缺席球员的情况下进行练习。Inverted dropout 将保留下来的值除以 (1 - p),使得每个 activation 的期望值保持不变,因此在测试时无需更改任何内容。
x = [2, 4, 6, 8], p = 0.5,随机抽样结果为 [0.7, 0.2, 0.9, 0.4]。当 draw >= 0.5 时保留,因此 mask 为 [1, 0, 1, 0]。Output = [2, 0, 6, 0] / 0.5 = [4, 0, 12, 0]。平均而言,保留的值补偿了被丢弃的值。在 evaluation mode 或 p = 0 时,原样返回 x(作为 floats)。
mask = rng.random(x.shape) >= p; out = x * mask / (1 - p) 仅在 training 时执行。请务必仅调用一次具有完整 shape 的 rng.random,以确保结果可复现。Dropout 被广泛应用于许多网络以及某些 LLM fine-tuning 设置中。
公司3
- ByteDance the topic appears in interview reports ByteDance Machine Learning Engineer Interview Process
- Google the topic appears in interview reports Google AI/ML, RAG and agentic AI interview (AI Engineering Insider)
- NVIDIA the topic appears in interview reports NVIDIA Interview Prep: Questions, Process & Study Plan
来自公开面试报告和指南。与这些公司无隶属关系或背书关系。