如何用索引替换张量中的值? [英] How to replace a value within a tensor by indices?
问题描述
以下代码通过索引向张量内的特定位置添加内容(感谢@mrry 的回答 此处).
The below code add something to a specific location within a tensor by indices (thanks to @mrry's answer 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,结果是
It'll add 1 at [1, 1], resulting in
[[0.0, 0.0, 0.0],
[0.0, 1.0, 0.0],
[0.0, 0.0, 0.0]])
问题 - 是否可以替换特定位置的值而不是在该位置添加值?如果在 tensorflow 中不可能,那么在任何其他类似的库中是否可能?
Question - Is it possible to replace the value at a specific location instead of adding at that location? If it's not possible in tensorflow, is it possible in any other similar libraries?
例如
鉴于此 -
[[4.0, 43.1.0, 45.0],
[2.0, 22.0, 6664.0],
[-4543.0, 0.0, 43.0]])
有没有办法将 [1, 1] 处的 22 替换为(比如说)45,从而得到以下结果?
Is there a way to replace the 22 at [1, 1] with (say) 45, resulting in the below?
[[4.0, 43.1.0, 45.0],
[2.0, 45.0, 6664.0],
[-4543.0, 0.0, 43.0]])
推荐答案
这很笨拙,但它确实替换了张量中的值.它基于您提到的这个答案.
This is clunky, but it does replace values in a tensor. It's based on this answer that you mentioned.
# 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)
它的作用:
- 在需要替换为 0 的位置设置输入元素.
- 向这些 0 添加所需的值(直接来自此处).
运行检查:
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]]
不像许多否则 tf.Variable()
s.
Unlike many otherwise great answers out there, this one works beyond tf.Variable()
s.
这篇关于如何用索引替换张量中的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!