Python 中的肯德尔一致性系数 (W)

G.L*_*G.L 4 python statistics r function

我正在尝试根据我的数据计算肯德尔一致性系数(W)。有谁知道在 R 的“vegan”包中实现的 Python 包中的函数(http://cc.oulu.fi/~jarioksa/softhelp/vegan/html/kendall.global.html),包括排列测试?

Kendall 的 W 并不难计算,但我找不到可以将其与排列测试结合起来的 Python 函数。

Bil*_*ell 5

请注意:我感谢鲍里斯在这段代码中发现了错误。在计算的行中,S我无意中乘以了m而不是n

我也不知道有一个。但是,您可以通过这种方式计算 Python 中的排列测试。请注意,我没有在“W”公式中包含对绑定值的修正。

import numpy as np

def kendall_w(expt_ratings):
    if expt_ratings.ndim!=2:
        raise 'ratings matrix must be 2-dimensional'
    m = expt_ratings.shape[0] #raters
    n = expt_ratings.shape[1] # items rated
    denom = m**2*(n**3-n)
    rating_sums = np.sum(expt_ratings, axis=0)
    S = n*np.var(rating_sums)
    return 12*S/denom

the_ratings = np.array([[1,2,3,4],[2,1,3,4],[1,3,2,4],[1,3,4,2]])
m = the_ratings.shape[0]
n = the_ratings.shape[1]

W = kendall_w(the_ratings)

count = 0
for trial in range(1000):
    perm_trial = []
    for _ in range(m):
        perm_trial.append(list(np.random.permutation(range(1, 1+n))))
    count += 1 if kendall_w(np.array(perm_trial)) > W else 0

print ('Calculated value of W:', W, ' exceeds permutation values in', count, 'out of 1000 cases')
Run Code Online (Sandbox Code Playgroud)

在这种情况下,结果是,

Calculated value of W: 0.575  exceeds permutation values in 55 out of 1000 cases.
Run Code Online (Sandbox Code Playgroud)

您还应该注意,由于这些是随机排列,因此报告的值的数量会有一些变化。例如,在我进行的一项试验中,我认为 0.575 的计算值仅超过 1000 个案例中的 48 个。