皮尔逊相关系数的计算(python代码版)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
from
math
import
sqrt
def
multipl(a,b):
sumofab
=
0.0
for
i
in
range
(
len
(a)):
temp
=
a[i]
*
b[i]
sumofab
+
=
temp
return
sumofab
def
corrcoef(x,y):
n
=
len
(x)
#求和
sum1
=
sum
(x)
sum2
=
sum
(y)
#求乘积之和
sumofxy
=
multipl(x,y)
#求平方和
sumofx2
=
sum
([
pow
(i,
2
)
for
i
in
x])
sumofy2
=
sum
([
pow
(j,
2
)
for
j
in
y])
num
=
sumofxy
-
(
float
(sum1)
*
float
(sum2)
/
n)
#计算皮尔逊相关系数
den
=
sqrt((sumofx2
-
float
(sum1
*
*
2
)
/
n)
*
(sumofy2
-
float
(sum2
*
*
2
)
/
n))
return
num
/
den
x
=
[
0
,
1
,
0
,
3
]
y
=
[
0
,
1
,
1
,
1
]
print
corrcoef(x,y)
#0.471404520791
http://www.cnblogs.com/ryuham/p/4764015.html
|