【问题标题】:Visualizing a multivariate normal distribution with numpy and matplotlib in 3 Dimensions使用 numpy 和 matplotlib 在 3 维中可视化多元正态分布
【发布时间】:2018-07-06 01:09:51
【问题描述】:

我正在尝试使用 matplotlib 可视化多元正态分布。我想制作这样的东西:

我使用以下代码:

from mpl_toolkits import mplot3d
x = np.linspace(-1, 3, 100)
y = np.linspace(0, 4, 100)
X, Y = np.meshgrid(x, y)
Z = np.random.multivariate_normal(mean = [1, 2], cov = np.array([[0.5, 0.25],[0.25, 0.50]]), size = 100000)
ax = plt.axes(projection='3d')
ax.plot_surface(X, Y, Z, rstride=1, cstride=1,
                cmap='viridis', edgecolor='none')
ax.set_title('surface');

但我收到以下错误消息:

...
      7 ax.plot_surface(X, Y, Z, rstride=1, cstride=1,
----> 8                 cmap='viridis', edgecolor='none')
...
ValueError: shape mismatch: objects cannot be broadcast to a single shape

错误的原因是什么以及如何更正我的代码?

【问题讨论】:

  • 不应该Zx, y 对的函数吗?如图所示here。 Atm 您可能为 Z 创建了不同的数组大小。

标签: python numpy matplotlib 3d


【解决方案1】:

过去我使用scipy.stats.multivariate_normal 完成此操作,特别是使用pdf 方法生成z 值。正如@Piinthesky 指出的那样,numpy 实现返回给定分布的 x 和 y 值。使用辣版本的示例是(另一个可以在 (Python add gaussian noise in a radius around a point [closed]) 中找到:

from mpl_toolkits import mplot3d
import matplotlib.pyplot as plt
from scipy.stats import multivariate_normal
x = np.linspace(-1, 3, 100)
y = np.linspace(0, 4, 100)
X, Y = np.meshgrid(x, y)
pos = np.dstack((X, Y))
mu = np.array([1, 2])
cov = np.array([[.5, .25],[.25, .5]])
rv = multivariate_normal(mu, cov)
Z = rv.pdf(pos)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z)
fig.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-05
    • 1970-01-01
    • 2018-07-16
    • 2020-08-18
    • 1970-01-01
    • 1970-01-01
    • 2012-03-13
    相关资源
    最近更新 更多