在ano图中替换表达式的变量

2024-09-27 07:27:36 发布

您现在位置:Python中文网/ 问答频道 /正文

给出以下代码:

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

有没有可能用表达式中的z+A代替y,这样它就等价于x+z+A+B?。它可以手动完成,方法是在图形中搜索y的出现,并用z+A替换它们。然而,在API中使用一种更简单的高级方法似乎是合乎逻辑的。在


Tags: 方法代码nameimportnumpytrueasnp
1条回答
网友
1楼 · 发布于 2024-09-27 07:27:36

这是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函数所取代,它就不再是输入)。在

相关问题 更多 >

    热门问题