尝试在3D图中绘制多元高斯分布,matplotlib 返回空图
我正在尝试用matplotlib画一个高斯分布的图,但我得到的只是一个空白的图:
我在网上查了一下,了解到ax.plot_surface()
这个函数需要三个参数,分别是X值、Y值,还有Z值(Z值是通过X和Y计算出来的一个函数)。这样理解对吗?
我把下面的代码贴出来,希望你们能帮我找出我哪里做错了。谢谢!
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
###############################################
### The multivariate Gaussian density function
###############################################
def pdf_multivariate_gauss(x, mu, cov):
'''
Caculate the multivariate normal density (pdf)
Keyword arguments:
x = numpy array of a "d x 1" sample vector
mu = numpy array of a "d x 1" mean vector
cov = "numpy array of a d x d" covariance matrix
'''
assert(mu.shape[0] > mu.shape[1]), 'mu must be a row vector'
assert(x.shape[0] > x.shape[1]), 'x must be a row vector'
assert(cov.shape[0] == cov.shape[1]), 'covariance matrix must be square'
assert(mu.shape[0] == cov.shape[0]), 'cov_mat and mu_vec must have the same dimensions'
assert(mu.shape[0] == x.shape[0]), 'mu and x must have the same dimensions'
part1 = 1 / ( ((2* np.pi)**(len(mu)/2)) * (np.linalg.det(cov)**(1/2)) )
part2 = (-1/2) * ((x-mu).T.dot(np.linalg.inv(cov))).dot((x-mu))
return float(part1 * np.exp(part2))
# Test
x = np.array([[0],[0]])
mu = np.array([[0],[0]])
cov = np.eye(2)
print(pdf_multivariate_gauss(x, mu, cov))
#prints 0.15915494309189535
###############################################
### The plot
###############################################
mu = np.array([[0],[0]])
cov = np.eye(2)
def construct_Z(X, Y, mu, cov):
Z = []
for i,j in zip(X,Y):
x = np.array([i,j]).reshape(2,1)
Z.append(pdf_multivariate_gauss(x, mu, cov))
return Z
X = linspace(-5, 5, 200)
Y = linspace(-5, 5, 200)
Z = construct_Z(X, Y, mu, cov)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, color='0.8',
alpha=0.85, linewidth=1)
plt.show()
1 个回答
2
我对在matplotlib中做3D图不是很在行,但我觉得你的数据有问题。
从这个教程的源代码中可以看到,你的 X,Y
和 Z
数据必须是二维数组。你的 X
和 Y
是一维的,而 Z
只是一个简单的列表。
试着把你的数据调整成一个网格,可能可以用 X, Y = np.meshgrid(X, Y)
来实现。