gpt4 book ai didi

python - 交换矩阵行和列中的元素 - TensorFlow scatter_nd

转载 作者:太空宇宙 更新时间:2023-11-03 15:40:11 27 4
gpt4 key购买 nike

我正在尝试使用 scatter_nd TensorFlow 中的函数可对矩阵行中的元素进行重新排序。例如,假设我有代码:

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 的行进行重新排序矩阵。

我不仅想对行重新排序,还想对每行中的各个元素重新排序。如果我只有一个向量(秩为 1 的张量),则此示例有效:

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]

我真正关心的是能够交换 scatter1 中每一行中的元素,正如我在 scatter2 中所做的那样,但对 scatter1 的每一行执行此操作。我尝试过 indices 的各种组合但不断收到 scatter_nd 抛出的大小不一致的错误功能。

最佳答案

下面使用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]]

indices 中坐标的位置定义了 updates 中获取值的位置,实际坐标定义了将值放置在 scatter1 中的位置

这个答案晚了几个月,但希望仍然有帮助。

关于python - 交换矩阵行和列中的元素 - TensorFlow scatter_nd,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42207554/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com