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

280. 将广播梯度还原回输入形状

MediumAutograd

当形状为 (d,) 的 bias 被加到形状为 (n, d) 的 activations 上时,NumPy 会对其进行广播。在反向传播中,传入的 gradient 形状为 (n, d),但 bias gradient 的形状必须为 (d,):因为每个广播副本都做出了贡献,所以需要进行求和。每个数组 autograd engine 都需要这个辅助函数。

编写 unbroadcast(grad, shape),其中 grad 是根据 NumPy 规则,将给定形状(一个 tuple)的输入广播到 grad.shape 后产生的数组。通过对以下维度求和,返回一个形状完全一致的数组:
- 输入中不存在的额外前导维度,以及
- 输入中大小为 1 但 grad 中大小 > 1 的维度(保持其大小为 1)。
如果 shape 是 (),则返回一个包含总和的 0-d 数组。

函数def unbroadcast(grad, shape)

示例 1

输入: grad of shape (2, 3) filled with ones and shape (3,)

输出: [2.0, 2.0, 2.0]

约束条件

  • grad has shape (2, 3)
  • Python 3 with NumPy. Code runs in your browser.
  • Your code must pass all 7 tests to be accepted.
提示 1

首先在 grad.ndim > len(shape) 时对 axis 0 进行求和。

提示 2

然后对于每个满足 shape[i] == 1 且 grad.shape[i] != 1 的 axis i,使用 keepdims=True 进行求和。

常见错误
  • 有 Bug 的版本仅移除了前导维度。
理解思路

Broadcasting 会静默地复制一个小数组以匹配较大的数组,例如一个 bias 行被重复用于 batch 中的每个样本。在反向传播中,每个副本都接收到了自己的 gradient,因此输入的 gradient 是所有副本的求和。复制通过两种方式实现:输入从未有过的新增前导维度,以及输入大小为 1 的维度。

Worked example

grad = [[1, 2, 3], [4, 5, 6]],形状为 (2, 3)。对于形状为 (3,) 的输入,对前导维度求和:[5, 7, 9]。对于形状为 (2, 1) 的输入,保持维度数量但对 axis 1 求和并保持大小为 1:[[6], [15]]。对于形状 (),求所有元素的和:21。

首先对额外的前导维度进行求和,直到维度数量匹配,然后对于目标大小为 1 且 grad 大小更大的每个维度,沿该维度求和并保留该维度。输出必须完全符合请求的形状。每个数组 autograd engine 在执行 add、mul 和其他 broadcasting ops 后都会调用此类辅助函数。
主题
Autograd
相似题目
  • 构建一个微型反向模式 autograd 引擎Medium
  • Route gradients through a max reductionMedium
  • Compute a gradient on a DAG with memoized backpropMedium
  • 使用拓扑排序为反向传播排列计算图Easy
所有 Autograd 道题目
反馈
280 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def unbroadcast(grad, shape):
# your code here
pass
​

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

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