theano tutorial(六)IfElse vs Switch

来源:互联网 发布:易语言统计成绩源码 编辑:程序博客网 时间:2021/05/15 20:08

1.IfElse 和 Switch都用于判定公式是否满足某种条件

2.IfElse用boolean作为条件,输入为两个变量

3.Swich用tensor作为条件,输入也为两个变量,Switch是一种elementwise操作符,因此比ifelse更加通用

4.switch对每个输出变量进行操作,ifelse只对一个满足条件的变量操作,意思就是说

switch(cond, ift, iff):    """if cond then ift else iff"""

如果满足条件,则switch既执行ift也执行iff

而ifelse只执行ift或者只执行iff


#coding=utf-8# IfElse vs Switchfrom theano import tensor as Tfrom theano.ifelse import ifelseimport theano,time,numpya,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))#li:a < b?z_lazy=ifelse(T.lt(a,b),T.mean(x),T.mean(y))#The Mode represents a way to optimize and then link a computation graph.#def __init__(self, linker=None, optimizer='default'):#optimizer:optimizer的类型结构(可以简化计算,增加计算的稳定性)#linker:决定使用哪种方式进行编译(C/Python),怎么把他们联系到一起来进行运算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 = 10tic = 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))

time spent evaluating both values 0.358457 sectime spent evaluating one value 0.188870 sec


如果不使用inker='vm' 或者 linker='cvm' ,ifelse 的执行时间将会和switch一样

0 0