gpt4 book ai didi

python - 使用scipy对数正态分布拟合小值数据,然后在matplotlib中显示

转载 作者:行者123 更新时间:2023-12-05 03:03:32 25 4
gpt4 key购买 nike

我有一个数据集,其中包含从 0 到 1e-5 的值。我想数据可以用对数正态分布来描述。因此,我使用 scipy.stats.lognorm 来拟合我的数据,并希望使用 matplotlib 在同一图形上绘制原始数据和拟合分布。

首先,我按直方图绘制样本:
enter image description here

然后,我通过线图添加拟合分布。但是,这会将 Y 轴更改为非常大的数字:
enter image description here

所以图中看不到原始数据(sample)!

我检查了所有变量,发现变量 pdf_fitted 太大 (>1e7)。我真的不明白为什么将 scistats.lognorm.fit 简单拟合到由同一分布 scistats.lognorm.pdf 生成的样本不起作用。以下是演示我的问题的代码:

from matplotlib import pyplot as plt
from scipy import stats as scistats
import numpy as np

# generate a sample for x between 0 and 1e-5
x = np.linspace(0, 1e-5, num=1000)
y = scistats.lognorm.pdf(x, 3, loc=0, scale=np.exp(10))
h = plt.hist(y, bins=40) # plot the sample by histogram
# plt.show()

# fit the sample by using Log Normal distribution
param = scistats.lognorm.fit(y)
print("Log-normal distribution parameters : ", param)
pdf_fitted = scistats.lognorm.pdf(
x, *param[:-2], loc=param[-2], scale=param[-1])
plt.plot(x, pdf_fitted, label="Fitted Lognormal distribution")
plt.ticklabel_format(style='sci', scilimits=(-3, 4), axis='x')
plt.legend()
plt.show()

最佳答案

问题

您面临的直接问题是您的健康状况真的非常糟糕。如果您将图上的 x 和 y 比例设置为日志,您可以看到这一点,例如 plt.xscale('log')plt.yscale('log')。这使您可以在单个图上同时查看直方图和拟合数据:

enter image description here

所以它在两个方向上都偏离了许多数量级。

修复

您从 stats.lognorm 表示的概率分布生成样本并拟合它的整个方法是错误的。这是一种正确的方法,使用与您在问题中提供的对数范数分布相同的参数:

from matplotlib import pyplot as plt
from scipy import stats as scistats
import numpy as np

plt.figure(figsize=(12,7))
realparam = [.1, 0, np.exp(10)]

# generate pdf data around the mean value
m = realparam[2]
x = np.linspace(m*.6, m*1.4, num=10000)
y = scistats.lognorm.pdf(x, *realparam)

# generate a matching random sample
sample = scistats.lognorm.rvs(*realparam, size=100000)
# plot the sample by histogram
h = plt.hist(sample, bins=100, density=True)

# fit the sample by using Log Normal distribution
param = scistats.lognorm.fit(sample)
print("Log-normal distribution parameters : ", param)
pdf_fitted = scistats.lognorm.pdf(x, *param)
plt.plot(x, pdf_fitted, lw=5, label="Fitted Lognormal distribution")
plt.legend()
plt.show()

输出:

Log-normal distribution parameters :  (0.09916091013245995, -215.9562383088556, 22245.970148671593)

enter image description here

关于python - 使用scipy对数正态分布拟合小值数据,然后在matplotlib中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53838781/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com