通过Matplotlib绘制正常密度的判别函数

时间:2014-03-12 02:28:20

标签: python numpy matplotlib classification

我想绘制一些随机数据的正常密度的一般判别函数。我不知道如何通过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

谢谢!

1 个答案:

答案 0 :(得分:1)

以下是代码:

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