问题描述
我正在尝试在TensorFlow中使用 scatter_nd 函数来对矩阵行中的元素进行重新排序.例如,假设我有以下代码:
I am trying to use the scatter_nd function in TensorFlow to reorder elements within rows of a Matrix. For example, suppose I have the code:
indices = tf.constant([[1],[0]])
updates = tf.constant([ [5, 6, 7, 8],
[1, 2, 3, 4] ])
shape = tf.constant([2, 4])
scatter1 = tf.scatter_nd(indices, updates, shape)
$ print(scatter1) = [[1,2,3,4]
[5,6,7,8]]
这将重新排列updates
矩阵的行.
This reorders the rows of the updates
matrix.
我不仅希望对行进行重新排序,还希望对每行中的各个元素也进行重新排序.如果我只有一个向量(秩为1的张量),则此示例有效:
Instead of only being able to reorder the rows, I'd like to reorder the individual elements within each row as well. If I just have a vector (Tensor of rank 1), then this example works:
indices = tf.constant([[1],[0],[2],[3]])
updates = tf.constant([5, 6, 7, 8])
shape = tf.constant([4])
scatter2 = tf.scatter_nd(indices, updates, shape)
$ print(scatter2) = [6,5,7,8]
我真正关心的是能够像在scatter2
中那样在scatter1
的每一行中交换元素,但是要在scatter1
的每一行中进行交换.我已经尝试过indices
的各种组合,但是不断收到错误消息,提示scatter_nd
函数会抛出大小不一致的错误.
What I really care about is to be able to swap elements within each row in scatter1
, as I had done in scatter2
, but do it for each row of scatter1
. I've tried various combinations of indices
but keep getting errors that the sizes are inconsistent thrown by the scatter_nd
function.
推荐答案
以下内容使用scatter_nd
The following swaps the elements of each row of each row using scatter_nd
indices = tf.constant([[[0, 1], [0, 0], [0, 2], [0, 3]],
[[1, 1], [1, 0], [1, 2], [1, 3]]])
updates = tf.constant([ [5, 6, 7, 8],
[1, 2, 3, 4] ])
shape = tf.constant([2, 4])
scatter1 = tf.scatter_nd(indices, updates, shape)
with tf.Session() as sess:
print(sess.run(scatter1))
提供以下内容的输出:[[6 5 7 8] [2 1 3 4]]
Giving an output of:[[6 5 7 8] [2 1 3 4]]
indices
中坐标的位置定义了在updates
中取值的位置,而实际坐标定义了将值放置在scatter1
中的位置.
The locations of the coordinate in indices
define where the values are being taken from in updates
and the actual cordinates define where the values will be placed in scatter1
.
这个答案已经晚了几个月,但希望仍然会有所帮助.
This answer is a few months late but hopefully still helpful.
这篇关于在矩阵行和列中交换元素-TensorFlow scatter_nd的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!