用autograd grad()递归找到n阶导数

问题描述 投票:-1回答:1

我正在尝试使用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]
python recursion derivative
1个回答
0
投票

非常简单。您应该嵌套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)
© www.soinside.com 2019 - 2024. All rights reserved.