Pearson相关系数与Spearman相关系数

import numpy as np
data = np.array([[10,10,8,9,7],[4,5,4,3,3],[3,3,1,1,1]])
data
array([[10, 10,  8,  9,  7],
       [ 4,  5,  4,  3,  3],
       [ 3,  3,  1,  1,  1]])
#行与行之间的相关系数
np.corrcoef(data)
array([[1.        , 0.64168895, 0.84016805],
       [0.64168895, 1.        , 0.76376262],
       [0.84016805, 0.76376262, 1.        ]])
#计算个列之间的相关系数
np.corrcoef(data,rowvar=0)
array([[1.        , 0.98898224, 0.9526832 , 0.9939441 , 0.97986371],
       [0.98898224, 1.        , 0.98718399, 0.99926008, 0.99862543],
       [0.9526832 , 0.98718399, 1.        , 0.98031562, 0.99419163],
       [0.9939441 , 0.99926008, 0.98031562, 1.        , 0.99587059],
       [0.97986371, 0.99862543, 0.99419163, 0.99587059, 1.        ]])
#相关系数显著性检验
import numpy as np
import scipy.stats as stats
import scipy

x=[10.35,6.24,3.18,8.46,3.21,7.65,4.32,8.66,9.12,10.31]
y=[5.1,3.15,1.67,4.33,1.76,4.11,2.11,4.88,4.99,5.12]

correlation,pvalue = stats.stats.pearsonr(x,y)
print("correlation:",correlation)
print("pvalue:",pvalue)

correlation: 0.9891763198690562
pvalue: 5.926875946481138e-08
 

#spearman相关系数,方式一
x=[10.35,6.24,3.18,8.46,3.21,7.65,4.32,8.66,9.12,10.31]
y=[5.1,3.15,1.67,4.33,1.76,4.11,2.11,4.88,4.99,5.12]
correlation,pvalue = stats.spearmanr(x,y)
print("correlation:",correlation)
print("pvalue:",pvalue)
correlation: 0.9878787878787878
pvalue: 9.307459988955517e-08
#spearman相关系数,方式二
x = scipy.stats.stats.rankdata(x)
y = scipy.stats.stats.rankdata(y)
print(x,y)
correlation,pvalue = scipy.stats.spearmanr(x,y)
print("correlation:",correlation)
print("pvalue:",pvalue)
[10.  4.  1.  6.  2.  5.  3.  7.  8.  9.] [ 9.  4.  1.  6.  2.  5.  3.  7.  8. 10.]
correlation: 0.9878787878787878
pvalue: 9.307459988955517e-08

你可能感兴趣的:(概率论与数理统计)