tf.while_loop - ValueError:这两个结构的元素数量不同

Cha*_*nya 0 python while-loop tensorflow

我正在尝试在 Tensorflow 中执行以下操作 -

import tensorflow as tf

graph = tf.Graph()

with graph.as_default():

    i = tf.Variable(0)
    sol = tf.Variable(0)

    def cond(i, sol):
        return tf.less(i, 2)
    def body(i, sol):
        i = tf.add(i, 1)
        sol = tf.add(sol, 1)
    tf.while_loop(cond, body, [i, sol])

with tf.Session(graph=graph) as session:
    tf.global_variables_initializer().run()

    result = session.run(sol, feed_dict={})
    print result
Run Code Online (Sandbox Code Playgroud)

我得到的错误如下图所示。 在此处输入图片说明

我无法理解错误消息中的两个“结构”是什么。我想最终根据 tf.Placeholder (上面代码中的“i”)的值制作一个带有“条件”的“tf.while_loop”。

Vla*_*cky 5

您应该returnbody函数添加语句:

def body(i, sol):
    i = tf.add(i, 1)
    sol = tf.add(sol, 1)
    return [i, sol]
Run Code Online (Sandbox Code Playgroud)

但我认为您也应该将代码更改为类似

graph = tf.Graph()

with graph.as_default():
    i = tf.Variable(0)
    sol = tf.Variable(0)

    def cond(i, sol):
        return tf.less(i, 2)

    def body(i, sol):
        i = tf.add(i, 1)
        sol = tf.add(sol, 1)
        return [i, sol]

    result = tf.while_loop(cond, body, [i, sol])

with tf.Session(graph=graph) as session:
    tf.global_variables_initializer().run()
    result = session.run(result, feed_dict={})
    print(result[1])
Run Code Online (Sandbox Code Playgroud)

因为tf.while_loop()只是图中的节点,您应该运行它,否则您将不会得到任何结果。