使用Matplotlib的pyplot绘制将2个类分开的决策边界 [英] Plotting a decision boundary separating 2 classes using Matplotlib's pyplot

查看:140
本文介绍了使用Matplotlib的pyplot绘制将2个类分开的决策边界的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的可以使用技巧来帮助我绘制决策边界以区分数据类别.我通过Python NumPy创建了一些样本数据(来自高斯分布).在这种情况下,每个数据点都是2D坐标,即由2行组成的1列向量.例如,

I could really use a tip to help me plotting a decision boundary to separate to classes of data. I created some sample data (from a Gaussian distribution) via Python NumPy. In this case, every data point is a 2D coordinate, i.e., a 1 column vector consisting of 2 rows. E.g.,

[ 1
  2 ]

假设我有2个类,即class1和class2,并通过下面的代码(分配给变量x1_samples和x2_samples)为class1和class2创建了100个数据点.

Let's assume I have 2 classes, class1 and class2, and I created 100 data points for class1 and 100 data points for class2 via the code below (assigned to the variables x1_samples and x2_samples).

mu_vec1 = np.array([0,0])
cov_mat1 = np.array([[2,0],[0,2]])
x1_samples = np.random.multivariate_normal(mu_vec1, cov_mat1, 100)
mu_vec1 = mu_vec1.reshape(1,2).T # to 1-col vector

mu_vec2 = np.array([1,2])
cov_mat2 = np.array([[1,0],[0,1]])
x2_samples = np.random.multivariate_normal(mu_vec2, cov_mat2, 100)
mu_vec2 = mu_vec2.reshape(1,2).T

当我为每个类绘制数据点时,它看起来像这样:

When I plot the data points for each class, it would look like this:

现在,我想出了一个决策边界方程,将两个类别分开,并希望将其添加到绘图中.但是,我不确定如何绘制此函数:

Now, I came up with an equation for an decision boundary to separate both classes and would like to add it to the plot. However, I am not really sure how I can plot this function:

def decision_boundary(x_vec, mu_vec1, mu_vec2):
    g1 = (x_vec-mu_vec1).T.dot((x_vec-mu_vec1))
    g2 = 2*( (x_vec-mu_vec2).T.dot((x_vec-mu_vec2)) )
    return g1 - g2

我将非常感谢您的帮助!

I would really appreciate any help!

凭直觉(如果我的数学正确的话),我希望在绘制函数时决策边界看起来像这条红线...

Intuitively (If I did my math right) I would expect the decision boundary to look somewhat like this red line when I plot the function...

推荐答案

这些都是很棒的建议,非常感谢您的帮助!我最终通过解析方式求解了方程,这就是我最终得到的解决方案(我只想将其发布以供将来参考:

Those were some great suggestions, thanks a lot for your help! I ended up solving the equation analytically and this is the solution I ended up with (I just want to post it for future reference:

可以找到该代码此处

我还具有一个便利功能,可为实现fitpredict方法的分类器(例如scikit-learn中的分类器)绘制决策区域,如果无法通过解析找到解决方案,该功能将非常有用.在此处.

I also have a convenience function for plotting decision regions for classifiers that implement a fit and predict method, e.g., the classifiers in scikit-learn, which is useful if the solution cannot be found analytically. A more detailed description how it works can be found here.

这篇关于使用Matplotlib的pyplot绘制将2个类分开的决策边界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆