gpt4 book ai didi

python - 通过 Matplotlib 绘制正态密度的判别函数

转载 作者:太空宇宙 更新时间:2023-11-03 18:31:21 24 4
gpt4 key购买 nike

我想绘制一些随机数据的正常密度的一般判别函数。我不知道如何通过 matplotlib 来解决这个问题,我希望任何人都可以帮助我一点。

等式为:

enter image description here enter image description here enter image description here

我已经编写了代码并将其放入 IPython 笔记本中,希望对您有所帮助!

View iPython notebook

如果您想下载,该笔记本也在 Github 上(如果有帮助的话,我还可以制作一个 .py 脚本)。 Link to IPython notebook file on Github

谢谢!

最佳答案

这是代码:

import pylab as pl
import numpy as np

D = 2

M1 = np.array([0.0, 0.0])
M2 = np.array([1.0, 1.0])

C1 = np.array([[2.0, 0.4], [0.4, 1.0]])
C2 = np.array([[1.0, 0.6], [0.6, 2.0]])

X, Y = np.mgrid[-2:2:100j, -2:2:100j]
points = np.c_[X.ravel(), Y.ravel()]

invC = np.linalg.inv(C1)
v = points - M1
g1 = -0.5*np.sum(np.dot(v, invC) * v, axis=1) - D*0.5*np.log(2*np.pi) - 0.5*np.log(np.linalg.det(C1))
g1.shape = 100, 100

invC = np.linalg.inv(C2)
v = points - M2
g2 = -0.5*np.sum(np.dot(v, invC) * v, axis=1) - D*0.5*np.log(2*np.pi) - 0.5*np.log(np.linalg.det(C2))
g2.shape = 100, 100

fig, axes = pl.subplots(1, 3, figsize=(15, 5))
ax1, ax2, ax3 = axes.ravel()
for ax in axes.ravel():
ax.set_aspect("equal")

ax1.pcolormesh(X, Y, g1)
ax2.pcolormesh(X, Y, g2)
ax3.pcolormesh(X, Y, g1 > g2)

输出:

enter image description here

然后使用随机数进行模拟:

N = 3000000
r1 = np.random.multivariate_normal(M1, C1, N)
r2 = np.random.multivariate_normal(M2, C2, N)

h1, rx, ry = np.histogram2d(r1[:, 0], r1[:, 1], bins=50, range=[[-2, 2], [-2, 2]])
h2, _, _ = np.histogram2d(r2[:, 0], r2[:, 1], bins=50, range=[[-2, 2], [-2, 2]])

rx, ry = np.broadcast_arrays(rx[:, None], ry[None, :])

fig, axes = pl.subplots(1, 3, figsize=(15, 5))
ax1, ax2, ax3 = axes.ravel()
for ax in axes.ravel():
ax.set_aspect("equal")

ax1.pcolormesh(rx, ry, h1)
ax2.pcolormesh(rx, ry, h2)
ax3.pcolormesh(rx, ry, h1 > h2)

输出:

enter image description here

关于python - 通过 Matplotlib 绘制正态密度的判别函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22340808/

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