python 的topk算法實(shí)例
我就廢話不多說了,還是直接看代碼吧!
#! conding:utf-8def 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 leftdef 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 = 1a_pred = [0.02, 0.23, 0.35, 0.38, 0.02]#top-1 a_pred_label = 3 match = False#top-3a_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,4import numpy as npa_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 labelmatch_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í)例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. ASP基礎(chǔ)入門第四篇(腳本變量、函數(shù)、過程和條件語句)2. ASP將數(shù)字轉(zhuǎn)中文數(shù)字(大寫金額)的函數(shù)3. jscript與vbscript 操作XML元素屬性的代碼4. JSP開發(fā)之hibernate之單向多對(duì)一關(guān)聯(lián)的實(shí)例5. php使用正則驗(yàn)證密碼字段的復(fù)雜強(qiáng)度原理詳細(xì)講解 原創(chuàng)6. HTML5實(shí)戰(zhàn)與剖析之觸摸事件(touchstart、touchmove和touchend)7. 基于PHP做個(gè)圖片防盜鏈8. jsp 實(shí)現(xiàn)的簡易mvc模式示例9. XML在語音合成中的應(yīng)用10. PHP session反序列化漏洞超詳細(xì)講解
