在矩阵行和列中交换元素-TensorFlow scatter_nd [英] Swapping elements within a matrix rows and columns - TensorFlow scatter_nd

查看:335
本文介绍了在矩阵行和列中交换元素-TensorFlow scatter_nd的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆