Build a Jacobian with central finite differences

When a function returns a vector, its derivative is a matrix. Finite differences give you a reference to test hand-written backward passes against.

Write fd_jacobian(f, x, eps=1e-6). f maps a 1D array of length n to a 1D array of length m. Return the (m, n) matrix J with J[i, j] = d f_i / d x_j, using (f(x + eps e_j) - f(x - eps e_j)) / (2 eps).

Signaturedef fd_jacobian(f, x, eps=1e-6)

Example

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

Understand the idea

When a function returns a vector, its derivative is a matrix called the Jacobian: entry (i, j) says how output i changes when input j is nudged. Central finite differences estimate each column by nudging one input a tiny bit up and down and comparing outputs. It is slow but simple, which makes it the standard reference for checking hand-written gradients. Worked example: f(x) = [x0^2, x0 * x1] at x = [1, 2]. Nudging x0: d(x0^2)/dx0 = 2 * 1 = 2 and d(x0 * x1)/dx0 = x1 = 2. Nudging x1: 0 and x0 = 1. So J = [[2, 0], [2, 1]]: rows are outputs, columns are inputs. Rule: for each input j, make e_j (zeros with a 1 at j), compute (f(x + eps * e_j) - f(x - eps * e_j)) / (2 * eps), and put it in column j; J has shape (m, n). Central differences are accurate to about eps^2. Stacking the results as rows instead gives the transpose, which only looks right for symmetric cases. Used for gradient checks in autograd and backprop code.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: examplefd_jacobian(lambda v: np.array([v[0] * v[1], v[0] + v[1]]), [2.0, 3.0])
  • Sample 2: non squarefd_jacobian(lambda v: np.array([v[0] ** 2, np.sin(v[1]), v[0] * v[2]]), [1.0, 0.5, 2.0])
  • Test 3: linear mapfd_jacobian(lambda v: np.array([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]) @ v, [0.1, -0.2])