Python計算皮爾遜 pearson相關系數


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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM