python - 定义自定义 Op theano 的 grad
问题描述
我正在尝试定义一个带有渐变的自定义 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)
解决方案
找到解决方案,更改如下:
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]
推荐阅读
- python - 难以找到某些使用 CSS 选择器的标签
- collections - 如何在 MarkLogic 中添加 Unitemporal 文档
- javascript - 如何在没有 jQuery 的情况下一次验证多个单选按钮?
- javascript - 如何从以纯文本形式显示的 API 中提取 JSON 数据?
- reactjs - “React.createContext 不是函数” - 但我没有使用它
- sharepoint-online - 如何区分sharepoint文档库中的微软团队频道文件夹和普通SP文件夹
- sorting - 在 NetSuite 中,我可以按项目 # 或其他列字段对事务进行排序吗?
- html - 您可以在 SCSS 中将设备的宽度作为变量调用吗?
- avro - 如何在 Avro Schema 中创建记录列表
- android - Android Firebase 阻止用户删除数据库