1 # -*- coding: utf-8 -*-
2 """
3 Created on Mon Jan 8 19:36:48 2018
4
5 @author: markli
6 """
7
8 import numpy as np;
9 import math;
10
11 '''
12 计算矩阵A的相关系数矩阵
13 '''
14 def Correlation(A):
15 #得到A的形状 m 是行数 n 是列数
16 m,n = A.shape;
17 #存放每一列的均值
18 means = [];
19 #存放每一列的方差
20 var = [];
21 for i in range(n):
22 me = np.mean(A[:,i]);
23 means.append(me);
24 temp = A[:,i] - me;
25 #计算方差,除以m-1 与np.corrcoef有误差,除以m则基本没有误差
26 v = np.sum([p**2 for p in temp]) / m ;
27 var.append(v);
28
29 #存放相关系数
30 r = np.ones((n,n));
31 #离差矩阵
32 deviation = A - np.atleast_2d(means);
33
34 for i in range(n):
35 for j in range(n):
36 cov = np.dot(np.atleast_2d(deviation[:,i]),np.atleast_2d(deviation[:,j]).T)/ (m);
37 va = math.sqrt(var[i] * var[j]);
38 r[i,j] = cov / va;
39 if(i==j):
40 r[i,j]=1;
41
42 return r;
43 #coeffs = np.ployfit(X,Y,degree) #得到一组回归方程的系数 X为一维,Y一般为一维,最多二维 degree指定自变量的次数
44 #np.ploy1d(coeffs) 产生一个多项式 多项式次数由高到低
45 A = np.random.random((10,3));
46 r1 = Correlation(A);
47 r2 = np.corrcoef(A,rowvar=False);
48 print(r1);
49 print('numpy 计算值:');
50 print(r2);
51
52