如何实现kolmogorov smirnov测试来提取适合我的数据的最佳分布



我在这里找到了关于如何输入链接描述的解释我需要在样本和每个分布之间比较基于Kolmogorov-Smirnov检验的分布。但我不知道如何解释结果,并根据这个测试选择最佳分布?此代码不实现Kolmogorov-Smirnov测试。因此1-如何实现Kolmokorov-Smirov测试?2-如何选择最佳分配?

def best_fit_distribution(data, bins=200, ax=None):
"""Model data by finding best fit distribution to data"""
# Get histogram of original data
y, x = np.histogram(data, bins=bins, density=True)
x = (x + np.roll(x, -1))[:-1] / 2.0
# Distributions to check
DISTRIBUTIONS = [st.alpha, st.anglit]
# Best holders
best_distribution = st.norm
best_params = (0.0, 1.0)
best_sse = np.inf
runs = []
# Estimate distribution parameters from data
for distribution in DISTRIBUTIONS:
# Try to fit the distribution
try:
# Ignore warnings from data that can't be fit
with warnings.catch_warnings():
warnings.filterwarnings('ignore')
# fit dist to data
params = distribution.fit(data)
print(params)
# Separate parts of parameters
arg = params[:-2]
print(arg)
loc = params[-2]
print(loc)
scale = params[-1]
print(scale)
# Calculate fitted PDF and error with fit in distribution
pdf = distribution.pdf(x, loc=loc, scale=scale, *arg)
sse = np.sum(np.power(y - pdf, 2.0))
# if axis pass in add to plot
try:
if ax:
pd.Series(pdf, x).plot(ax=ax)
end
except Exception:
pass
runs.append([distribution.name, sse])
# identify if this distribution is better
if best_sse > sse > 0:
best_distribution = distribution
best_params = params
best_sse = sse
except Exception:
pass
print(runs)
return (best_distribution.name, best_params)

首先,让我注意到您提供的源代码片段不包括Kolmogorov-Smirnov测试,而是进行参数MLE估计,然后计算误差平方和以选择最佳拟合。

为了回答你的第一个问题,让我展示一个关于scipy.stats:中正态分布的Kolmogorov-Smirnov拟合优度测试的例子

stats.kstest(samples, 'norm', args=(0, 1))

其中

  • 样本-收集/观察到的实验数据
  • "范数"-理论连续分布的预定义名称
  • args-理论分布的参数,在示例中为mean=0和std=1

因此,要对其他分布进行测试,只需要像上面例子中的正态分布一样,迭代所需的理论分布名称及其参数。

stats.kstest函数返回两个值:

  • D-a K-S统计
  • p值-零假设的p值样品取自所提供的理论分布

因此,要回答第二个问题,如果p值小于显著性值,则应拒绝测试。如果零假设不能被拒绝,那么你可以比较D值并选择具有最小D值的分布,因为它表示拟合优度:D值越小,它对数据的拟合越好。

最新更新