Python tf.cond:向列表中添加元素
我需要一个非常简单的图中的条件控制流,它可以将元素添加到列表中。在我的例子中,应该使用Python tf.cond:向列表中添加元素,python,tensorflow,Python,Tensorflow,我需要一个非常简单的图中的条件控制流,它可以将元素添加到列表中。在我的例子中,应该使用tf.Variable([])声明列表 我收到一个奇怪的错误:UnboundLocalError:在赋值之前引用了局部变量“list1” 以下是一个玩具示例: pred = tf.placeholder(tf.bool, shape=[]) list1 = tf.Variable([]) def f1(): e1 = tf.constant(1.0) list1 = tf.concat([list1,
tf.Variable([])
声明列表
我收到一个奇怪的错误:UnboundLocalError:在赋值之前引用了局部变量“list1”
以下是一个玩具示例:
pred = tf.placeholder(tf.bool, shape=[])
list1 = tf.Variable([])
def f1():
e1 = tf.constant(1.0)
list1 = tf.concat([list1, [e1]], 0)
def f2():
e2 = tf.constant(2.0)
list1 = tf.concat([list1, [e2]], 0)
y = tf.cond(pred, f1, f2)
with tf.Session() as session:
session.run(tf.global_variables_initializer())
print(y.eval(feed_dict={pred: False})) # ==> [1]
print(y.eval(feed_dict={pred: True})) # ==> [2]
获取具有这些参数的现有变量或创建新变量
因此,这种模式避免了您面临的问题
除此之外,我必须在关闭形状验证后使用这一行,因为这会导致验证错误
list1 = tf.assign( list1, tf.concat([list1, [e1]], 0), validate_shape=False)
工作代码是这样的
def f1():
with tf.variable_scope("reuse", reuse=tf.AUTO_REUSE):
list1 = tf.get_variable(initializer=[], dtype=tf.float32, name='list1')
e1 = tf.constant(1.)
print(tf.shape(list1))
list1 = tf.assign( list1, tf.concat([list1, [e1]], 0), validate_shape=False)
return list1
def f2():
with tf.variable_scope("reuse", reuse=tf.AUTO_REUSE):
list1 = tf.get_variable( dtype=tf.float32, name='list1')
e2 = tf.constant(2.)
list1 = tf.assign( list1, tf.concat([list1, [e2]], 0), validate_shape=False)
return list1
y = tf.cond(pred, f1, f2)
with tf.Session() as session:
with tf.variable_scope("reuse", reuse=tf.AUTO_REUSE):
session.run(tf.global_variables_initializer())
print(session.run([y], feed_dict={pred: False})) # ==> [1]
print(session.run([y], feed_dict={pred: True})) # ==> [2]
# Gets the updated variable
list1 = tf.get_variable(dtype=tf.float32, name='list1')
print(session.run(list1))
这张照片
[array([2.], dtype=float32)]
[array([2., 1.], dtype=float32)]
[2. 1.]