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

265. 实现 inverted dropout

MediumNeural networks
提问于ByteDanceGoogleNVIDIA

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 的期望值保持不变,因此在测试时无需更改任何内容。

Worked example

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 设置中。
主题
Neural networks
公司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

来自公开面试报告和指南。与这些公司无隶属关系或背书关系。

相似题目
  • Pre-norm 残差 MLP 模块的前向传播Medium
  • 通过 embedding lookup 进行反向传播Medium
  • 通过 2 层 tanh 网络进行回归和二分类的反向传播Medium
  • 追踪 Xavier 和 He 初始化下深层 ReLU 网络的激活值扩散Medium
所有 Neural networks 道题目
反馈
265 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def dropout(x, p, training, rng):
# your code here
pass
​

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

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