# python中的ifelse以及switch

python中的ifelse以及switch

ifelse以及switchpython中的用法，其中switchpython里可以用字典的形式表示

result=‘a’:lambda x:x*2......大括号打不出来，此处省略了～～～

import theano.tensor as T

from theano.ifelse import ifelse

import theano,time,numpy

from theano import function

a,b=T.dscalars('a','b')

x,y=T.dmatrices('x','y')

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

z_ifelse=ifelse(T.lt(a,b),T.mean(x),T.mean(y))

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

f_ifelse=function([a,b,x,y],z_ifelse,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_ifelse(val1,val2,big_mat1,big_mat2)

print'time spent evaluating one value %f sec'%(time.clock()-tic)

https://blog.sciencenet.cn/blog-571755-707369.html

## 全部精选博文导读

GMT+8, 2024-9-15 12:00

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社