argsort¶
对输入变量沿给定轴进行排序,输出排序好的数据的相应索引,其维度和输入相同。默认升序排列,如果需要降序排列设置 descending=True
。
参数¶
x (Tensor) - 输入的多维
Tensor
,支持的数据类型:float16、bfloat16、float32、float64、int16、int32、int64、uint8。axis (int,可选) - 指定对输入 Tensor 进行运算的轴,
axis
的有效范围是 [-R, R),R 是输入x
的 Rank,axis
为负时与axis
+ R 等价。默认值为 -1。descending (bool,可选) - 指定算法排序的方向。如果设置为 True,算法按照降序排序。如果设置为 False 或者不设置,按照升序排序。默认值为 False。
stable (bool,可选) - 是否使用稳定排序算法。若设置为 True,则使用稳定排序算法,即相同元素的顺序在排序结果中将会被保留。默认值为 False,此时的算法不一定是稳定排序算法。
name (str,可选) - 具体用法请参见 Name,一般无需设置,默认值为 None。
返回¶
Tensor,排序后索引信息(与 x
维度信息一致),数据类型为 int64。
代码示例¶
>>> import paddle
>>> x = paddle.to_tensor([[[5,8,9,5],
... [0,0,1,7],
... [6,9,2,4]],
... [[5,2,4,2],
... [4,7,7,9],
... [1,7,0,6]]],
... dtype='float32')
>>> out1 = paddle.argsort(x, axis=-1)
>>> out2 = paddle.argsort(x, axis=0)
>>> out3 = paddle.argsort(x, axis=1)
>>> print(out1)
Tensor(shape=[2, 3, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
[[[0, 3, 1, 2],
[0, 1, 2, 3],
[2, 3, 0, 1]],
[[1, 3, 2, 0],
[0, 1, 2, 3],
[2, 0, 3, 1]]])
>>> print(out2)
Tensor(shape=[2, 3, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
[[[0, 1, 1, 1],
[0, 0, 0, 0],
[1, 1, 1, 0]],
[[1, 0, 0, 0],
[1, 1, 1, 1],
[0, 0, 0, 1]]])
>>> print(out3)
Tensor(shape=[2, 3, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
[[[1, 1, 1, 2],
[0, 0, 2, 0],
[2, 2, 0, 1]],
[[2, 0, 2, 0],
[1, 1, 0, 2],
[0, 2, 1, 1]]])
>>> x = paddle.to_tensor([1, 0]*40, dtype='float32')
>>> out1 = paddle.argsort(x, stable=False)
>>> out2 = paddle.argsort(x, stable=True)
>>> print(out1)
Tensor(shape=[80], dtype=int64, place=Place(cpu), stop_gradient=True,
[55, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 1 , 57, 59, 61,
63, 65, 67, 69, 71, 73, 75, 77, 79, 17, 11, 13, 25, 7 , 3 , 27, 23, 19,
15, 5 , 21, 9 , 10, 64, 62, 68, 60, 58, 8 , 66, 14, 6 , 70, 72, 4 , 74,
76, 2 , 78, 0 , 20, 28, 26, 30, 32, 24, 34, 36, 22, 38, 40, 12, 42, 44,
18, 46, 48, 16, 50, 52, 54, 56])
>>> print(out2)
Tensor(shape=[80], dtype=int64, place=Place(cpu), stop_gradient=True,
[1 , 3 , 5 , 7 , 9 , 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35,
37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71,
73, 75, 77, 79, 0 , 2 , 4 , 6 , 8 , 10, 12, 14, 16, 18, 20, 22, 24, 26,
28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62,
64, 66, 68, 70, 72, 74, 76, 78])