我的图表中需要一个条件控制流程.如果pred是True,则图形应该调用更新变量的op然后返回它,否则它将返回变量不变.简化版本是:
pred = tf.constant(True)
x = tf.Variable([1])
assign_x_2 = tf.assign(x, [2])
def update_x_2():
with tf.control_dependencies([assign_x_2]):
return tf.identity(x)
y = tf.cond(pred, update_x_2, lambda: tf.identity(x))
with tf.Session() as session:
session.run(tf.initialize_all_variables())
print(y.eval())
Run Code Online (Sandbox Code Playgroud)
不过,我觉得,无论pred=True并pred=False导致相同的结果y=[2],这意味着分配运算时也被称为update_x_2没有被选中tf.cond.怎么解释这个?以及如何解决这个问题?
当使用tensorflow的Dataset API Iterator时,我的目标是定义一个在迭代器的get_next()张量上操作的RNN 作为其输入(参见(1)代码).
但是,简单地将dynamic_rnnwith 定义get_next()为输入会导致错误:ValueError: Initializer for variable rnn/basic_lstm_cell/kernel/ is from inside a control-flow construct, such as a loop or conditional. When creating a variable inside a loop or conditional, use a lambda as the initializer.
现在我知道了一个解决方法是简单地创建了一个占位符next_batch,然后eval()张量(因为你无法通过自身张量),并用它传递feed_dict(见X并(2)在代码中).但是,如果我理解正确,这不是一个有效的解决方案,因为我们首先评估然后重新初始化张量.
有没有办法:
dynamic_rnn直接在迭代器的输出顶部定义;要么:
get_next()张量传递给占位符,这是输入dynamic_rnn?完整的工作实例; 该(1)版本是我想要的工作,但它没有,虽然(2)是可行的解决方法.
import tensorflow as tf
from tensorflow.contrib.rnn import BasicLSTMCell …Run Code Online (Sandbox Code Playgroud)