如何在不重建图形的情况下重用具有不同共享变量的 Theano 函数? [英] How to reuse Theano function with different shared variables without rebuilding graph?

查看:20
本文介绍了如何在不重建图形的情况下重用具有不同共享变量的 Theano 函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个被多次调用的 Theano 函数,每次都使用不同的共享变量.按照现在的实现方式,Theano 函数在每次运行时都会重新定义.我假设,这会使整个程序变慢,因为每次定义 Theano 函数时,图形都会重建.

I have a Theano function that is called several times, each time with different shared variables. The way it is implemented now, the Theano function gets redefined every time it is run. I assume, that this make the whole program slow, because every time the Theano functions gets defined the graph is rebuild.

def sumprod_shared(T_shared_array1, T_shared_array2):
    f = theano.function([], (T_shared_array1 * T_shared_array2).sum(axis=0))
    return f()

for factor in range(10):
    m1 = theano.shared(factor * array([[1, 2, 4], [5, 6, 7]]))
    m2 = theano.shared(factor * array([[1, 2, 4], [5, 6, 7]]))
    print sumprod_shared(m1, m2)

对于非共享(普通)变量,我可以定义一次函数,然后使用不同的变量调用它而无需重新定义.

For non shared (normal) variables I can define the function once and then call it with different variables without redefining.

def sumprod_init():
    T_matrix1 = T.lmatrix('T_matrix1')
    T_matrix2 = T.lmatrix('T_matrix2')
    return theano.function([T_matrix1, T_matrix2], (T_matrix1 * T_matrix2).sum(axis=0))    

sumprod = sumprod_init()
for factor in range(10):
    np_array1 = factor * array([[1, 2, 4], [5, 6, 7]])
    np_array2 = factor * array([[1, 2, 4], [5, 6, 7]])
    print sumprod(np_array1, np_array2)

这也适用于共享变量吗?

Is this possible also for shared variables?

推荐答案

你可以使用 theano.function 中的 givens 关键字来解决这个问题.基本上,您可以执行以下操作.

You can use the givens keyword in theano.function for that. Basically, you do the following.

m1 = theano.shared(name='m1', value = np.zeros((3,2)) )
m2 = theano.shared(name='m2', value = np.zeros((3,2)) )

x1 = theano.tensor.dmatrix('x1')
x2 = theano.tensor.dmatrix('x2')

y = (x1*x2).sum(axis=0)
f = theano.function([],y,givens=[(x1,m1),(x2,m2)],on_unused_input='ignore')

然后循环遍历值,您只需将共享变量的值设置为您想要的值.顺便说一下,您必须将 on_unused_input 设置为 'ignore' 以使用在 theano 中没有参数的函数.像这样:

then to loop through values you just set the value of the shared variables to the value you'd like. You have to set the on_unused_input to 'ignore' to use functions with no arguments in theano, by the way. Like this:

array1 = array([[1,2,3],[4,5,6]])
array2 = array([[2,4,6],[8,10,12]])

for i in range(10):
    m1.set_value(i*array1)
    m2.set_value(i*array2)
    print f()

它应该有效,至少我是这样解决的.

It should work, at least that's how I've been working around it.

这篇关于如何在不重建图形的情况下重用具有不同共享变量的 Theano 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆