用autograd grad()递归求n阶导数

Recursively find the nth order derivative with autograd grad()

我正在尝试使用 autograd 库中的 grad 函数查找函数的 n 次导数。 grad(x) 给出一阶导数,但它不允许变量找到比方说三阶导数等。有没有办法我可以递归地执行此操作,以便用户可以确定他们想要的导数顺序看?

import matplotlib.pyplot as plt
from autograd import grad
import autograd.numpy as np


# a named Python function
g = lambda w: w**2

w_vals = np.linspace(-5,5,200)
nabla_g = grad(g)   #A function here that can find the nth derivative
# evaluate gradient over input range
g_vals = [g(v) for v in w_vals]
grad_vals = [nabla_g(v) for v in w_vals]

很简单。你应该嵌套你的 grad 函数

# import matplotlib.pyplot as plt
from autograd import grad
import autograd.numpy as np

def my_grad(fun, ord):
    for i in range(ord):
        fun = grad(fun)
    return fun

# a named Python function
g = lambda w: w**3

# derivative x^3 = 3x^2
# derivative 3x^2 = 6x
# derivative 6x = 6
w_vals = np.linspace(-5,5,200)
nabla_g = my_grad(g, 3)   # recursive call to grad lead to 3° derivative
g_vals = [g(v) for v in w_vals]
grad_vals = [nabla_g(v) for v in w_vals]
print(grad_vals) #should output 6 for every input

我还开发了my_grad的递归版本:

def my_grad(fun, ord):
    if ord == 0:
       return fun
    return my_grad(grad(fun), ord-1)