在 python 中每小时创建 Poission 到达的一天的请求数

create number of requests for a day having Poission arrival on an hourly basis in python

假设我们有一项服务,有 # 个请求,我们每小时添加这些请求,例如 12-11-2 等。所以我想做的是生成这些泊松到达后的请求数量,然后将其添加到表示一周中某天的字典中

 monday = [hour_range, number_of_clients_in_that_hour]

然后在最后,我们将根据 Mon to Sunday 命名这 7 个字典,并且可以使用一些线性回归来预测给定一天的下一个小时的客户数量。

所以基本上,当我在 python 中模拟这种情况时,我需要到达代表这种情况。我有以下代码,使用它我使用均匀分布生成 # of clients in an hour 。对于泊松到达或任何其他真正代表这种情况的到达,我该怎么做?我的代码如下

day_names = ['mon','tue','wed','thurs','fri','sat','sun']

time_values = np.linspace(1,23,23,dtype='int') # print from 1,2...23

for day_iterator in range(1,7+1): 

     number_of_clients = [] # create empty list that will hold number of clients
        for i in range(1,24,1): #  lets create no. of clients for a day on an hourly basis in this for loop
            rand_value =  random.randint(1,20) # generate number of clients

            number_of_clients.append(rand_value)  # append the number of clients to this list

        # a single day data is generated after this for
        locals() [day_names[day_iterator-1]] = dict(zip(time_values,number_of_clients)) # create dict for each day of a week


    # print each day
    print "monday = %s"%mon
    print "tuesday = %s"%tue
    print "wed = %s"%wed
    print "thurs = %s"%thurs
    print "fri = %s"%fri
    print "sat = %s"%sat
    print "sun = %s"%sun

    plt.plot(mon.keys(),mon.values())

泊松过程(使用通常的简化假设)的到达间隔时间呈指数分布。那么在这种建模工作中,经常使用的是到达间隔时间而不是父进程。

下面介绍了如何使用著名的 Python 库计算泊松过程中每小时的计数。请注意泊松参数的倒数中的 scale

>>> def hourly_arrivals(scale=1):
...     count = 0
...     while expon.rvs(scale=scale, size=1) < 1:
...         count += 1
...     return count
... 
>>> hourly_arrivals()
0
>>> hourly_arrivals()
8
>>> hourly_arrivals()
0
>>> hourly_arrivals()
1
>>> hourly_arrivals()
4
>>> hourly_arrivals()
0
>>> hourly_arrivals()
2

您还询问了 'any other arrival which truly represents such scenario'。这是一个经验问题。我会说,为您正在研究的系统收集尽可能多的稳态到达间隔时间,并尝试为它们拟合累积分布函数。如果您想对此进行讨论,请提出另一个问题。

阻力最小的方法是使用 numpy 中的内置泊松发生器。 但是,如果您想自己动手,可以使用以下代码:

import math
import random

def poisson(rate):
    x = 0
    product = random.random()
    threshold = math.exp(-rate)
    while product >= threshold:
        product *= random.random()
        x += 1

    return x

这是基于泊松事件的到达间隔时间呈指数分布这一事实,因此您可以 generate exponentials 直到它们的总和超过您指定的速率。不过,这个实现稍微聪明一些——通过对 summation/threshold 关系的两边取幂,对数求和变成简单的乘法,结果可以与预先计算的取幂阈值进行比较。这在代数上与指数随机变量的总和相同,但它执行单个求幂和 lambda 乘法的平均值,而不是对 lambda 对数求值的平均值求和。

最后,无论您使用哪种发电机,您都需要知道费率。请记住,poisson 在法语中是鱼的意思,prob & stats 中最糟糕的笑话之一是语句 "the Poisson scales." 这意味着只需将小时费率乘以 24,即可将小时费率转换为日费率,即一天中的几个小时。例如,如果您平均每小时有 3 个,那么您每天平均有 72 个。