绕晕大多数Python初学者的argsort()函数

绕晕大多数Python初学者的argsort()函数,第1张

使用python做机器学习的一般都是从k-近邻算法开始学习。

这就很难绕开argsort()函数,但是在使用argsort()函数时大部分初学者都会被绕晕进去。

argsort()函数是用来返回数组值从小到大索引值的。举例

那么

下面讲一下详细逻辑:

我们把矩阵a从小到大排序,记排序后的矩阵为b:

矩阵a和b的关系:

所以a.argsort(),也就是a排序后索引值就是[1,2,0]

PS:索引值相当于页数,是一个排序值,不等于元素的值。

像书的目录一样,对于例子中的矩阵,我们有如下索引:

6............0

4............1

5............2

所以排序后b=[4,5,6],用索引值来表达就是[1,2,0]

numpy.argsort( a , axis=-1 , kind='quicksort' , order=None )

Returns the indices that would sort an array.

Perform an indirect sort along the given axis using the algorithm specified by the kind keyword. It returns an array of indices of the same shape as a that index data along the given axis in sorted order.

Parameters:

a : array_like

Array to sort.

axis : int or None, optional

Axis along which to sort. The default is -1 (the last axis). If None, the flattened array is used.

kind : {‘quicksort’, ‘mergesort’, ‘heapsort’}, optional

Sorting algorithm.

order : str or list of str, optional

When a is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string, and not all fields need be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties.

Returns:

index_array : ndarray, int

Array of indices that sort a along the specified axis. If a is one-dimensional, a[index_array] yields a sorted a .

例1:


欢迎分享,转载请注明来源:夏雨云

原文地址:https://www.xiayuyun.com/zonghe/25555.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-02-17
下一篇2023-02-17

发表评论

登录后才能评论

评论列表(0条)

    保存