• 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

  • 相关阅读:
    2020软件工程作业01
    2020软件工程—06—个人作业
    团队二次作业
    软件工程作业05
    软件工程作业00--问题清单
    软件工程作业04二期
    2020软件工程作业04
    oracle11安装过程中常出现的问题和解决办法
    2020软件工程作业03
    2020软件工程作业02
  • 原文地址:https://www.cnblogs.com/qi-yuan-008/p/12608323.html
Copyright © 2020-2023  润新知