1. 程式人生 > 程式設計 >Python 按比例獲取樣本資料或執行任務的實現程式碼

Python 按比例獲取樣本資料或執行任務的實現程式碼

按比例獲取樣本資料或執行任務

By:授客 QQ:1033553122

開發環境

win 10

python 3.6.5

需求

已知每種分類的樣本佔比數,及樣本總數,需要按比例獲取這些分類的樣本。比如,我有4種任務要執行,分別為任務A,任務B,任務C,任務D,要求執行的總任務次數為100000,且不同分類任務執行次數佔比為 A:B:C:D = 3:5:7:9,且在巨集觀上這些任務同時進行

程式碼實現

#!/usr/bin/env python
# -*- coding:utf-8 -*-
 
 
__author__ = 'shouke'
 
import time
from copy import deepcopy
 
 
def main():
 
  class_propotion_map = {'A':3,'B':5,'C':7,'D':7} # 分類及樣本數比例對映
  class_list = [] # 分類
  class_proption_list = [] # 存放分類樣本數比例
 
  for class_type,propotion in class_propotion_map.items(): # 同一個迴圈,可以保證比例索引和對應分類索引一一對應
    class_list.append(class_type)
    class_proption_list.append(propotion)
 
  temp_class_propotion_list = deepcopy(class_proption_list)
  result = []
 
  t1 = time.time()
  total_sample_num = 100000 #任務執行次數
  for i in range(1,total_sample_num+1):
    max_propotion = max(temp_class_propotion_list)
    if max_propotion > 0:
      index = temp_class_propotion_list.index(max_propotion)
      result.append(class_list[index])
      temp_class_propotion_list[index] -= 1
    elif max_propotion == 0 and min(temp_class_propotion_list) == 0:
      temp_class_propotion_list = deepcopy(class_proption_list)
      index = temp_class_propotion_list.index(max(temp_class_propotion_list))
      result.append(class_list[index])
      temp_class_propotion_list[index] -= 1

  t2 = time.time()
  from collections import Counter
  c = Counter(result)
  for item in c.items():
    print(item[0],item[1]/total_sample_num)
  print('耗時:%s'%(t2-t1))
 
main()

執行結果

Python 按比例獲取樣本資料或執行任務的實現程式碼

說明

以上方式大致實現思路就是,獲取每種分類樣本數所佔比例副本資料列表,然後每次從中獲取最大比例值,並查詢該比例值對應的分類(獲取分類後就可以根據需要構造、獲取分類樣本資料),找到目標分類後,把比例資料副本中該比例值減1,直到最大比例和最小比例都等於0,接著重置比例副本資料為樣本數比例值,重複前面的過程,直到樣本數達到目標樣本總數,這種方式實現的前提是得提前知道樣本總數及不同分類樣本數所佔比例,且比例值為整數

到此這篇關於Python 按比例獲取樣本資料或執行任務的文章就介紹到這了,更多相關Python獲取樣本資料執行任務內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!