我正在尝试使用渐变定义自定义theano Op以便将其与pymc3一起使用,但我不知道如何定义grad
方法。
下面的代码是我遇到的问题。函数phi()
是一个模拟函数(实际上,它是一个外部程序);对于标量输入x
,它返回向量(phi_0(x), phi_1(x), ...)
。函数phi_diff()
(也是模拟函数)返回向量(dphi_0/dx, dphi_1/dx, ...)
。
我将phi()
和phi_diff()
包装在theano.Op
对象中,但是我对grad
函数的实现无法正常工作。 theano的文档中包含一些更简单的示例,在这种情况下,我不知道如何适应它们。任何帮助将不胜感激。
import numpy as np
import theano.tensor as T
import theano
theano.config.optimizer = "None"
theano.config.exception_verbosity = "high"
def phi(x):
return np.arange(n) * x
def phi_diff(x):
return np.arange(n)
class PhiOp(theano.Op):
itypes = [theano.tensor.dscalar]
otypes = [theano.tensor.dvector]
def perform(self, node, inputs, output_storage):
x = inputs[0]
output_storage[0][0] = phi(x)
def grad(self, inputs, output_grads):
x = inputs[0]
# ???
return [PhiDiffOp()(x) * output_grads[0]]
class PhiDiffOp(theano.Op):
itypes = [theano.tensor.dscalar]
otypes = [theano.tensor.dvector]
def perform(self, node, inputs, output_storage):
x = inputs[0]
output_storage[0][0] = phi_diff(x)
n = 5
x = 777.
phi_op = PhiOp()
x_tensor = T.dscalar("x_tensor")
phi_func = theano.function([x_tensor], phi_op(x_tensor))
np.testing.assert_allclose(phi_func(x), phi(x))
T.jacobian(phi_op(x_tensor), x_tensor)
答案 0 :(得分:1)
找到了解决方案,更改如下:
def phi_diff(x):
return np.arange(n, dtype=np.float_)
class PhiOp(theano.Op):
def grad(self, inputs, output_grads):
x = inputs[0]
gg = (PhiDiffOp()(x) * output_grads[0]).sum()
return [gg]