Theano2.1.9-基础知识之条件

来自:http://deeplearning.net/software/theano/tutorial/conditions.html

conditions

一、IfElse vs Switch

  • 这两个操作都是在符号变量上建立约束条件
  • IfElse 采用 boolean 条件,并且两个变量作为输入。
  • Switch t采用 tensor 作为条件,也是两个变量作为输入。 switch 是一个逐元素的操作,所以比ifelse更通用。
  • 然而 switch 在两个输出变量上进行评估,而 ifelse 只对一个关于条件的变量进行评估。

Example

from theano import tensor as T
from theano.ifelse import ifelse
import theano, time, numpy

a,b = T.scalars('a', 'b')
x,y = T.matrices('x', 'y')

z_switch = T.switch(T.lt(a, b), T.mean(x), T.mean(y))
z_lazy = ifelse(T.lt(a, b), T.mean(x), T.mean(y))

f_switch = theano.function([a, b, x, y], z_switch,
                    mode=theano.Mode(linker='vm'))
f_lazyifelse = theano.function([a, b, x, y], z_lazy,
                    mode=theano.Mode(linker='vm'))

val1 = 0.
val2 = 1.
big_mat1 = numpy.ones((10000, 1000))
big_mat2 = numpy.ones((10000, 1000))

n_times = 10

tic = time.clock()
for i in xrange(n_times):
    f_switch(val1, val2, big_mat1, big_mat2)
print 'time spent evaluating both values %f sec' % (time.clock() - tic)

tic = time.clock()
for i in xrange(n_times):
    f_lazyifelse(val1, val2, big_mat1, big_mat2)
print 'time spent evaluating one value %f sec' % (time.clock() - tic)
    在这个例子中,fElse 操作比Switch花费更少的时间(大约节约一半时间)因为它只计算两个变量中的一个。

>>> python ifelse_switch.py
time spent evaluating both values 0.6700 sec
time spent evaluating one value 0.3500 sec

    除非使用了 linker='vm' 或者 linker='cvm' , ifelse 才会计算两个变量,然后会和switch有着一样的计算时间。尽管连接器当前设置的默认值不是cvm,不过在不久的将来会是的。

    没有自动的优化,通过使用广播的标量来替换switch成为ifelse,因为这并不见得总是更快的,见 ticket.


参考资料:

[1]官网:http://deeplearning.net/software/theano/tutorial/conditions.html


posted @ 2015-06-16 22:59  仙守  阅读(1088)  评论(0编辑  收藏  举报