numpy random choice的替代方案


无法避免的使用多次循环完成指定概率分布抽样。

加速的方法是通过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

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM