我有 3 个判别函数,将 2D 空间划分为 3 个区域。我想绘制这些区域之间的决策边界。我不知道如何在 python 中使用 matplotlib meshgrid 来做到这一点。
对于2个判别函数,过程很简单。我计算值为 0 的函数和等高线图之间的差异。
lin_param = (-5, 5, 100)
xx = np.linspace(*lin_param)
yy = np.linspace(*lin_param)
x, y = np.meshgrid(xx, yy)
z = g1(x, y) - g2(x, y)
cp = plt.contour(x, y, z, levels=[0], colors="k")
plt.scatter(0, 0)
plt.scatter(2, 2)
plt.show()
其中 g1 和 g2 是均值为 (0, 0) 和 (2, 2) 的多元高斯分布。 (分布并不重要,我想将其应用于任何判别函数)
def pdf(x, y, mean, cov):
var = multivariate_normal(mean=mean, cov=cov)
pos = np.empty(x.shape + (2,))
pos[:, :, 0] = x; pos[:, :, 1] = y
return var.pdf(pos)
def g1(x, y):
return pdf(x, y, mean=[0,0], cov=[[1,0],[0,1]])
def g2(x, y):
return pdf(x, y, mean=[2,2], cov=[[1,0],[0,1]])
def g3(x, y):
return pdf(x, y, mean=[-2,2], cov=[[1,0],[0,1]])
这里一侧是负极,另一侧是正极。沿决策边界的值全部为零。现在我要添加第三个函数 g3,其均值位于 (-2, 2)。绘制结果决策边界并不简单。我尝试取 3 个函数的最大 2 个值并将它们的差值指定为 z 值,但无法实现我想要的。
我希望看到类似于下图的内容:
是否可以使用类似的网格轮廓图方法来实现它?我不想明确地计算这条线。
Update
通过使用contourf方法,可以用不同的颜色填充区域。然而,划定边界线仍然是个问题。