具有上限的Scipy泊松分布

时间:2018-09-19 05:45:56

标签: python scipy statistics poisson

我正在使用scipy统计信息生成一个随机数。 我使用了泊松分布。 下面是一个示例:

import scipy.stats as sct

A =2.5
Pos = sct.poisson.rvs(A,size = 20)

在打印Pos时,我得到以下数字:

array([1, 3, 2, 3, 1, 2, 1, 2, 2, 3, 6, 0, 0, 4, 0, 1, 1, 3, 1, 5])

您可以从数组中看到生成了一些数字,例如6。

我想做的是限制最大数量(比如说5),即使用sct.poisson.rvs生成的任何随机数应等于或小于5,

如何调整代码以实现它。 顺便说一下,我正在Pandas Dataframe中使用它。

2 个答案:

答案 0 :(得分:2)

我认为解决方案非常简单(假设我正确理解了您的问题):

# for repeatability:
import numpy as np
np.random.seed(0)

from scipy.stats import poisson, uniform
sample_size = 20
maxval = 5
mu = 2.5

cutoff = poisson.cdf(maxval, mu)
# generate uniform distribution [0,cutoff):
u = uniform.rvs(scale=cutoff, size= sample_size)
# convert to Poisson:
truncated_poisson = poisson.ppf(u, mu)

然后print(truncated_poisson)

[2. 3. 3. 2. 2. 3. 2. 4. 5. 2. 4. 2. 3. 4. 0. 1. 0. 4. 3. 4.]

答案 1 :(得分:1)

您想要的可以被称为截断的Poisson分布,只是在该术语的常用用法中,截断从下方而不是从上方(example)发生。对截断分布进行采样的最简单(即使并非总是最有效)的方法是将请求的数组大小加倍,并仅将落入所需范围内的元素保持在原位;如果不够,请再次将大小再加倍,依此类推。如下所示:

import scipy.stats as sct

def truncated_Poisson(mu, max_value, size):
    temp_size = size
    while True:
        temp_size *= 2
        temp = sct.poisson.rvs(mu, size=temp_size)
        truncated = temp[temp <= max_value]
        if len(truncated) >= size:
            return truncated[:size]

mu = 2.5
max_value = 5
print(truncated_Poisson(mu, max_value, 20))

典型输出:[0 1 4 5 0 2 3 2 2 2 5 2 3 3 3 3 4 1 0 3]

相关问题