对数据拟合对数正态分布并在 Python 和 R 中执行 Kolmogorov-Smirnov 检验

Fitting a lognormal distribution to the data and performing Kolmogorov-Smirnov test in Python and R

我将我的数据拟合为对数正态分布,并且我在 Python 和 R 中进行了 KS 测试,我得到了非常不同的结果。

数据为:

series
341 291 283 155 271 270 250 272 209 236 295 214 443 632 310 334 376 305 216 339

在 R 中,代码是:

fit = fitdistr(series, "lognormal")$estimate
fit
meanlog
5.66611754205579
sdlog
0.290617205700481
ks.test(series, "plnorm", meanlog=fit[1], sdlog=fit[2], exact=TRUE)
One-sample Kolmogorov-Smirnov test

data:  series
D = 0.13421, p-value = 0.8181
alternative hypothesis: two-sided

在Python中的代码是:

distribution = stats.lognorm
args = distribution.fit(series)
args
(4.2221814852591635, 154.99999999212395, 0.45374242945626875)
stats.kstest(series, distribution.cdf, args, alternative = 'two-sided')
KstestResult(statistic=0.8211678552361514, pvalue=2.6645352591003757e-15)

对数正态分布的 SciPy 实现与 R 代码中的参数化方式不同。在 Whosebug 上搜索 [scipy] lognorm 这里有许多类似的问题,并查看 lognorm 文档字符串中关于参数化的说明。另请注意,要匹配 R 结果,必须使用参数 floc=0 将位置参数 loc 固定为值 0。 R 实现不包含位置参数。

这是一个脚本,展示了如何获得 R 报告的相同值:

import numpy as np
from scipy.stats import lognorm, kstest


x = [341, 291, 283, 155, 271, 270, 250, 272, 209, 236,
     295, 214, 443, 632, 310, 334, 376, 305, 216, 339]


sigma, loc, scale = lognorm.fit(x, floc=0)

mu = np.log(scale)

print("mu    = %9.5f" % mu)
print("sigma = %9.5f" % sigma)

stat, p = kstest(x, 'lognorm', args=(sigma, 0, scale), alternative='two-sided')
print("KS Test:")
print("stat    = %9.5f" % stat)
print("p-value = %9.5f" % p)

输出:

mu    =   5.66612
sigma =   0.29062
KS Test:
stat    =   0.13421
p-value =   0.86403

SciPy 中的 kstest 函数没有计算精确 p 值的选项。要将其值与 R 进行比较,可以使用 exact=FALSE in fitdistr:

> ks.test(series, "plnorm", meanlog=fit[1], sdlog=fit[2], exact=FALSE)

    One-sample Kolmogorov-Smirnov test

data:  series
D = 0.1342, p-value = 0.864
alternative hypothesis: two-sided