Scipy lognorm拟合直方图

时间:2017-01-30 16:23:50

标签: python scipy normal-distribution

我将lognormal pdf拟合到某些分箱数据,但我的曲线与数据不完全匹配,请参见下图。我的代码是:

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

data = genfromtxt('data.txt')
data = np.sort(data)

# plot histogram in log space

ax.hist(data, bins=np.logspace(0,5,200),normed=1)
ax.set_xscale("log")

shape,loc,scale = lognorm.fit(data)

print shape, loc, scale

pdf = sp.stats.lognorm.pdf(data, shape, loc, scale)

ax.plot(data,pdf)

plt.show()

这就是它的样子:

enter image description here

我是否需要以某种方式为形状,位置和比例提供合理的猜测?

谢谢!

1 个答案:

答案 0 :(得分:5)

您尝试拟合的数据看起来不像对数正态分布。当以对数x标度绘制时,对数正态分布应该看起来像正态分布。您显示的情节不是这种情况。如果分布不适合数据,则会得到奇怪的参数。

在尝试适应某些内容之前,您需要了解您的数据是如何真正分发的(严格来说,这些内容在SO处是偏离主题的)。

这是我们在使用从对数正态分布中随机抽取的数据时得到的结果:

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

np.random.seed(42)

data = lognorm.rvs(s=0.5, loc=1, scale=1000, size=1000)

# plot histogram in log space
ax = plt.subplot(111)
ax.hist(data, bins=np.logspace(0,5,200),normed=1)
ax.set_xscale("log")

shape,loc,scale = lognorm.fit(data)

x = np.logspace(0, 5, 200)
pdf = lognorm.pdf(x, shape, loc, scale)

ax.plot(x, pdf, 'r')

plt.show()

histogram and PDF of lognorm distribution look like normal distribution when the x-axis is logarithmic