pearson相关系数:用于判断数据是否线性相关的方法。
注意:不线性相关并不代表不相关,因为可能是非线性相关。
Python计算pearson相关系数:
1. 使用numpy计算(corrcoef),以下是先标准化再求相关系数
import numpy as np import pandas as pd aa = np.array([2,3,9,6,8]) bb = np.array([5,6,3,7,9]) cc = np.array([aa, bb]) print(cc) cc_mean = np.mean(cc, axis=0) #axis=0,表示按列求均值 ——— 即第一维 cc_std = np.std(cc, axis=0) cc_zscore = (cc-cc_mean)/cc_std #标准化 cc_zscore_corr = np.corrcoef(cc_zscore) #相关系数矩阵 print(cc_zscore_corr)
其中:
def corrcoef(x, y=None, rowvar=True, bias=np._NoValue, ddof=np._NoValue): """ Return Pearson product-moment correlation coefficients. Please refer to the documentation for `cov` for more detail. The relationship between the correlation coefficient matrix, `R`, and the covariance matrix, `C`, is .. math:: R_{ij} = \frac{ C_{ij} } { \sqrt{ C_{ii} * C_{jj} } } The values of `R` are between -1 and 1, inclusive. Parameters ---------- x : array_like A 1-D or 2-D array containing multiple variables and observations. Each row of `x` represents a variable, and each column a single observation of all those variables. Also see `rowvar` below.
2. 使用pandas计算相关系数
cc_pd = pd.DataFrame(cc_zscore.T, columns=['c1', 'c2']) cc_corr = cc_pd.corr(method='spearman') #相关系数矩阵
其中,method中,有三种相关系数的计算方式,包括 —— 'pearson', 'kendall', 'spearman',常用的是线性相关pearson。
Parameters ---------- method : {'pearson', 'kendall', 'spearman'} * pearson : standard correlation coefficient * kendall : Kendall Tau correlation coefficient * spearman : Spearman rank correlation
cc_corr 值可用于获取:某个因子与其他因子的相关系数:
print(cc_corr['c1']) #某个因子与其他因子的相关系数
附:pandas计算协方差
print(cc_pd.c1.cov(cc_pd.c2)) #协方差 print(cc_pd.c1.corr(cc_pd.c2)) #两个因子的相关系数 y_cov = cc_pd.cov() #协方差矩阵
3. 可直接计算,因为pearson相关系数的计算公式为:
cov(X,Y)表示的是协方差
var(x)和var(y)表示的是方差
##
参考:
https://www.jianshu.com/p/c83dd487df09
https://blog.csdn.net/liuchengzimozigreat/article/details/82989224