【问题标题】:KS test: R vs PythonKS 测试:R 与 Python
【发布时间】:2021-04-14 07:11:18
【问题描述】:

我在 R 和 Python 中得到不同的 KS 测试值。

input_test = [2457.145, 878.081, 855.118, 1157.135, 1099.82, 880.0, 1399.0339999999999]

R 代码:

> parameters
 meanlog    sdlog 
9.621626 2.220691 

H <- 846.6572

truncgof::ks.test(input_test, 'plnorm', parameters, H=H, sim=50)

R 输出:

data:  input_test
KS = 2.3246, p-value < 2.2e-16
alternative hypothesis: two.sided

treshold = 846.6572, simulations: 50

Python 代码:

import scipy.stats as st
p = [ 2.22096211e+00, 1.50686480e+04]
ks = st.kstest(input_test, st.lognorm.cdf, args=([p[0], 0, p[1])]), N=50, alternative='two-sided')

Python 输出:

KstestResult(statistic=0.7929187086107005, pvalue=3.34390068700874e-05)

有人知道如何获得相同(或相似)的结果吗?是否可以在 Python 中设置阈值(R 中的 H)?

【问题讨论】:

    标签: python r scipy statistics


    【解决方案1】:

    试试下面的。 它使用包 truncdist 创建截断的对数正态分布函数,然后使用基 R ks.test 运行 KS 测试。结果与您的 Python 结果相似但不完全相同。

    library(truncdist)
    
    ptrunclnorm <- function(x, H, ...){
      truncdist::ptrunc(x, spec = "lnorm", a = H, b = Inf, ...)
    }
    
    input_test = c(2457.145, 878.081, 855.118, 1157.135, 1099.82, 880.0, 1399.0339999999999)
    H <- 846.6572
    meanlog <- 9.621626 
    sdlog <- 2.220691
    
    parameters <- c(meanlog, sdlog)
    
    set.seed(2020)
    truncgof::ks.test(input_test, 'plnorm', parameters, H=H, sim=50)
    
    ks.test(input_test, "ptrunclnorm", H = H, meanlog = meanlog, sdlog = sdlog)
    #
    #   One-sample Kolmogorov-Smirnov test
    #
    #data:  input_test
    #D = 0.8786, p-value = 7.771e-07
    #alternative hypothesis: two-sided
    

    EnvStats 具有截断对数正态分布的函数,因此不需要定义它。

    library(EnvStats)
    
    ks.test(input_test, "plnormTrunc", 
            meanlog = meanlog, sdlog = sdlog, 
            min = H, max = Inf)
    

    输出同上。

    【讨论】:

    • 那么 Python 在计算 KS 时会截断数据集吗?是否有可能在 Python 中得到与 R 结果相似的结果
    • @ruan 不,这不是 Python 传递给scipy.stats.kstest 的截断对数正态分布。
    • @ruanNo,你没看懂我写的东西。 Python 确实使用截断分布,R 代码使用。
    猜你喜欢
    • 2021-06-12
    • 1970-01-01
    • 1970-01-01
    • 2016-09-25
    • 2017-12-26
    • 2013-05-30
    • 1970-01-01
    • 2014-01-31
    • 2018-05-15
    相关资源
    最近更新 更多