具有上限的 Scipy 泊松分布 [英] Scipy poisson distribution with an upper limit

查看:94
本文介绍了具有上限的 Scipy 泊松分布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 scipy stats 生成一个随机数.我使用了泊松分布.下面是一个例子:

I am generating a random number using scipy stats. I used the Poisson distribution. Below is an example:

import scipy.stats as sct

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

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

When I print Pos, I got the following numbers:

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

从数组中可以看出生成了一些数字,例如 6.

You can see from the array that some of the number,such as 6, is generated.

我想做什么来限制最大数(假设为 5),即使用 sct.poisson.rvs 生成的任何随机数都应等于或小于 5,

What I want to do it to limit the biggest number(let's say 5), i.e. any random number generated using sct.poisson.rvs should be equal or less than 5,

我如何调整我的代码来实现它.顺便说一下,我在 Pandas Dataframe 中使用了这个.

How can I tweak my code to achieve it. By the way, I am using this in Pandas Dataframe.

推荐答案

你想要的可以称为截断泊松分布,除了在这个术语的常见用法中,截断发生在下面从上面(示例).对截断分布进行采样的最简单(即使并不总是最有效)方法是将请求的数组大小加倍,并仅保留落在所需范围内的元素;如果不够,再放大一倍,以此类推,如下图:

What you want could be called the truncated Poisson distribution, except that in the common usage of this term, truncation happens from below instead of from above (example). The easiest, even if not always the most efficient, way to sample a truncated distribution is to double the requested array size and keep only the elements that fall in the desired range; if there are not enough, double the size again, etc. As shown below:

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

这篇关于具有上限的 Scipy 泊松分布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆