use*_*937 3 python automatic-differentiation differentiation python-2.7 autograd
我有一个接受多变量参数 x 的函数。这里 x = [x1,x2,x3]。假设我的函数如下所示: f(x,T) = np.dot(x,T) + np.exp(np.dot(x,T) 其中 T 是一个常数。
我对查找 df/dx1、df/dx2 和 df/dx3 函数很感兴趣。
我使用 scipy diff 取得了一些成功,但我有点怀疑,因为它使用了数值差异。昨天,我的同事指给我 Autograd (github)。由于它似乎是一个流行的包,我希望这里有人知道如何使用这个包来获得偏微分。我对这个库的初步测试表明 grad 函数只对第一个参数进行微分。我不确定如何将其扩展到其他参数。任何帮助将不胜感激。
谢谢。
我在 autograd 源代码中找到了以下对 grad 函数的描述:
def grad(fun, x)
"Returns a function which computes the gradient of `fun` with
respect to positional argument number `argnum`. The returned
function takes the same arguments as `fun`, but returns the
gradient instead. The function `fun`should be scalar-valued. The
gradient has the same type as the argument."
Run Code Online (Sandbox Code Playgroud)
所以
def h(x,t):
return np.dot(x,t) + np.exp(np.dot(x,t))
h_x = grad(h,0) # derivative with respect to x
h_t = grad(h,1) # derivative with respect to t
Run Code Online (Sandbox Code Playgroud)
还要确保使用 autograd 附带的 numpy libaray
import autograd.numpy as np
Run Code Online (Sandbox Code Playgroud)
代替
import numpy as np
Run Code Online (Sandbox Code Playgroud)
以便使用所有 numpy 函数。
| 归档时间: |
|
| 查看次数: |
2891 次 |
| 最近记录: |