张量流:十位数上的while循环

2024-10-03 17:25:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试在张量值上应用while循环。例如,对于变量“a”,我尝试递增地增加张量的值,直到满足某个条件。但是,我一直得到这个错误:

ValueError: Shape must be rank 0 but is rank 3 for 'while_12/LoopCond' (op: 'LoopCond') with input shapes: [3,1,1].

a = array([[[0.76393723]],
       [[0.93270312]],
       [[0.08361106]]])

a = np.random.random((3,1,1))
a1 = tf.constant(np.float64(a))
i = tf.constant(np.float64(6.14))

c = lambda i: tf.less(i, a1)
b = lambda x: tf.add(x, 0.1)
r = tf.while_loop(c, b, [a1])

Tags: lambdatfa1错误nprandom条件shape
1条回答
网友
1楼 · 发布于 2024-10-03 17:25:41

tf.while_loop()的第一个参数应该返回标量(秩0的张量实际上是标量,这就是错误消息的内容)。在您的示例中,您可能希望使条件返回true,以防a1张量中的所有数字都小于6.14。这可以通过tf.reduce_all()(逻辑AND)和tf.reduce_any()(逻辑OR)来实现。在

这段话对我很有用:

tf.reset_default_graph()

a = np.random.random_integers(3, size=(3,2))
print(a)
# [[1 1]
#  [2 3]
#  [1 1]]

a1 = tf.constant(a)
i = 6

# condition returns True till any number in `x` is less than 6
condition = lambda x : tf.reduce_any(tf.less(x, i))
body      = lambda x : tf.add(x, 1)
loop = tf.while_loop(
    condition,
    body,
    [a1],
)

with tf.Session() as sess:
    result = sess.run(loop)
    print(result)
    # [[6 6]
    #  [7 8]
    #  [6 6]]
    # All numbers now are greater than 6

相关问题 更多 >