这是一个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])