使用 np.argpartition 得到错误结果,同时从数组中选择最大 n 个值

Getting wrong results with np.argpartition, while selecting maximum n values from an array

所以我在 'How do I get indices of N maximum values in a NumPy array?' 问题上使用了 this 答案。我在我的 ML 模型中使用它,它输出 Logsoftmax 层值,我想在每个层值中获得前 4 类。在大多数情况下,它会正确排序并给出值,但在极少数情况下,我会看到部分未排序的结果,如下所示

arr = np.array([-3.0302, -2.7103, -7.4844, -3.4761, -5.3009, -5.2121, -3.7549, -4.7834,
     -5.8870, -3.4839, -5.0104, -3.0992, -4.8823, -0.3319, -6.8084])
ind = np.argpartition(arr, -4)[-4:]
print(arr[ind])

输出为

[-3.0992 -3.0302 -0.3319 -2.7103]

这是未排序的,它最后必须输出最大值,但在这种情况下没有看到。我检查了其他示例,一切正常。喜欢

arr = np.array([45, 35, 67.345, -34.5555, 66, -0.23655, 11.0001, 0.234444444])
ind = np.argpartition(arr, -4)[-4:]
print(arr[ind])

输出

[35.    45.    66.    67.345]

可能是什么原因?我错过了什么吗?

如果您不打算实际使用排序索引,为什么不直接使用 np.sort

>>> arr = np.array([-3.0302, -2.7103, -7.4844, -3.4761, -5.3009, -5.2121, -3.7549, 
              -4.7834, -5.8870, -3.4839, -5.0104, -3.0992, -4.8823, -0.3319, -6.8084])

>>> np.sort(arr)[-4:]
array([-3.0992, -3.0302, -2.7103, -0.3319])

或者, you could use a range for your kth option on np.argpartition

np.argpartition(arr, range(0, -4, -1))[-4:]
array([-3.0992, -3.0302, -2.7103, -0.3319])