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就需要自己實現了:
#5類:0,1,2,3,4import numpy as npa_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 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算法實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章:
1. 將properties文件的配置設置為整個Web應用的全局變量實現方法2. docker compose idea CreateProcess error=2 系統找不到指定的文件的問題3. 一文秒懂idea的git插件跟翻譯插件4. PHP設計模式之迭代器模式Iterator實例分析【對象行為型】5. 在Vue 中獲取下拉框的文本及選項值操作6. python爬蟲利用代理池更換IP的方法步驟7. JS算法題解旋轉數組方法示例8. python中pandas.read_csv()函數的深入講解9. vue中使用echarts的示例10. JS中的常見數組遍歷案例詳解(forEach, map, filter, sort, reduce, every)
