gpt4 book ai didi

python - 使用 numpy 和 matplotlib 在 3 维中可视化多元正态分布

转载 作者:太空狗 更新时间:2023-10-30 02:53:45 25 4
gpt4 key购买 nike

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

enter image description here

我使用以下代码:

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

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

最佳答案

过去我用 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()

enter image description here

关于python - 使用 numpy 和 matplotlib 在 3 维中可视化多元正态分布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48465683/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com