版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010255642/article/details/82527058
例如非严格语义的示例:在下面的示例中,计数器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:[1]
i:[2]
x:[2]
i:[3]
x:[3]
i:[4]
x:[4]
i:[5]
x:[5]
i:[6]
x:[6]
i:[7]
i:[8]x:[7]
i:[9]
x:[8]
x:[9]
[10, 10]
>>>
观察上面例子,x和i是并行计算的,以至于在i为8时,x还是7
i:[6]
x:[6]
i:[7]
i:[8]x:[7]
下面的例子将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, 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 1 2...]i:[1]
x:[1 2 3...]i:[2]
x:[2 3 4...]
i:[3]
x:[3 4 5...]
i:[4]
x:[4 5 6...]
x:[5 6 7...]i:[5]
x:[6 7 8...]i:[6]
x:[7 8 9...]i:[7]
x:[8 9 10...]
i:[8]
i:[9]
x:[9 10 11...]
[10, array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19], dtype=int32)]