我试图区分z(x)w.r.t。 x使用ad
库,我知道y(x)和z(y)。如果我不能分析地找到z(x),我该如何进行区分?换句话说,我试图避免链规则计算,如下所示:
from ad import gh
def y(x):
return 2*x
def z(y):
return 3*y
dzdy,hy = gh(z)
dydx,hz = gh(y)
x0 = 0 # does not matter for this example
dydx_x0 = dydx(x0)
y0 = y(x0)
dzdy_y0 = dzdy(y0)
dzdx_x0 = dzdy_y0[0] * dydx_x0[0]
print(dzdx_x0) # dz/dx = dz/dy*dy/dx = 3*2 = 6
答案 0 :(得分:2)
def z_of_x(x):
return z(y(x))
gradient, hessian = gh(z_of_x)
只需定义一个按z
计算x
的函数,并像往常一样应用自动微分。