python 的topk算法實(shí)例
我就廢話不多說了,還是直接看代碼吧!
#! 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)
補(bǔ)充知識(shí):python numpy 求top-k accuracy指標(biāo)
top-k acc表示在多分類情況下取最高的k類得分的label,與真實(shí)值匹配,只要有一個(gè)label match,結(jié)果就是True。
如對(duì)于一個(gè)有5類的多分類任務(wù)
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
對(duì)于top-1 accuracy
sklearn.metrics提供accuracy的方法,能夠直接計(jì)算得分,但是對(duì)于topk-acc就需要自己實(shí)現(xiàn)了:
#5類:0,1,2,3,4 import numpy as np a_real = np.array([[1], [2], [1], [3]]) #用隨機(jī)數(shù)代替分?jǐn)?shù) 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 #以下是計(jì)算方法 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) #得到匹配結(jié)果 topk_acc_score = match_array.sum() / match_array.shape[0]
以上這篇python 的topk算法實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
python隊(duì)列原理及實(shí)現(xiàn)方法示例
這篇文章主要介紹了python隊(duì)列原理及實(shí)現(xiàn)方法,結(jié)合實(shí)例形式詳細(xì)分析了Python隊(duì)列的概念、原理、定義及基本操作技巧,需要的朋友可以參考下2019-11-11

全網(wǎng)最簡(jiǎn)約的Anaconda+Python3.7安裝教程Win10

分享一下Python數(shù)據(jù)分析常用的8款工具

詳解Python使用apscheduler定時(shí)執(zhí)行任務(wù)

python 實(shí)現(xiàn)以相同規(guī)律打亂多組數(shù)據(jù)

python一維表轉(zhuǎn)二維表的實(shí)現(xiàn)示例

python pytorch中.view()函數(shù)的用法解讀