tensorflow-条件循环控制(4)
例如非严格语义的示例:在下面的示例中,计数器i的最终值不依赖于x。while_loop可并行地增加计数器,并更新x。
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Thu Sep 6 10:16:37 2018 @author: myhaspl """ import tensorflow as tf import tensorflow as tf n = 10 x = tf.constant(0) c = lambda i,x: i < n b = lambda i,x: (tf.Print(i + 1,[i],"i:"),tf.Print(x + 1,[x],"x:")) i,out = tf.while_loop(c,b,(0,x)) with tf.Session() as sess: print(sess.run([i,out])) i:[0]x:[0] x:[1] i:[9]
i:[6] 下面的例子将x设为列表,每次迭代对列表的每个元素加1 #!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Thu Sep 6 10:16:37 2018 @author: myhaspl """ import tensorflow as tf import tensorflow as tf n = 10 x = tf.constant(list(range(n))) c = lambda i,out])) i:[0] x:[1 2 3...]i:[2] x:[2 3 4...] x:[6 7 8...]i:[6] x:[7 8 9...]i:[7] x:[8 9 10...] 因为一个循环迭代中的循环计数器依赖于前一个迭代中的值循环计数器本身不能并行递增。 #!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Thu Sep 6 10:16:37 2018 @author: myhaspl """ import tensorflow as tf def b(i): return tf.Print(i + 2,"i:") def c(i): return tf.less(i,n) n = tf.constant(10) i = tf.constant(0) res = tf.while_loop(c,[i]) with tf.Session() as sess: print sess.run(res) i:[0] #!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Thu Sep 6 10:16:37 2018 @author: myhaspl """ import tensorflow as tf def b(i,x): return (tf.Print(i + 2,"x:")) def c(i,x): return tf.less(i,n) n = 10 i = 0 x = tf.constant(list(range(n))) i,(i,x)) with tf.Session() as sess: print sess.run(i) i:[0] 注意:因为i每次递增2,所以x只会递增5次,每次增加1 #!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Thu Sep 6 10:16:37 2018 @author: myhaspl """ import tensorflow as tf def b(i,x)) with tf.Session() as sess: print sess.run(out) i:[0] x:[1 2 3...]i:[4] i:[6]x:[2 3 4...] x:[3 4 5...] 在极端情况下,可以想象,递增计数器的线程在x递增一次之前一直运行到完成。唯一不可能发生的事情是线程更新x永远不可能超过计数器线程,因为递增x的线程取决于计数器的值。下面模拟了这种情况(i>6时,x更新递增) #!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Thu Sep 6 10:16:37 2018 @author: myhaspl """ import tensorflow as tf def b(i,x): i=tf.Print(i + 1,"i:") x=tf.cond(i<=5,lambda: tf.Print(x,"x:"),lambda: tf.Print(x + 1,"x:")) return (i,x) def c(i,n) n = 10 i = 0 x = 0 i,x)) with tf.Session() as sess: print sess.run(out) i:[0] x:[0] 组合tf.cond与tf.while_loop #!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Thu Sep 6 10:16:37 2018 @author: myhaspl @email:[email?protected] 二分法猜数字 """ import tensorflow as tf def body(a,guessnum,num): center = tf.div(tf.add(a,b),2) a,num= tf.cond(guessnum>center,lambda: (center,center),lambda: (a,center,center)) return (tf.Print(a,[a],"a:"),tf.Print(b,[b],"b:"),num) def c(a,num): return tf.not_equal(guessnum,num) guessnum = tf.constant(71) mynum = tf.constant(-1) a = tf.constant(0) b = tf.constant(100) a,num = tf.while_loop(c,body,(a,mynum)) with tf.Session() as sess: print sess.run(num) b:[100]a:[50]a:[50]b:[75]b:[75]a:[62]b:[75]a:[68]a:[68]b:[71]71 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |