科披 : 对数正态分布拟合

2024-04-26 00:34:20 发布

您现在位置:Python中文网/ 问答频道 /正文

有很多关于用Scipy处理lognorm分布的帖子,但是我仍然没有掌握它的窍门。

2参数lognormal通常由参数\mu\sigma来描述,它们对应于Scipysloc=0\sigma=shape\mu=np.log(scale)

scipy, lognormal distribution - parameters,我们可以阅读如何使用随机分布的指数生成lognorm(\mu,\sigma)样本。现在让我们尝试其他方法:

(一)

直接创建lognorm有什么问题:

# lognorm(mu=10,sigma=3)
# so shape=3, loc=0, scale=np.exp(10) ?
x=np.linspace(0.01,20,200)
sample_dist = sp.stats.lognorm.pdf(x, 3, loc=0, scale=np.exp(10))
shape, loc, scale = sp.stats.lognorm.fit(sample_dist, floc=0)
print shape, loc, scale
print np.log(scale), shape # mu and sigma
# last line: -7.63285693379 0.140259699945  # not 10 and 3

(二)

我使用拟合的返回值来创建拟合分布。但显然我又做错了:

samp=sp.stats.lognorm(0.5,loc=0,scale=1).rvs(size=2000) # sample
param=sp.stats.lognorm.fit(samp) # fit the sample data
print param # does not coincide  with shape, loc, scale above!
x=np.linspace(0,4,100)
pdf_fitted = sp.stats.lognorm.pdf(x, param[0], loc=param[1], scale=param[2]) # fitted distribution
pdf = sp.stats.lognorm.pdf(x, 0.5, loc=0, scale=1) # original distribution
plt.plot(x,pdf_fitted,'r-',x,pdf,'g-')
plt.hist(samp,bins=30,normed=True,alpha=.3)

lognorm


Tags: samplepdfparamstatsnpsigmalocsp
2条回答

我意识到我的错误:

A)我正在绘制的示例需要来自.rvs方法。就像这样: sample_dist = sp.stats.lognorm.rvs(3, loc=0, scale=np.exp(10), size=2000)

B)配合有问题。当我们修正loc参数时,拟合效果会好得多。 param=sp.stats.lognorm.fit(samp, floc=0)

我也做了同样的观察:所有参数的自由拟合在大多数情况下都是失败的。您可以通过提供更好的初始猜测来提供帮助,无需修复参数。

samp = stats.lognorm(0.5,loc=0,scale=1).rvs(size=2000)

# this is where the fit gets it initial guess from
print stats.lognorm._fitstart(samp)

(1.0, 0.66628696413404565, 0.28031095750445462)

print stats.lognorm.fit(samp)
# note that the fit failed completely as the parameters did not change at all

(1.0, 0.66628696413404565, 0.28031095750445462)

# fit again with a better initial guess for loc
print stats.lognorm.fit(samp, loc=0)

(0.50146296628099118, 0.0011019321419653122, 0.99361128537912125)

您还可以自己构造函数来计算初始猜测,例如:

def your_func(sample):
    # do some magic here
    return guess

stats.lognorm._fitstart = your_func

相关问题 更多 >