2 回答

TA贡献1946条经验 获得超3个赞
事实证明,正如弗拉德所指出的那样,所缺少的只是一个不能在循环内分配变量的事实。相反,可以返回变量的新值。
def make_update_op(w):
return w + 0.001
new_w = tf.while_loop(lambda _: True, make_update_op, (weights,), maximum_iterations=x.shape[0])
update_op = weights.assign(new_w)
要使用更多变量,需要从函数返回相同数量并在 Python 中解压缩它们,但原理是相同的。
def make_update_op(w, d):
return w + 0.001, d
new_w, _ = tf.while_loop(lambda *_: True, make_update_op, (weights, data), maximum_iterations=x.shape[0])
update_op = weights.assign(new_w)

TA贡献2080条经验 获得超4个赞
您尝试在 while 循环中分配新值的张量是多个操作张量序列的结果(操作是图中的节点,而张量是有向边)。特别是,while 循环将产生:
Variable/Read-->while/Enter-->while/Merge-->while/Switch-->while/Identity
您要在这里分配的是一个 tensor while/Identity。
tf.while_loop通常用于迭代张量的维度(也在 None- 未知维度上)。您正在尝试迭代完全定义的变量。你不需要为此创建一个tf.while_loop。只需创建更新每个变量的操作并将这些操作组合在一起:
update_ops = [w.assign(w + 0.001) for w in weights]
update_op = tf.group(update_ops)
现在,当您执行update_opwithtf.Session()接口时,它将更新所有变量。
例子:
import tensorflow as tf
v1 = tf.Variable(tf.ones((1, 2), dtype=tf.float32))
v2 = tf.Variable(2*tf.ones((1, 3), dtype=tf.float32))
update_ops = [w.assign(w + 0.001) for w in [v1, v2]]
update_op = tf.group(update_ops)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print('before update:')
print(v1.eval(), v2.eval())
print('after update:')
sess.run(update_op) # <-- update your variables
print(v1.eval(), v2.eval())
# before update:
# [[1. 1.]] [[2. 2. 2.]]
# after update:
# [[1.001 1.001]] [[2.001 2.001 2.001]]
添加回答
举报