Skip to content Skip to sidebar Skip to footer

How Is Covariance Implemented Internally In Numpy?

This is the definition of a covariance matrix. http://en.wikipedia.org/wiki/Covariance_matrix#Definition Each element in the matrix, except in the principal diagonal, (if I am not

Solution 1:

Simply check the code.cov in \site-packages\numpy\lib\function_base.py

defcov(m, y=None, rowvar=1, bias=0, ddof=None):
    """
    Estimate a covariance matrix, given data.

    Covariance indicates the level to which two variables vary together.
    If we examine N-dimensional samples, :math:`X = [x_1, x_2, ... x_N]^T`,
    then the covariance matrix element :math:`C_{ij}` is the covariance of
    :math:`x_i` and :math:`x_j`. The element :math:`C_{ii}` is the variance
    of :math:`x_i`.

    Parameters
    ----------
    m : array_like
        A 1-D or 2-D array containing multiple variables and observations.
        Each row of `m` represents a variable, and each column a single
        observation of all those variables. Also see `rowvar` below.

...

if y isnotNone:
        y = array(y, copy=False, ndmin=2, dtype=float)
        X = concatenate((X,y), axis)

    X -= X.mean(axis=1-axis)[tup]
    if rowvar:
        N = X.shape[1]
    else:
        N = X.shape[0]

    if ddof isNone:
        if bias == 0:
            ddof = 1else:
            ddof = 0
    fact = float(N - ddof)

    ifnot rowvar:
        return (dot(X.T, X.conj()) / fact).squeeze()
    else:
        return (dot(X, X.T.conj()) / fact).squeeze()

Post a Comment for "How Is Covariance Implemented Internally In Numpy?"