A Jacobian From the Outside

Linear Algebra for Deep LearningMedium+20 XP+20

A Jacobian From the Outside

In this chapter you built Jacobians with pencil and paper: differentiate every output with respect to every input, and lay the results out so that

Jij=∂fi∂xjJ_{ij} = \frac{\partial f_i}{\partial x_j}Jij​=∂xj​∂fi​​

Row iii belongs to output iii; column jjj belongs to input jjj.

Sometimes pencil and paper aren't an option. The function might be a black box you can only call — a simulator, say — or you've worked a Jacobian out by hand and want an independent check that you didn't slip. Then you measure it instead.

To measure column jjj, leave every input alone except xjx_jxj​. Nudge xjx_jxj​ up by a small amount hhh and call fff; nudge it down by hhh and call fff again. How far each output moved, divided by the distance 2h2h2h between the two calls, estimates that output's partial derivative:

Jij≈fi(…, xj+h, …)  −  fi(…, xj−h, …)2hJ_{ij} \approx \frac{f_i(\ldots,\ x_j + h,\ \ldots) \;-\; f_i(\ldots,\ x_j - h,\ \ldots)}{2h}Jij​≈2hfi​(…, xj​+h, …)−fi​(…, xj​−h, …)​

Task: write numerical_jacobian(f, x, h).

  • f is a Python function. It takes a list of nnn numbers and returns a list of mmm numbers — and mmm doesn't have to equal nnn.
  • x is the point, a list of nnn numbers. Leave it exactly as it was: the caller still needs it.
  • h is the nudge size, a positive number.
  • Return the m×nm \times nm×n estimate as a list of mmm rows, each holding nnn numbers, with every entry rounded to 4 decimal places.

Use exactly the formula above with the h you are given. Several tests use a fairly large h on purpose, so the estimate can differ slightly from the exact derivative — return the estimate, not the exact value.

Example. The chapter's worked example, f(x,y)=(x+y2, xy)f(x, y) = (x + y^2,\ xy)f(x,y)=(x+y2, xy) at the point (2,1)(2, 1)(2,1):

That agrees with the hand-derived Jacobian [12yyx]\begin{bmatrix} 1 & 2y \\ y & x \end{bmatrix}[1y​2yx​] at (2,1)(2, 1)(2,1).

Examples

f = lambda v: [v[0] + v[1] ** 2, v[0] * v[1]]
x = [2.0, 1.0]
h = 0.001
returns [[1.0, 2.0], [1.0, 2.0]]
f = lambda v: [v[0] * v[1] + v[2], v[0] ** 3 - 2 * v[2]]
x = [1.5, -2.0, 0.5]
h = 0.01
returns [[-2.0, 1.5, 1.0], [6.7501, 0.0, -2.0]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run