Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python TensorFlow使用tf.while_loop()卡在无限循环中 复制步骤_Python_Tensorflow - Fatal编程技术网

Python TensorFlow使用tf.while_loop()卡在无限循环中 复制步骤

Python TensorFlow使用tf.while_loop()卡在无限循环中 复制步骤,python,tensorflow,Python,Tensorflow,我正在使用TensorFlow实现一个需要使用tf.while\u loop() 你试过什么? 我发现如果我想要sess.run()body()中任何未返回的变量,tensorflow就会陷入无休止的循环中。 上面的例子微不足道,但它揭示了一些东西。在实际情况中,我使用tf.while\u loop()运行一个包含y=wx+b类似内容的RNN,但是w和b在while循环之后不会返回。在前向网络中,它工作良好。然而,如果我运行反向传播,程序将陷入无休止的循环。我假设上面的代码再现了我的问题,因为反

我正在使用TensorFlow实现一个需要使用
tf.while\u loop()

你试过什么? 我发现如果我想要sess.run()body()中任何未返回的变量,tensorflow就会陷入无休止的循环中。
上面的例子微不足道,但它揭示了一些东西。在实际情况中,我使用
tf.while\u loop()
运行一个包含y=wx+b类似内容的RNN,但是
w
b
在while循环之后不会返回。在前向网络中,它工作良好。然而,如果我运行反向传播,程序将陷入无休止的循环。我假设上面的代码再现了我的问题,因为反向传播确实需要修改
w
b
。或者有没有办法处理这个问题

TL;DR:不能存储在循环体中创建的张量以供以后使用,因为这打破了有关循环结构的一些假设

通常,
condition()
body()
函数不得有副作用。 实际上,您的程序不太可能具有预期的行为:TensorFlow将执行
body()
函数一次,以构建必要的图形结构,因此
z
在运行
model.\uuu init\uuu()
后将只包含一个元素

相反,您必须使用
tf.concat()
在循环体中增量构造
z
,并将值作为循环变量生成:

starter = tf.constant(0)
z_initial = tf.constant([], dtype=tf.int32)

def body(hops, z_prev):
    hops = tf.add(hops, 1)
    z_next = tf.concat(0, [z_prev, tf.expand_dims(hops, 0)])
    return hops, z_next
def condition(hops, z):
    return tf.logical_and(tf.less(tf.gather(
        argmax_ep_gate_array_concat, hops), story_len), tf.less(hops, tf.constant(20)))

self.gate_index, self.z = tf.while_loop(condition,body,[starter, z_initial])

谢谢还有3个问题。1.如果
self.z=tf.concat(0,z)
给出了类似
Nonetype
错误的错误,或者只包含一个值,我对结果没有意见,但在我的示例中,程序只是卡住了。2.My
body()
函数涉及许多可训练的参数,如重量、偏差、单元格。我是否需要将它们全部发送到
body()
函数并返回它们?3.
cell
是TensorFlow中的一个对象,如何将对象发送到
body()
.1。是的,这是令人遗憾的。找到一种避免这种错误的方法是值得的。2.
body()
函数可以隐式捕获封闭范围内的张量和变量,因此您可能可以使用此机制将它们放入循环中。3.我不确定你说的是什么
cell
,但你也可以在这里使用隐式捕获。我似乎在使用这种方法时遇到了问题。向前传递很好,但是当试图计算梯度时,似乎只看到一个值(最后一个),我得到了这个错误:值错误:形状(24,4,65)和(1,4,65)不兼容。这是预期的吗?@jstaker7,我能想到两件事:1。确保您的条件函数至少成功运行一次;2.检查身体功能,确保图表的完整性。希望这能帮助解决。@mrry我也有同样的问题(从github问题页面登陆这里)。我使用的是模拟组件(
mock.mock()
),会不会是那些充当副作用的东西?
starter = tf.constant(0)
z_initial = tf.constant([], dtype=tf.int32)

def body(hops, z_prev):
    hops = tf.add(hops, 1)
    z_next = tf.concat(0, [z_prev, tf.expand_dims(hops, 0)])
    return hops, z_next
def condition(hops, z):
    return tf.logical_and(tf.less(tf.gather(
        argmax_ep_gate_array_concat, hops), story_len), tf.less(hops, tf.constant(20)))

self.gate_index, self.z = tf.while_loop(condition,body,[starter, z_initial])