【问题标题】:Change a single value of a tensor inside a while loop在 while 循环中更改张量的单个值
【发布时间】:2019-02-10 11:39:05
【问题描述】:

如何在 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])

【问题讨论】:

标签: python tensorflow


【解决方案1】:

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.]

【讨论】:

    猜你喜欢
    • 2020-04-17
    • 1970-01-01
    • 1970-01-01
    • 2019-04-28
    • 2018-06-05
    • 1970-01-01
    • 2016-11-12
    • 2013-09-13
    • 1970-01-01
    相关资源
    最近更新 更多