python - 替换 theano 图中表达式的变量

标签 python theano

给定以下代码:

import numpy as np
import theano
import theano.tensor as T

x,y,z = T.dmatrices('x','y','z')
A = theano.shared(np.random.rand(3,4), borrow=True, name='A')
B = theano.shared(np.random.rand(3,4), borrow=True, name='B')

f = x+y+B

是否可以在表达式 f 中用 z+A 替换 y,使其等价于 x+z +A+B?它可以手动完成,方法是在图表中搜索出现的 y 并将它们替换为 z+A。但是,在 API 中使用更简单的高级方法来执行此操作似乎合乎逻辑。

最佳答案

这是 discussed on the theano-users mailing list .

您可以使用 theano.functiongivens 机制或使用 theano.clone

下面是一些示例代码:

import numpy as np
import theano
import theano.tensor as T

x, y, z = T.dmatrices('x', 'y', 'z')
A = theano.shared(np.random.rand(3, 4), borrow=True, name='A')
B = theano.shared(np.random.rand(3, 4), borrow=True, name='B')

h1 = x + y + B
h2 = theano.clone(h1, {y: z + A})

f1 = theano.function([x, y], h1)
f2 = theano.function([x, z], h2)
f3 = theano.function([x, z], h1, givens={y: z + A})

a = np.random.randn(3, 4)
b = np.random.randn(3, 4)
print f1(a, b)
print f2(a, b)
print f3(a, b)

请注意,必须调整 theano 函数的输入以确保只有未指定的张量被接受为输入(即 y 一旦被 的函数替换后就不再是输入>z).

关于python - 替换 theano 图中表达式的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33920777/

相关文章:

python - 导入错误 : No module named xml. dom.minidom

python - 如何存储像 "The last day in Feb"、 "Fourth Saturday in April"这样的描述性日期?

python - 定位并切掉数据数组中的重叠部分

python - 检验大量股票 yield 的自相关性

theano - 如何在没有嵌入层的Keras中编写LSTM?

python - 从 GPU 核心/线程的角度理解 Theano 示例

python - Keras 的 Resnet 期望输入什么?

python - 如何使用Python模块 "attr.asdict(MyObject)"实现 'attrs'的反转

python - Theano输入输出样本数错误

installation - 有没有办法在没有 Nvidia 的情况下安装 Theano