gpt4 book ai didi

tensorflow - Tensorflow 中的 while_loop 错误

转载 作者:行者123 更新时间:2023-12-03 15:06:42 26 4
gpt4 key购买 nike

我尝试使用 while_loop Tensorflow ,但是当我尝试返回目标时 输出 从可调用的 while 循环中,它给了我一个错误,因为每次都会增加形状。

输出应包含基于 的(0 或 1)个值数据值(输入数组)。如 数据值大于 5 返回 1 否则返回 0 .返回值必须加到输出

这是代码::

import numpy as np
import tensorflow as tf

data = np.random.randint(10, size=(30))
data = tf.constant(data, dtype= tf.float32)

global output
output= tf.constant([], dtype= tf.float32)
i = tf.constant(0)
c = lambda i: tf.less(i, 30)


def b(i):
i= tf.add(i,1)
cond= tf.cond(tf.greater(data[i-1], tf.constant(5.)), lambda: tf.constant(1.0), lambda: tf.constant([0.0]))
output =tf.expand_dims(cond, axis = i-1)
return i, output

r,out = tf.while_loop(c, b, [i])
print(out)
sess= tf.Session()
sess.run(out)

错误::

r, out = tf.while_loop(c, b, [i])

ValueError: The two structures don't have the same number of elements.

First structure (1 elements): [tf.Tensor 'while/Identity:0' shape=() dtype=int32]

Second structure (2 elements): [tf.Tensor 'while/Add:0' shape=() dtype=int32, tf.Tensor 'while/ExpandDims:0' shape=unknown dtype=float32>]



我用 tensorflow -1.1.3 python-3.5

如何更改我的代码以提供目标结果?

编辑::

我根据@mrry 的答案编辑了代码,但仍然存在输出不正确答案的问题
输出是数字总和
a = tf.ones([10,4])
print(a)
a = tf.reduce_sum(a, axis = 1)
i =tf.constant(0)
c = lambda i, _:tf.less(i,10)

def Smooth(x):
return tf.add(x,2)

summ = tf.constant(0.)
def b(i,_):
global summ
summ = tf.add(summ, tf.cast(Smooth(a[i]), tf.float32))
i= tf.add(i,1)
return i, summ

r, smooth_l1 = tf.while_loop(c, b, [i, smooth_l1])

print(smooth_l1)

sess = tf.Session()
print(sess.run(smooth_l1))

输出是 6.0 (错误的)。

最佳答案

tf.while_loop() function 要求以下四个列表具有相同的长度,并且每个元素的类型相同:

  • cond 的参数列表函数(在本例中为 c)。
  • body 的参数列表函数(在本例中为 b)。
  • 来自 body 的返回值列表功能。
  • loop_vars名单表示循环变量。

  • 因此,如果您的循环体有两个输出,则必须在 b 中添加相应的参数。和 c ,以及对应于 loop_vars 的元素:
    c = lambda i, _: tf.less(i, 30)

    def b(i, _):
    i = tf.add(i, 1)
    cond = tf.cond(tf.greater(data[i-1], tf.constant(5.)),
    lambda: tf.constant(1.0),
    lambda: tf.constant([0.0]))

    # NOTE: This line fails with a shape error, because the output of `cond` has
    # a rank of either 0 or 1, but axis may be as large as 28.
    output = tf.expand_dims(cond, axis=i-1)
    return i, output

    # NOTE: Use a shapeless `tf.placeholder_with_default()` because the shape
    # of the output will vary from one iteration to the next.
    r, out = tf.while_loop(c, b, [i, tf.placeholder_with_default(0., None)])

    正如评论中所指出的,循环的主体(特别是对 tf.expand_dims() 的调用)似乎不正确,该程序无法按原样运行,但希望这足以让您入门。

    关于tensorflow - Tensorflow 中的 while_loop 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46768386/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com