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

41. 使用中心有限差分构建 Jacobian 矩阵

EasyCalculus and gradients

当一个函数返回一个向量时,其导数是一个矩阵。有限差分可以为你提供一个参考值,用于测试手写的 backward pass。

编写 fd_jacobian(f, x, eps=1e-6)。f 将长度为 n 的 1D array 映射到长度为 m 的 1D array。使用 (f(x + eps e_j) - f(x - eps e_j)) / (2 eps) 返回 (m, n) 矩阵 J,其中 J[i, j] = d f_i / d x_j。

函数def fd_jacobian(f, x, eps=1e-6)

示例 1

for f(x) = [x0 * x1, x0 + x1] at x = [2, 3], J is [[3, 2], [1, 1]].

示例 2

输入: f = lambda v: [v[0] ** 2, np.sin(v[1]), v[0] * v[2]], x = [1.0, 0.5, 2.0]

输出: [[2, 0.0, 0.0], [0.0, 0.877583, 0.0], [2, 0.0, 1]]

示例 3

输入: f = lambda v: [[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]] @ v, x = [0.1, -0.2]

输出: [[1, 2], [3, 4], [5, 6]]

约束条件

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

Nudging one input x_j changes every output at once, so one pair of function calls gives you a whole column of the Jacobian.

提示 2

Loop over input positions j, build a vector that is eps at position j and zero elsewhere, evaluate f at x plus and minus that vector, divide the difference by 2 eps, and stack the columns.

提示 3

Each column has length m, and there are n of them, so stack with np.stack(cols, axis=1) to get shape (m, n), not (n, m). Convert x and f's outputs to float arrays so the arithmetic works on lists.

理解思路

当一个函数返回一个向量时,其导数是一个被称为 Jacobian 的矩阵:第 (i, j) 个元素表示当输入 j 发生微小变化时,输出 i 如何变化。中心有限差分通过将一个输入分别向上和向下微调并比较输出,从而估计每一列。这种方法虽然慢但很简单,因此它是检查手写梯度标准参考。

Worked example

f(x) = [x0^2, x0 * x1] 在 x = [1, 2] 处。微调 x0: d(x0^2)/dx0 = 2 * 1 = 2 且 d(x0 * x1)/dx0 = x1 = 2。微调 x1: 0 和 x0 = 1。所以 J = [[2, 0], [2, 1]]: 行是输出,列是输入。

对于每个输入 j,构造 e_j (在 j 处为 1 的全零向量),计算 (f(x + eps * e_j) - f(x - eps * e_j)) / (2 * eps),并将其放入第 j 列;J 的 shape 为 (m, n)。中心差分的精度约为 eps^2。如果将结果按行堆叠则会得到转置,这仅在对称情况下看起来是正确的。常用于 autograd 和 backprop 代码中的梯度检查。
主题
Calculus and gradients
相似题目
  • 使用中心差分法检查梯度Easy
  • 当矩阵不对称时对二次型求导Easy
  • 推导线性模型的均方误差梯度Easy
  • 根据 Hessian 矩阵分类临界点Easy
所有 Calculus and gradients 道题目
反馈
41 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def fd_jacobian(f, x, eps=1e-6):
# your code here
pass
​

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

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