1. 程式人生 > >np.random.choice:概率不等於1

np.random.choice:概率不等於1

這是一個known issue與numpy。使用給定的容差為概率之和隨機選擇功能檢查(here the source

的解決方案是通過將它們除以它們的總和如果總和是足夠接近1

實施例歸一化的概率:

>>> p=[ 1.42836755e-01, 1.42836735e-01 , 1.42836735e-01, 1.42836735e-01 
, 4.76122449e-05, 1.42836735e-01 , 4.76122449e-05 , 1.42836735e-01, 
    1.42836735e-01, 4.79122449e-05] 
>>> sum(p) 
1.0000003017347 # over tolerance limit 
>>> np.random.choice([1,2,3,4,5,6,7,8,9, 10], 4, p=p, replace=False) 

Traceback (most recent call last): 
    File "<pyshell#23>", line 1, in <module> 
    np.random.choice([1,2,3,4,5,6,7,8,9, 10], 4, p=p, replace=False) 
    File "mtrand.pyx", line 1417, in mtrand.RandomState.choice (numpy\random\mtrand\mtrand.c:15985) 
ValueError: probabilities do not sum to 1 

隨著歸一化:

>>> p = np.array(p) 
>>> p /= p.sum() # normalize 
>>> np.random.choice([1,2,3,4,5,6,7,8,9, 10], 4, p=p, replace=False) 
array([8, 4, 1, 6])