如何用索引替换张量内的值?

时间:2017-03-19 05:56:43

标签: tensorflow

以下代码通过索引向张量内的特定位置添加内容(感谢@ mrry的答案here)。

indices = [[1, 1]]  # A list of coordinates to update.
values = [1.0]  # A list of values corresponding to the respective
            # coordinate in indices.
shape = [3, 3]  # The shape of the corresponding dense tensor, same as `c`.
delta = tf.SparseTensor(indices, values, shape)

例如,鉴于此 -

c = tf.constant([[0.0, 0.0, 0.0],
             [0.0, 0.0, 0.0],
             [0.0, 0.0, 0.0]])

它会在[1,1]处加1,导致

[[0.0, 0.0, 0.0],
[0.0, 1.0, 0.0],
[0.0, 0.0, 0.0]])

问题 - 是否可以替换特定位置的值而不是在该位置添加?如果在tensorflow中不可能,是否可以在任何其他类似的库中使用?

例如,

鉴于此 -

[[4.0, 43.1.0, 45.0],
[2.0, 22.0, 6664.0],
[-4543.0, 0.0, 43.0]])

有没有办法用(例如)45替换[1,1]的22,导致下面的?

[[4.0, 43.1.0, 45.0],
[2.0, 45.0, 6664.0],
[-4543.0, 0.0, 43.0]])

1 个答案:

答案 0 :(得分:0)

这很笨重,但确实取代了张量中的值。它基于您提到的this answer

# inputs
inputs = tf.placeholder(shape = [None, None], dtype = tf.float32)  # tensor with values to replace
indices = tf.placeholder(shape = [None, 2], dtype = tf.int64)  # coordinates to be updated
values = tf.placeholder(shape = [None], dtype = tf.float32)  # values corresponding to respective coordinates in "indices"

# set elements in "indices" to 0's
maskValues = tf.tile([0.0], [tf.shape(indices)[0]])  # one 0 for each element in "indices"
mask = tf.SparseTensor(indices, maskValues, tf.shape(inputs, out_type = tf.int64))
maskedInput = tf.multiply(inputs, tf.sparse_tensor_to_dense(mask, default_value = 1.0))  # set values in coordinates in "indices" to 0's, leave everything else intact

# replace elements in "indices" with "values"
delta = tf.SparseTensor(indices, values, tf.shape(inputs, out_type = tf.int64))
outputs = tf.add(maskedInput, tf.sparse_tensor_to_dense(delta))  # add "values" to elements in "indices" (which are 0's so far)

它的作用:

  1. 将输入元素设置在需要替换为0的位置。
  2. 将所需的值添加到这些0(这是直接来自here)。
  3. 通过运行检查:

    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        ins = np.array([[4.0, 43.0, 45.0], [2.0, 22.0, 6664.0], [-4543.0, 0.0, 43.0]])
        ind = [[1, 1]]
        vals = [45]
        outs = sess.run(outputs, feed_dict = { inputs: ins, indices: ind, values: vals })
        print(outs)
    

    输出:

    [[ 4.000e+00  4.300e+01  4.500e+01]
     [ 2.000e+00  4.500e+01  6.664e+03]
     [-4.543e+03  0.000e+00  4.300e+01]]
    

    与许多otherwise great answers不同,此版本超出tf.Variable() s。