用值填充张量中的特定索引

Fill a specific index in tensor with a value

我是张量流的初学者。 我创建了这个张量

z = tf.zeros([20,2], tf.float32)

我想将索引 z[2,1]z[2,2] 的值更改为 1.0 而不是零。 我该怎么做?

完全问的是不可能的,原因有二:

  • z是常数张量,不可改变
  • 没有z[2,2],只有z[2,0]z[2,1]

但假设您想将 z 更改为变量并修复索引,可以这样完成:

z = tf.Variable(tf.zeros([20,2], tf.float32))  # a variable, not a const
assign21 = tf.assign(z[2, 0], 1.0)             # an op to update z
assign22 = tf.assign(z[2, 1], 1.0)             # an op to update z

with tf.Session() as sess:
  sess.run(tf.global_variables_initializer())
  print(sess.run(z))                           # prints all zeros
  sess.run([assign21, assign22])
  print(sess.run(z))                           # prints 1.0 in the 3d row

一个简单的方法:

import numpy as np
import tensorflow as tf

init = np.zeros((20,2), np.float32)
init[2,1] = 1.0
z = tf.variable(init)

或使用tf.scatter_update(ref, indices, updates) https://www.tensorflow.org/api_docs/python/tf/scatter_update

实现此目的的更好方法是使用 tf.sparse_to_dense.

tf.sparse_to_dense(sparse_indices=[[0, 0], [1, 2]],
                   output_shape=[3, 4],
                   default_value=0,
                   sparse_values=1,
                   )

输出:

[[1, 0, 0, 0]
 [0, 0, 1, 0]
 [0, 0, 0, 0]]

但是,tf.sparse_to_dense 最近已弃用。因此,使用 tf.SparseTensor and then use tf.sparse.to_dense 得到与上面相同的结果

这个问题的 Tensorflow 2.x 解决方案如下所示:

import tensorflow as tf

z = tf.zeros([20,2], dtype=tf.float32)

index1 = [2, 0]
index2 = [2, 1]

result = tf.tensor_scatter_nd_update(z, [index1, index2], [1.0, 1.0])
tf.print(result)
[[0 0]
 [0 0]
 [1 1]
 ...
 [0 0]
 [0 0]
 [0 0]]