python 的topk算法實例
我就廢話不多說了,還是直接看代碼吧!
#! 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)
補充知識:python numpy 求top-k accuracy指標
top-k acc表示在多分類情況下取最高的k類得分的label,與真實值匹配,只要有一個label match,結果就是True。
如對于一個有5類的多分類任務
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
對于top-1 accuracy
sklearn.metrics提供accuracy的方法,能夠直接計算得分,但是對于topk-acc就需要自己實現(xiàn)了:
#5類:0,1,2,3,4import numpy as npa_real = np.array([[1], [2], [1], [3]])#用隨機數(shù)代替分數(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#以下是計算方法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) #得到匹配結果topk_acc_score = match_array.sum() / match_array.shape[0]
以上這篇python 的topk算法實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。
相關文章:
1. 通過CSS數(shù)學函數(shù)實現(xiàn)動畫特效2. CSS3中Transition屬性詳解以及示例分享3. 阿里前端開發(fā)中的規(guī)范要求4. 低版本IE正常運行HTML5+CSS3網(wǎng)站的3種解決方案5. 利用CSS3新特性創(chuàng)建透明邊框三角6. XML入門的常見問題(二)7. CSS3實例分享之多重背景的實現(xiàn)(Multiple backgrounds)8. IE6/IE7/IE8/IE9中tbody的innerHTML不能賦值的完美解決方案9. XML入門的常見問題(一)10. 解析原生JS getComputedStyle
