关于Kendall correlation coefficient的介绍可参见:
维基百科:https://en.wikipedia.org/wiki/Kendall_rank_correlation_coefficient
scipy库:https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.kendalltau.html
写了两个版本的代码:
import numpy as np
from scipy.stats import kendalltau
data = np.array([[0.7,0.2,0.5,0],
[0.6,0.1,0.1,0],
[0.8,0.2,0.3,0],
[0.6,0.3,0.5,0],
[0.5,0.4,0.2,1],
[0.4,0.5,0.3,1],
[0.5,0.6,0.3,1],
[0.4,0.5,0.1,1],
[0.2,0.9,0.4,2],
[0.2,1,0.6,2],
[0.2,0.8,0.5,2],
[0.1,1,0.1,2]])
Lens =len(data)
count = 0
for i in range(Lens-1):
for j in range(i+1,Lens):
count = count + np.sign(data[i][0] - data[j][0]) * np.sign(data[i][2] - data[j][2])
print('-----')
kendallCorrelation = count/((Lens*(Lens-1))/2)
kendallCorrelation_1,p_value = kendalltau(data[:,0],data[:,2])
print(kendallCorrelation)
print(kendallCorrelation_1)
from scipy.stats import kendalltau
import numpy as np
a = [1,2,3,4,5,6,7,8,9,10]
b = [4,7,2,10,3,6,8,1,5,9]
# a = [12,2,1,12,2]
# b = [1,4,7,1,0]
Lens = len(a)
count = 0
number = 0
for i in range(Lens-1):
for j in range(i+1,Lens):
count = count + np.sign(a[i] - a[j]) * np.sign(b[i] - b[j])
number += 1
Kendallta1 = count/(Lens*(Lens-1)/2)
Kendallta2,p_value = kendalltau(a,b)
print(number)
print(count)
print(Kendallta1)
print(Kendallta2)
结果为啥算出来不一样呢?【原因:自己写的是1938年的tau系数,scipy库里面的1945年版本的tau】
下面是1945年版本的代码:
from scipy.stats import kendalltau
import numpy as np
a = [1,1,2,2,5,5,8,8,9,10]
b = [2,7,2,3,3,6,8,4,5,5]
# a = [12,2,1,12,2]
# b = [1,4,7,1,0]
Lens = len(a)
ties_onlyin_x = 0
ties_onlyin_y = 0
con_pair = 0
dis_pair = 0
for i in range(Lens-1):
for j in range(i+1,Lens):
test_tying_x = np.sign(a[i] - a[j])
test_tying_y = np.sign(b[i] - b[j])
panduan =test_tying_x * test_tying_y
if panduan == 1:
con_pair +=1
elif panduan == -1:
dis_pair +=1
if test_tying_y ==0 and test_tying_x != 0:
ties_onlyin_y += 1
elif test_tying_x == 0 and test_tying_y !=0:
ties_onlyin_x += 1
Kendallta1 = (con_pair - dis_pair)/np.sqrt((con_pair + dis_pair + ties_onlyin_x)*(dis_pair +con_pair + ties_onlyin_y))
Kendallta2,p_value = kendalltau(a,b)
print(Kendallta1)
print(Kendallta2)
跑出来结果是一样的:
0.33737388489831593
0.33737388489831593