zoukankan      html  css  js  c++  java
  • 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
     
  • 相关阅读:
    8-6实战蒙版
    8-5渐变及半透明蒙版
    8-4修改蒙版
    8-3建立蒙版
    imageNamed、imageWithContentsOfFile、imageWithData
    #import、#include、@class、@protocol、@interface
    JSON解析
    控制器的生命周期
    纯代码方式实现九宫格布局
    KVC笔记
  • 原文地址:https://www.cnblogs.com/heshangaichirou/p/13041537.html
Copyright © 2011-2022 走看看