即使协方差是半正定的,为什么 bivariate_normal 也会返回 NaN? [英] Why bivariate_normal returns NaNs even if covariance is semi-positive definite?

查看:32
本文介绍了即使协方差是半正定的,为什么 bivariate_normal 也会返回 NaN?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下正态分布点:

import numpy as np
from matplotlib import pylab as plt
from matplotlib import mlab

mean_test = np.array([0,0])
cov_test = array([[ 0.6744121 , -0.16938146],
                  [-0.16938146,  0.21243464]])

协方差矩阵是确定的半正数,因此可以用作协方差

The covariance matrix is definite semi-positive so it can be used as a covariance

# Semi-positive definite if all eigenvalues are 0 or 
# if there exists a Cholesky decomposition 
print np.linalg.eigvals(cov_test)
print np.linalg.cholesky(cov_test)

[0.72985988 0.15698686]

[ 0.72985988 0.15698686]

[[0.82122597 0.][-0.20625439 0.41218172]]

[[ 0.82122597 0. ] [-0.20625439 0.41218172]]

如果我产生一些积分,我会得到:

If I generate some points I get:

 data_test = np.random.multivariate_normal(mean_test, cov_test, 1000)
 plt.scatter(data_test[:,0],data_test[:,1])

问题:

当我尝试绘制协方差轮廓时,为什么 bivariate_normal 方法会失败(返回 NaN)?

Why does bivariate_normal method fail (return NaNs) when I try to plot the covariance contour?

x = np.arange(-3.0, 3.0, 0.1)
y = np.arange(-3.0, 3.0, 0.1)
X, Y = np.meshgrid(x, y)
Z = mlab.bivariate_normal(X, Y, 
                      cov_test[0,0], cov_test[1,1],
                      0, 0, cov_test[0,1])
print Z
plt.contour(X, Y, Z)

输出:

 [[ nan  nan  nan ...,  nan  nan  nan]
 [ nan  nan  nan ...,  nan  nan  nan]
 [ nan  nan  nan ...,  nan  nan  nan]
 ..., 
 [ nan  nan  nan ...,  nan  nan  nan]
 [ nan  nan  nan ...,  nan  nan  nan]
 [ nan  nan  nan ...,  nan  nan  nan]]

 ValueError: zero-size array to reduction operation minimum which has no identity

推荐答案

协方差矩阵的对角线是方差,但是 sigmaxsigmay 的参数> mlab.bivariate_normal 是方差的平方根.更改此:

The diagonals of the covariance matrix are the variances, but the arguments sigmax and sigmay of mlab.bivariate_normal are the square roots of the variances. Change this:

Z = mlab.bivariate_normal(X, Y, 
                      cov_test[0,0], cov_test[1,1],
                      0, 0, cov_test[0,1])

为此:

Z = mlab.bivariate_normal(X, Y, 
                      np.sqrt(cov_test[0,0]), np.sqrt(cov_test[1,1]),
                      0, 0, cov_test[0,1])

这篇关于即使协方差是半正定的,为什么 bivariate_normal 也会返回 NaN?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆