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

257. 全连接层的反向传播

EasyNeural networks
提问于AnthropicNVIDIAOpenAI

全连接层计算 y = x @ W + b。给定损失函数对 y 的梯度,反向传播需要三个梯度。

编写 dense_backward(x, W, dy),其中 x 的形状为 (n, d_in),W 的形状为 (d_in, d_out),dy 的形状为 (n, d_out)。返回 (dx, dW, db)。

函数def dense_backward(x, W, dy)

示例 1

输入: dense_backward([[1.0, 2.0]], [[1.0], [0.5]], [[1.0]])

输出: ([[1.0, 0.5]], [[1.0], [2.0]], [1.0])

约束条件

  • Python 3 with NumPy. Code runs in your browser.
  • Your code must pass all 3 tests to be accepted.
提示 1

Each gradient must have the same shape as the thing it is a gradient of, and that alone tells you which matrices to multiply and transpose.

提示 2

Push dy back through the matrix product for dx and dW, and sum dy over the batch for db, because the bias was added to every row.

提示 3

dx is (n, d_in), so it is dy @ W.T; dW is (d_in, d_out), so it is x.T @ dy; db is dy.sum(axis=0).

理解思路

全连接层计算 y = x W + b。在反向传播中,你会收到 dy(即损失随每个输出的变化情况),并且必须传回三样东西:输入的梯度、权重的梯度以及偏置的梯度。这些都源于链式法则,且形状可以作为你的指导。

Worked example

x = [[1, 2]], W = [[1], [3]], dy = [[2]]. dx = dy W^T = [[2 x 1, 2 x 3]] = [[2, 6]]. dW = x^T dy = [[1 x 2], [2 x 2]] = [[2], [4]]. db = dy 按行求和 = [2]. 对于一个 batch 的行,dW 通过矩阵乘法累加了每一行的贡献,而 db 对 dy 按行求和是因为相同的偏置被加到了每一行。使用均值而不是求和是一个常见的 bug。

dx = dy W^T (形状为 n by d_in); dW = x^T dy (d_in by d_out); db = sum(dy, axis 0) (d_out). 每个 MLP 和 transformer 的 projection 都会用到这个反向传播过程。
主题
Neural networks
公司3
  • Anthropic a candidate reported this question ML Coding at Each Company (CircleCoder)
  • NVIDIA the topic appears in interview reports NVIDIA Interview Prep: Questions, Process & Study Plan
  • OpenAI a candidate reported this question Coding Exercises & ML System Design: Real AI Interview Questions (landedjobs)

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

相似题目
  • 计算 dense 和 conv 权重的 Xavier 和 He 初始化 scaleEasy
  • 计算 MLP 的参数量Easy
  • Find where early stopping haltsEasy
  • 运行 MLP 前向传播并保留每一层的 activationEasy
所有 Neural networks 道题目
反馈
257 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def dense_backward(x, W, dy):
# your code here
pass
​
dense_backward(_x, _W, _dy)[0]

此用例使用生成数据,因此按原样运行。按 + 添加你自己的用例。

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

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