How two rows can be swapped in a torch tensor?(如何在 Torch 张量中交换两行?)
问题描述
var = [[0, 1, -4, 8],[2, -3, 2, 1],[5, -8, 7, 1]]var = torch.Tensor(var)这里,var 是一个 3 x 4 (2d) 张量.如何交换第一行和第二行以获得以下二维张量?2, -3, 2, 10, 1, -4, 85, -8, 7, 1
解决方案 其他答案 不起作用,因为有些维度在复制之前被覆盖:
<预><代码>>>>var = [[0, 1, -4, 8],[2, -3, 2, 1],[5, -8, 7, 1]]>>>x = Torch.tensor(var)>>>index = torch.LongTensor([1, 0, 2])>>>x[索引] = x>>>X张量([[ 0, 1, -4, 8],[ 0, 1, -4, 8],[ 5, -8, 7, 1]])
对我来说,创建一个新的张量(具有单独的底层存储)来保存结果就足够了:
<预><代码>>>>x = Torch.tensor(var)>>>index = torch.LongTensor([1, 0, 2])>>>y = torch.zeros_like(x)>>>y[索引] = x或者,您可以使用 index_copy_
(遵循 discuss.pytorch.org),尽管目前我认为这两种方式都没有优势.
var = [[0, 1, -4, 8],
[2, -3, 2, 1],
[5, -8, 7, 1]]
var = torch.Tensor(var)
Here, var
is a 3 x 4 (2d) tensor. How the first and second row can be swapped to get the following 2d tensor?
2, -3, 2, 1
0, 1, -4, 8
5, -8, 7, 1
The other answer does not work, as some dimensions get overwritten before they are copied:
>>> var = [[0, 1, -4, 8],
[2, -3, 2, 1],
[5, -8, 7, 1]]
>>> x = torch.tensor(var)
>>> index = torch.LongTensor([1, 0, 2])
>>> x[index] = x
>>> x
tensor([[ 0, 1, -4, 8],
[ 0, 1, -4, 8],
[ 5, -8, 7, 1]])
For me, it suffices to create a new tensor (with separate underlying storage) to hold the result:
>>> x = torch.tensor(var)
>>> index = torch.LongTensor([1, 0, 2])
>>> y = torch.zeros_like(x)
>>> y[index] = x
Alternatively, you can use index_copy_
(following this explanation in discuss.pytorch.org), although I don't see an advantage for either way at the moment.
这篇关于如何在 Torch 张量中交换两行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!