268. 通过 2 层 tanh 网络进行回归和二分类的反向传播
重要性 面试官仍然会要求手推 2 层网络的 backward pass,这也是调试自定义层的基础案例。
通过手动实现一个小网络的反向传播,是建立对 autograd 信任最快的方式。
编写 two_layer_grads(X, y, W1, b1, W2, b2, task)。X 的形状为 (n, d),y 为 (n, 1),W1 为 (d, h),b1 为 (h,),W2 为 (h, 1),b2 为 (1,)。前向传播:H = tanh(X @ W1 + b1), out = H @ W2 + b2。如果 task 是 "regression",loss = 样本上 0.5 * (out - y)^2 的均值。如果 task 是 "binary",p = sigmoid(out),loss = p 对 y 的二分类交叉熵 (binary cross-entropy) 的均值。返回一个包含键 "loss", "dW1", "db1", "dW2", "db2" 的字典(均值 loss 的梯度,形状与参数相同,loss 为 float)。
def two_layer_grads(X, y, W1, b1, W2, b2, task)示例 1
输入: X = [[1, 2]], y = [[1]], W1 = [[0.5, -0.5], [0.25, 0]], b1 = [0, 0], W2 = [[1], [1]], b2 = [0], task "regression"
输出: loss 0.2454 (rounded) and db2 = [-0.7005] (rounded)
示例 2
输入: R(two_layer_grads([[1.0, 2.0], [-1.0, 0.5]], [[1.0], [0.0]], [[0.5, -0.5], [0.25, 0.1]], [0.1, 0.0], [[1.0], [-2.0]], [0.2], 'binary'))
输出: {'loss': 0.2409, 'dW1': [[-0.1492, 0.3474], [-0.0019, 0.216]], 'db1': [0.088, -0.0356], 'dW2': [[-0.1025], [0.0888]], 'db2': [0.0426]}
示例 3
输入: R(two_layer_grads([[0.0, 1.0], [2.0, -1.0], [1.0, 1.0]], [[0.5], [-1.0], [2.0]], [[0.3, 0.2], [-0.4, 0.6]], [0.0, -0.1], [[0.7], [-0.3]], [0.1], 'regression'))
输出: {'loss': 1.3724, 'dW1': [[-0.1597, -0.1784], [-0.8262, 0.3573]], 'db1': [-0.489, 0.0424], 'dW2': [[0.6101], [-0.7244]], 'db2': [-0.4117]}
约束条件
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 3 tests to be accepted.
提示 1
两个任务得到的输出梯度形状相同:对于带有 0.5 系数的 MSE,梯度为 (out - y) / n;对于 sigmoid 配合 BCE,梯度为 (p - y) / n。
提示 2
先写前向传播并保留 H。
提示 3
计算每个任务的 dout;它们的表达式形式相同。
提示 4
tanh'(z) = 1 - tanh(z)^2,而你已经在 H 中得到了 tanh(z)。
常见错误
- 因为 loss 是均值,忘记除以 n。
- 使用了错误的 tanh 导数。
- 在错误的轴上对 db 进行求和。
理解思路
反向传播就是按照链式法则逐层反向执行。想象一条工厂流水线:当最终产品出现偏差时,每个工位会根据其对产品改变量的大小按比例承担责任。
Tiny example with one sample: x = [1, 2], H = tanh([1, -0.5]) = [0.7616, -0.4621], out = 0.2995, y = 1。若 loss 为 0.5 * (out - y)^2,则 dout = out - y = -0.7005,因此 db2 = -0.7005,dW2 = H 乘以 dout。然后每个隐藏单元得到 dout * W2,再乘以 1 - H^2。
对于 MSE,dout = (out - y) / n;对于 sigmoid 配合 BCE,dout = (p - y) / n。dW2 = H^T dout, dH = dout W2^T, dZ = dH * (1 - H^2), dW1 = X^T dZ, db = 列求和。
这四行代码出现在每个网络的每个 dense 层中,包括 transformer 内部的 MLP 模块。
Shape 与数据流
X (n,d) -> Z1, H (n,h) -> out (n,1); dZ (n,h); dW1 (d,h); dW2 (h,1)
公司5
- Anthropic a candidate reported this question ML Coding at Each Company (CircleCoder)
- DeepMind the topic appears in interview reports Google DeepMind Onsite Interview: Every Round, What It Tests (SpaceComplexity)
- Meta a candidate reported this question Timed ML screen: concept questions then classic models from scratch (Land the Lab)
- 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)
来自公开面试报告和指南。与这些公司无隶属关系或背书关系。