[Python] numpy.cov() Giving Incorrect Answer

Discussão em 'Python' iniciado por Stack, Março 13, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to use Python and NumPy to calculate a covariance matrix.

    Here is the matrix:

    [[0.69, 0.49],
    [-1.31, -1.21],
    [0.39, 0.99],
    [0.09, 0.29],
    [1.29, 1.09],
    [0.49, 0.79],
    [0.19, -0.31],
    [-0.81, -0.81],
    [-0.31, -0.31],
    [-0.71, -1.01]]


    Here is the expected result:
    [[0.7322, 0.6189],

    [0.6189, 0.5956]]

    Here is the equation I was given: covariance matrix = (1 / (n - 1))ZTZ

    n is the number of entries (10)

    Z is the matrix

    I tried np.cov(np_matrix), which didn't return the correct size or values.

    I've also tried this:

    np.cov(np_matrix, rowvar=False)

    >>> array([[0.61655556, 0.61544444],
    [0.61544444, 0.71655556]]


    I'm also trying to calculate it manually instead of using the cov function, but multiplying by the transpose doesn't even return the correct value.
    The correct value is this:
    [[6.59, 5.57],
    [5.57, 5.36]]

    However, this is what my code returns:

    np_matrix.T @ np_matrix

    >>> array([[5.549, 5.539],
    [5.539, 6.449]])


    np_matrix.T * np_matrix

    >>> ValueError: operands could not be broadcast together with shapes (2,10) (10,2)


    I've also tried setting the arrays to floats and doubles.

    Continue reading...

Compartilhe esta Página