简体   繁体   English

使用Autograd的偏导数

[英]Partial Derivative using Autograd

I have a function that takes in a multivariate argument x. 我有一个接受多变量参数x的函数。 Here x = [x1,x2,x3]. 这里x = [x1,x2,x3]。 Let's say my function looks like: f(x,T) = np.dot(x,T) + np.exp(np.dot(x,T) where T is a constant. 假设我的函数看起来像:f(x,T)= np.dot(x,T)+ np.exp(np.dot(x,T),其中T是常数。

I am interested in finding df/dx1, df/dx2 and df/dx3 functions. 我对找到df / dx1,df / dx2和df / dx3函数感兴趣。

I have achieved some success using scipy diff, but I am a bit skeptical because it uses numerical differences. 我使用scipy diff取得了一些成功,但是我有点怀疑,因为它使用了数值差异。 Yesterday, my colleague pointed me to Autograd (github) . 昨天,我的同事将我指向Autograd (github) Since it seems to be a popular package, I am hoping someone here knows how to get partial differentiation using this package. 由于它似乎是一个受欢迎的软件包,因此我希望这里的人知道如何使用此软件包进行部分区分。 My initial tests with this library indicates that the grad function only takes differentiation with respect to the first argument. 我对该库的初步测试表明,grad函数仅对第一个参数进行微分。 I am not sure how to extend it to other arguments. 我不确定如何将其扩展到其他论点。 Any help would be greatly appreciated. 任何帮助将不胜感激。

Thanks. 谢谢。

I found the following description of the grad function in the autograd source code: 我在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."

So 所以

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

Also make sure to use the numpy libaray that comes with autograd 还要确保使用autograd随附的numpy libaray

import autograd.numpy as np

instead of 代替

import numpy as np

in order to make use of all numpy functions. 为了利用所有的numpy函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM