[Python] numpy positive semi-definite warning

Discussão em 'Python' iniciado por Stack, Abril 11, 2025.

  1. Stack

    Stack Membro Participativo

    In a Python script I'm writing I am simulating multivariate normal random vectors with the expression

    np.random.multivariate_normal(np.zeros(dim_obs), y_cov)


    My script runs, but generates the following warning:

    RuntimeWarning: covariance is not positive-semidefinite.


    Also the little debug print statements I throw in there print False most of the time

    print( np.all(np.linalg.eigvals(y_cov) > 0) )


    Why is this throwing false positives? My y_cov is positive semi-definite because it is (sorry about the lack of TeX markup) B x x'B' + y y' where the B is a matrix, and the others are random vectors with each element positive.

    In this particular run B is actually just a ones vector of size 9. Can I just ignore this warning? From the documentation:


    Note that the covariance matrix must be positive semidefinite (a.k.a. nonnegative-definite). Otherwise, the behavior of this method is undefined and backwards compatibility is not guaranteed.
    ​

    Edit: here's a runnable thing altogether. Thanks for the tip @user2357112.

    import numpy as np
    num_factors = 1
    dim_obs = 9
    u = np.random.normal(size = num_factors)
    v = np.random.normal(size = dim_obs)
    y_cov = np.dot(np.ones((9,1)), np.exp(u.reshape((num_factors,1))/2))
    y_cov = np.dot(y_cov, np.exp(u.reshape((1,num_factors))/2)) #transpose
    y_cov = np.dot(y_cov, np.transpose(np.ones((9,1))))
    y_cov += np.dot(np.exp( v.reshape((dim_obs,1)) / 2),
    np.exp( v.reshape((1,dim_obs)) / 2))
    print( np.random.multivariate_normal(np.zeros(dim_obs), y_cov) )
    print( np.all(np.linalg.eigvals(y_cov) > 0) )
    print( np.linalg.eigvals(y_cov) )

    Continue reading...

Compartilhe esta Página