我正在尝试根据我的数据计算 Kendall 一致性系数 (W)。有没有人知道在 Python 包中实现的函数,如在 R 的“纯素”包中(http://cc.oulu.fi/~jarioksa/softhelp/vegan/html/kendall.global.html),包括排列测试?
Kendall 的 W 不难计算,但我找不到一个 Python 函数可以将它与排列测试结合起来。
请您参考如下方法:
请注意:我很感谢 Boris 发现了这段代码中的错误。在计算 S 的行中,我无意中乘以了 m 而不是 n。
我也不知道。但是,您可以通过这种方式在 Python 中计算排列测试。请注意,我没有在“W”的公式中包括对绑定(bind)值的更正。
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')
在这种情况下,结果是,
Calculated value of W: 0.575 exceeds permutation values in 55 out of 1000 cases.
您还应注意,由于这些是随机排列,因此报告的值数量会有一些变化。例如,在我进行的一项试验中,我认为 0.575 的计算值超过 1000 个案例中的 48 个。
