Home  >  Article  >  Backend Development  >  A brief overview of the usage of the argsort() function in Python

A brief overview of the usage of the argsort() function in Python

Y2J
Y2JOriginal
2017-04-22 09:15:212804browse

This article mainly introduces the usage examples of the argsort() function in python, and introduces the usage of the argsort() function in detail. It has certain reference value. Interested friends can refer to it.

Because I wanted to use python to use the trained caffemodel to batch classify many images. During the learning process, I encountered the argsort function, so I checked the relevant literature and tested it myself in the python environment. I roughly understand its related uses. In order to avoid forgetting it later, I wrote it down to deepen my understanding. (ps: I am also a Python novice, so my understanding may be relatively simple)

1. Define an array data first

import numpy as np
x=np.array([1,4,3,-1,6,9])

2. Now we can look at the specific functions of the argsort() function :

x.argsort()

The output is defined as y=array([3,0,2,1,4,5]).

We found that the argsort() function arranges the elements in x from small to large, extracts their corresponding index, and then outputs it to y. For example: x[3]=-1 is the smallest, so y[0]=3, x[5]=9 is the largest, so y[5]=5.

The above is not difficult to understand. If you are not familiar with it, you can try it yourself in the python environment.

3. Since I encountered a form similar to np.argsort()[num] in the program, I still couldn’t understand it, so I went to the python environment and tried it myself:

ps: The absolute value of num here is less than or equal to the number of elements in x

When num>=0, np.argsort()[num] can be understood as y[ num];

When num<0, np.argsort()[num] is to output the elements of array y in reverse , for example, np.argsort()[- 1] means to output the index corresponding to the largest value in x, np.argsort()[-2] means to output the index corresponding to the second largest value in x, and so on. .

Only through intuitive experiments can you see the effect. Here is my verification using the above example:

This is the output when num is a negative value.

This is the output when num>=0.

The above is the detailed content of A brief overview of the usage of the argsort() function in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn