当前位置:首页 » python教程 » 正文

python 的topk算法实例

看: 1180次  时间:2020-07-25  分类 : python教程

我就废话不多说了,还是直接看代码吧!

#! 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)

补充知识:python numpy 求top-k accuracy指标

top-k acc表示在多分类情况下取最高的k类得分的label,与真实值匹配,只要有一个label match,结果就是True。

如对于一个有5类的多分类任务

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

对于top-1 accuracy

sklearn.metrics提供accuracy的方法,能够直接计算得分,但是对于topk-acc就需要自己实现了:

#5类:0,1,2,3,4
import numpy as np
a_real = np.array([[1], [2], [1], [3]])
#用随机数代替分数
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
#以下是计算方法
max_k_preds = a_pred_score.argsort(axis=1)[:, -k:][:, ::-1] #得到top-k label
match_array = np.logical_or.reduce(max_k_preds==a_real, axis=1) #得到匹配结果
topk_acc_score = match_array.sum() / match_array.shape[0]

以上这篇python 的topk算法实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持python博客。

标签:numpy  

<< 上一篇 下一篇 >>

搜索

推荐资源

  Powered By python教程网   鲁ICP备18013710号
python博客 - 小白学python最友好的网站!