0

我需要在win7上的Python 3.2中生成截断的伽玛分布pdf曲线和直方图。

import numpy as np
import matplotlib.pyplot as plt
import scipy.special as sps

shape, scale = 2., 2. # mean and dispersion
counter =0
s = []
upper_bound = 4
lower_bound  = 0.5
while (counter <= 1000):
    t = np.random.gamma(shape, scale, 1)
    if (lower_bound <= t <= upper_bound) :   
       s.append(t)
       counter += 1 

 count, bins, ignored = plt.hist(s, 50, normed=True)

 // this part take s very long time
 y = bins**(shape-1)*(np.exp(-bins/scale) /
                  (sps.gamma(shape)*scale**shape))

 plt.plot(bins, y, linewidth=2, color='r')
 plt.show()

我发现以下代码需要很长时间,并且弹出的图形窗口变得无响应。

"y = bins**(shape-1)*(np.exp(-bins/scale)/(sps.gamma(shape)*scale**shape))"

如果我删除伽马分布的下限和上限,它会运行得非常快。

任何帮助,将不胜感激。

4

1 回答 1

1

np.random.gamma您不应该需要size=1参数一致,您只需要一个浮点数,所以只需执行以下操作:

t = np.random.gamma(shape, scale)

目前需要很长时间,因为t您生成的每个数组都是一个包含 1 个元素的数组,而您s的数组是一个大型嵌套数组

你在while循环中所做的已经截断了你的分布!虽然更快的方法是获得你想要的范围,即将你的整个while循环替换为:

t = np.random.gamma(shape, scale, 1000) # 1000 entries in a gamma distribution
s = filter( lambda x: upper_bound>x>lower_bound, t ) # get entries within bounds
于 2014-03-14T00:28:00.743 回答