theano switch函数

IfElse vs Switch

  • Both ops build a condition over symbolic variables.
  • IfElse takes a boolean condition and two variables as inputs.
  • Switch takes a tensor as condition and two variables as inputs. switch is an elementwise operation and is thus more general than ifelse.
  • Whereas switch evaluates both output variables, ifelse is lazy and only evaluates one variable with respect to the condition.

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 range(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 range(n_times):
    f_lazyifelse(val1, val2, big_mat1, big_mat2)
print('time spent evaluating one value %f sec' % (time.clock() - tic))

In this example, the IfElse op spends less time (about half as much) than Switch since it computes only one variable out of the two.

$ python ifelse_switch.py
time spent evaluating both values 0.6700 sec
time spent evaluating one value 0.3500 sec    
比较最终花费的时间,ifelse消耗的时间是switch的一半,因为它只计算一个值,switch计算两个输出值
返回满足条件的一个

Unless linker='vm' or linker='cvm' are used, ifelse will compute both variables and take the same computation time as switch. Although the linker is not currently set by default to cvm, it will be in the near future.

There is no automatic optimization replacing a switch with a broadcasted scalar to an ifelse, as this is not always faster. See this ticket.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值