python - 在 while 循环中更改张量的单个值

标签 python tensorflow

如何在 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/

相关文章:

python - seaborn 中 kdeplot x 轴的范围与 data 中的不同

python - 由tensorflow中的索引张量指定的切片2d张量

python - Pytorch 相当于 `tf.reverse_sequence` ?

python - 如何在 emacs 中使 ropemacs 更快?

python - 如何在另一个类中使用一个类的自变量

tensorflow - 将 ResNeXt 导入 Keras

python - 如何将 NumPy 数组图像转换为 TensorFlow 图像?

python - tensorflow 估计器 : feature columns size error in 1. 5

python - 沿 numpy 数组轴的 k-最小值的索引

python - 如何根据数据框和 numpy 中的协变量对观察结果进行分类?