Scipy 有上限的泊松分布

Scipy poisson distribution with an upper limit

我正在使用 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 中使用它。

您想要的可以称为截断泊松分布,除了在该术语的常见用法中,截断发生在下方而不是上方(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].

我认为解决方法很简单(假设我正确理解了你的问题):

# 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.]