How to apply numpy random.choice to a matrix of probability values (Vectorized solution)

后端 未结 1 1596
终归单人心
终归单人心 2020-12-18 06:51

The problem I have is as follows

I have a 1-D list of integers (or np.array) with 3 values

l = [0,1,2]

I have a 2-D list of probabi

相关标签:
1条回答
  • 2020-12-18 07:37

    Here's one way.

    Here's the array of probabilities:

    In [161]: p
    Out[161]: 
    array([[ 0.8 ,  0.1 ,  0.1 ],
           [ 0.3 ,  0.3 ,  0.4 ],
           [ 0.25,  0.5 ,  0.25]])
    

    c holds the cumulative distributions:

    In [162]: c = p.cumsum(axis=1)
    

    Generate a set of uniformly distributed samples...

    In [163]: u = np.random.rand(len(c), 1)
    

    ...and then see where they "fit" in c:

    In [164]: choices = (u < c).argmax(axis=1)
    
    In [165]: choices
    Out[165]: array([1, 2, 2])
    
    0 讨论(0)
提交回复
热议问题