用scipy拟合伽玛分布中的位置参数

时间:2016-09-05 12:19:15

标签: python scipy distribution gamma

有人能够向我解释如何在Scipy中使用location参数和gamma.fit函数吗?

在我看来,位置参数(μ)将分布的支持从x≥0改变为y =(x-μ)≥0。如果μ为正,那么我们不会丢失所有数据不满足x - μ≥0?

谢谢!

1 个答案:

答案 0 :(得分:6)

fit函数在找到拟合时会考虑所有数据。为数据添加噪声将改变拟合参数,并且可以提供不能很好地表示数据的分布。因此,当我们使用fit时,我们必须要有点聪明。

以下是使用numpy生成数据y1loc=2scale=1的一些代码。它还会在0到10的范围内为数据添加噪声,以创建y2。拟合y1可以产生出色的效果,但尝试拟合嘈杂的y2是有问题的。我们添加的噪音抹掉了分布。但是,我们还可以在拟合数据时保持一个或多个参数不变。在这种情况下,我们将floc=2传递给fit,这会强制在执行拟合时将位置保持在2,从而返回更好的结果。

from scipy.stats import gamma
import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0,10,.1)
y1 = np.random.gamma(shape=1, scale=1, size=1000) + 2  # sets loc = 2 
y2 = np.hstack((y1, 10*np.random.rand(100)))  # add noise from 0 to 10

# fit the distributions, get the PDF distribution using the parameters
shape1, loc1, scale1 = gamma.fit(y1)
g1 = gamma.pdf(x=x, a=shape1, loc=loc1, scale=scale1)

shape2, loc2, scale2 = gamma.fit(y2)
g2 = gamma.pdf(x=x, a=shape2, loc=loc2, scale=scale2)

# again fit the distribution, but force loc=2
shape3, loc3, scale3 = gamma.fit(y2, floc=2)
g3 = gamma.pdf(x=x, a=shape3, loc=loc3, scale=scale3)

制作一些情节......

# plot the distributions and fits.  to lazy to do iteration today
fig, axes = plt.subplots(1, 3, figsize=(13,4))
ax = axes[0]
ax.hist(y1, bins=40, normed=True);
ax.plot(x, g1, 'r-', linewidth=6, alpha=.6)
ax.annotate(s='shape = %.3f\nloc = %.3f\nscale = %.3f' %(shape1, loc1, scale1), xy=(6,.2))
ax.set_title('gamma fit')

ax = axes[1]
ax.hist(y2, bins=40, normed=True);
ax.plot(x, g2, 'r-', linewidth=6, alpha=.6)
ax.annotate(s='shape = %.3f\nloc = %.3f\nscale = %.3f' %(shape2, loc2, scale2), xy=(6,.2))
ax.set_title('gamma fit with noise')

ax = axes[2]
ax.hist(y2, bins=40, normed=True);
ax.plot(x, g3, 'r-', linewidth=6, alpha=.6)
ax.annotate(s='shape = %.3f\nloc = %.3f\nscale = %.3f' %(shape3, loc3, scale3), xy=(6,.2))
ax.set_title('gamma fit w/ noise, location forced')

enter image description here

相关问题