Pearson correlation coefficient


피어슨 상관 계수(Pearson correlation coefficient 또는 Pearson’s r)는 두 변수간의 관련성을 구하기 위해 보편적으로 이용된다. 개념은 다음과 같다.

r = X와 Y가 함께 변하는 정도 / X와 Y가 각각 변하는 정도

결과의 해석

r 값은 X 와 Y 가 완전히 동일하면 +1, 전혀 다르면 0, 반대방향으로 완전히 동일 하면 –1 을 가진다. 결정계수 (coefficient of determination) 는 r^2 로 계산하며 이것은 X 로부터 Y 를 예측할 수 있는 정도를 의미한다.

일반적으로

r이 -1.0과 -0.7 사이이면, 강한 음적 선형관계,
r이 -0.7과 -0.3 사이이면, 뚜렷한 음적 선형관계,
r이 -0.3과 -0.1 사이이면, 약한 음적 선형관계,
r이 -0.1과 +0.1 사이이면, 거의 무시될 수 있는 선형관계,
r이 +0.1과 +0.3 사이이면, 약한 양적 선형관계,
r이 +0.3과 +0.7 사이이면, 뚜렷한 양적 선형관계,
r이 +0.7과 +1.0 사이이면, 강한 양적 선형관계

로 해석할 수 있다. pearson 상관 계수를 구하는 공식은 다음과 같다.

\[r_{pb} = \frac{\sum (x - m_x) (y - m_y)}{\sqrt{\sum (x - m_x)^2 (y - m_y)^2}}\]

\(m_x\) 는 x의 평균이고 \(m_y\) 는 y의 평균을 의미한다.

다음은 scipy.stats의 pearsonr 함수 구현 코드이다.

def pearsonr(x, y):
    r"""
    Calculate a Pearson correlation coefficient and the p-value for testing
    non-correlation.
    The Pearson correlation coefficient measures the linear relationship
    between two datasets. Strictly speaking, Pearson's correlation requires
    that each dataset be normally distributed, and not necessarily zero-mean.
    Like other correlation coefficients, this one varies between -1 and +1
    with 0 implying no correlation. Correlations of -1 or +1 imply an exact
    linear relationship. Positive correlations imply that as x increases, so
    does y. Negative correlations imply that as x increases, y decreases.
    The p-value roughly indicates the probability of an uncorrelated system
    producing datasets that have a Pearson correlation at least as extreme
    as the one computed from these datasets. The p-values are not entirely
    reliable but are probably reasonable for datasets larger than 500 or so.

    Parameters
    ----------
    x : (N,) array_like
        Input
    y : (N,) array_like
        Input
    Returns
    -------
    r : float
        Pearson's correlation coefficient
    Notes
    -----
    The correlation coefficient is calculated as follows:
    .. math::
        r_{pb} = \frac{\sum (x - m_x) (y - m_y)
                       }{\sqrt{\sum (x - m_x)^2 (y - m_y)^2}}
    where :math:`m_x` is the mean of the vector :math:`x` and :math:`m_y` is
    the mean of the vector :math:`y`.

    References
    ----------
    http://www.statsoft.com/textbook/glosp.html#Pearson%20Correlation
    """
    # x and y should have same length.
    x = np.asarray(x)
    y = np.asarray(y)
    n = len(x)
    mx = x.mean()
    my = y.mean()
    xm, ym = x - mx, y - my
    r_num = np.add.reduce(xm * ym)
    r_den = np.sqrt(_sum_of_squares(xm) * _sum_of_squares(ym))
    r = r_num / r_den

    # Presumably, if abs(r) > 1, then it is only some small artifact of
    # floating point arithmetic.
    r = max(min(r, 1.0), -1.0)

    return r