tf.while_loop - ValueError:这两个结构的元素数量不同 [英] tf.while_loop - ValueError: The two structures don't have the same number of elements

查看:30
本文介绍了tf.while_loop - ValueError:这两个结构的元素数量不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to do the following in 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

我得到的错误如下图所示.

The error that I get is shown in the image below.

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

I'm unable to understand what the two 'structures' are in the error message. I want to ultimately make a 'tf.while_loop' with the 'condition' based on the value of a tf.Placeholder ('i' in the code above).

推荐答案

你应该在body函数中添加return语句:

You should add return statement to body function:

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

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

But I think you should also change your code to something like

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])

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

because tf.while_loop() is only node in graph, which you should run, else you will not get any results.

这篇关于tf.while_loop - ValueError:这两个结构的元素数量不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆