pytorch 张量根据列对行进行排序[重复]

问题描述 投票:0回答:3

在像这样的二维张量中

tensor([[0.8771, 0.0976, 0.8186],
        [0.7044, 0.4783, 0.0350],
        [0.4239, 0.8341, 0.3693],
        [0.5568, 0.9175, 0.0763],
        [0.0876, 0.1651, 0.2776]])

如何根据列中的值对行进行排序?例如,如果我们要根据最后一列进行排序,我希望这些行是这样的......

tensor([[0.7044, 0.4783, 0.0350],
        [0.5568, 0.9175, 0.0763],
        [0.0876, 0.1651, 0.2776],
        [0.4239, 0.8341, 0.3693],
        [0.8771, 0.0976, 0.8186]])

最后一列中的值现在按升序排列。

python sorting pytorch tensor
3个回答
2
投票
a = <your tensor>
ind = a[:,-1].argsort(dim=0)
a[ind]

argsort
“返回沿给定维度按值升序对张量进行排序的索引。”因此,基本上,您可以获得最后一列的排序索引,并根据这些索引对行重新排序。


2
投票
t = torch.rand(5, 3)
COL_INDEX_TO_SORT = 2

# sort() returns a tuple where first element is the sorted tensor 
# and the second is the indices of the sorted tensor.
# The [1] at the end is used to select the second element - the sorted indices.
sorted_indices = t[:, COL_INDEX_TO_SORT].sort()[1] 
t = t[sorted_indices]

0
投票

您可以使用排序函数和 lambda 函数,如下所示。排序键是列表中的最后一项,x[-1]

tensor = [[0.8771, 0.0976, 0.8186],
        [0.7044, 0.4783, 0.0350],
        [0.4239, 0.8341, 0.3693],
        [0.5568, 0.9175, 0.0763],
        [0.0876, 0.1651, 0.2776]]
sorted(tensor,key=lambda x: x[-1])


Result: 

 [[0.7044, 0.4783, 0.035],
 [0.5568, 0.9175, 0.0763],
 [0.0876, 0.1651, 0.2776],
 [0.4239, 0.8341, 0.3693],
 [0.8771, 0.0976, 0.8186]]
© www.soinside.com 2019 - 2024. All rights reserved.