無法避免的使用多次循環完成指定概率分布抽樣。
加速的方法是通過numba 的jit來進行。
但是numba不支持choice的指定概率p的用法。
所以需要尋找choice用法的替代方案。
網上查出:https://www.pythonheidong.com/blog/article/147920/
def weighted_random(w, n): cumsum = np.cumsum(w) rdm_unif = np.random.rand(n) return np.searchsorted(cumsum, rdm_unif)
可以嘗試。
經過嘗試成功:
@jit(nopython=True) def weighted_random(w, n): cumsum = np.cumsum(w) rdm_unif = np.random.rand(n) return np.searchsorted(cumsum, rdm_unif) @jit(nopython=True) def pirandom2(rate,det,pha): pilist=[] for i,phai in enumerate(pha): pitemp = weighted_random(rate[det[i]][phai],1) pilist.append(pitemp[0]) #print i,det[i],phai,pitemp return pilist #####下方代碼無法執行#####因為numba不支持choice的p用法####### @jit(nopython=True) def pirandom(rate,det,pha): pilist=[] for i,phai in enumerate(pha): pilist.append(np.random.choice(256, 1, p=rate[det[i]][phai])) print i,det[i],phai,pilist[i] return pilist