Python's topk algorithm example

I won't talk too much nonsense, let's just look at the code!

#! conding:utf-8

def quick_index(array, start, end):
 left, right = start, end
 key = array[left]while left < right:while left < right and array[right]   key:
 right -=1
 array[left]= array[right]while left < right and array[left]< key:
 left +=1
 array[right]= array[left]

 array[left]= key
 return left

def min_num(array, m):
 start, end =0,len(array)-1
 index =quick_index(array, start, end)while index != m:if index < m:
 index =quick_index(array, index+1, end)else:
 index =quick_index(array, start, index)print(array[:m])if __name__ =='__main__':
 alist =[15,54,26,93,17,77,31,44,55,20]min_num(alist,5)

Supplementary knowledge: python numpy for top-k accuracy index

top-k acc means that the label with the highest k score is taken in the case of multi-classification and matches the true value. As long as there is a label match, the result is True.

For example, for a multi-classification task with 5 categories

a_real =1
a_pred =[0.02,0.23,0.35,0.38,0.02]

# top-1 
a_pred_label =3 match = False
# top-3
a_pred_label_list =[1,2,3] match = True

For top-1 accuracy

sklearn.metrics provides an accuracy method that can directly calculate the score, but for topk-acc, you need to implement it yourself:

#5 Class: 0, 1, 2, 3, 4 import numpy as np
a_real = np.array([[1],[2],[1],[3]])
# Use random numbers instead of scores
random_score = np.random.rand((4,5))
a_pred_score = random_score / random_score.sum(axis=1).reshape(random_score.shape[0],1)

k =3 #top-3
# The following is the calculation method
max_k_preds = a_pred_score.argsort(axis=1)[:,-k:][:,::-1] #Get top-k label
match_array = np.logical_or.reduce(max_k_preds==a_real, axis=1) #Get matching results
topk_acc_score = match_array.sum()/ match_array.shape[0]

The above example of python's topk algorithm is all the content shared by the editor. I hope to give you a reference.

Recommended Posts

Python&#39;s topk algorithm example