如何在 while 循环中更改张量的单个值?
我知道我可以使用 tf.scatter_update(variable, index, value)
操作 tf.Variable
的单个值,但在循环内我无法访问变量。有没有一种方法/解决方法可以在 while 循环内操作 Tensor
的给定值。
作为引用,这是我当前的代码:
my_variable = tf.Variable()
def body(i, my_variable):
[...]
return tf.add(i, 1), tf.scatter_update(my_variable, [index], value)
loop = tf.while_loop(lambda i, _: tf.less(i, 5), body, [0, my_variable])
最佳答案
灵感来自 this post您可以使用稀疏张量将增量存储到您要分配的值,然后使用加法来“设置”该值。例如。像这样(我在这里假设了一些形状/值,但将它推广到更高级别的张量应该是直截了当的):
import tensorflow as tf
my_variable = tf.Variable(tf.ones([5]))
def body(i, v):
index = i
new_value = 3.0
delta_value = new_value - v[index:index+1]
delta = tf.SparseTensor([[index]], delta_value, (5,))
v_updated = v + tf.sparse_tensor_to_dense(delta)
return tf.add(i, 1), v_updated
_, updated = tf.while_loop(lambda i, _: tf.less(i, 5), body, [0, my_variable])
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(sess.run(my_variable))
print(sess.run(updated))
这打印
[1. 1. 1. 1. 1.]
[3. 3. 3. 3. 3.]
关于python - 在 while 循环中更改张量的单个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54615979/