gpt4 book ai didi

python - TensorFlow 使用 tf.while_loop() 陷入无限循环

转载 作者:行者123 更新时间:2023-11-28 20:18:10 24 4
gpt4 key购买 nike

重现步骤

我正在使用TensorFlow实现一个需要使用tf.while_loop()

的网络
import tensorflow as tf
import numpy as np
class model(object):
def __init__(self):
self.argmax_ep_gate_array = [ tf.placeholder(tf.int32, [None]) for _ in range(10)]
argmax_ep_gate_array_concat = tf.concat(0, self.argmax_ep_gate_array)
story_len = tf.constant(7)
starter = tf.constant(0)
z = []
def body(hops):
hops = tf.add(hops,1)
z.append(hops)
return hops
def condition(hops):
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 = tf.while_loop(condition,body,[starter])
self.z=tf.concat(0,z)

def step(self, sess):
feed={}
for i in range(10):
feed[self.argmax_ep_gate_array[i].name]=[i]
print (sess.run([self.gate_index,self.z],feed))
with tf.Session() as sess:
while_loop = model()
sess.run(tf.initialize_all_variables())
while_loop.step(sess)

你尝试了什么?

我发现如果我想 sess.run() body() 中未返回的任何变量,tensorflow 将陷入无限循环。上面的例子很简单,但它揭示了一些东西。在实际情况下,我正在使用 tf.while_loop() 运行一个 RNN,其中包括 y= wx+b 类似的东西,但是 wb 在 while 循环后不返回。在前向网络中,它工作正常。但是,如果我运行反向传播,程序就会陷入无限循环。我想上面的代码重现了我的问题,因为反向传播确实需要修改 wb。或者有什么办法可以处理这个问题?

最佳答案

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

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

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

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

关于python - TensorFlow 使用 tf.while_loop() 陷入无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37571017/

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