python中topk算法的示例

发布时间:2021-03-11 09:40:05 作者:小新
来源:亿速云 阅读:199

这篇文章给大家分享的是有关python中topk算法的示例的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

直接看代码吧!

#! 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算法的示例”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

推荐阅读:
  1. PyTorch中topk函数的用法详解
  2. python中遗传算法的示例分析

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python topk算法

上一篇:Python基础类继承重写实现的示例

下一篇:Python第三方包之DingDingBot钉钉机器人

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》