给定以下代码:
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.function
的 givens
机制或使用 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/