Python 绘制决策边界 matplotlib
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19054923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
plot decision boundary matplotlib
提问by anonuser0428
I am very new to matplotlib and am working on simple projects to get acquainted with it. I was wondering how I might plot the decision boundary which is the weight vector of the form [w1,w2], which basically separates the two classes lets say C1 and C2, using matplotlib.
我对 matplotlib 很陌生,正在做一些简单的项目来熟悉它。我想知道如何绘制决策边界,即 [w1,w2] 形式的权重向量,它基本上将两个类分开,比如说 C1 和 C2,使用 matplotlib。
Is it as simple as plotting a line from (0,0) to the point (w1,w2) (since W is the weight "vector") if so, how do I extend this like in both directions if I need to?
是否像从 (0,0) 到点 (w1,w2) 绘制一条线一样简单(因为 W 是权重“向量”),如果是这样,如果需要,我该如何在两个方向上扩展它?
Right now all I am doing is :
现在我正在做的是:
import matplotlib.pyplot as plt
plt.plot([0,w1],[0,w2])
plt.show()
Thanks in advance.
提前致谢。
采纳答案by lejlot
Decision boundary is generally much more complex then just a line, and so (in 2d dimensional case) it is better to use the code for generic case, which will also work well with linear classifiers. The simplest idea is to plot contour plot of the decision function
决策边界通常比一条线复杂得多,因此(在二维情况下)最好使用通用情况的代码,这也适用于线性分类器。最简单的想法是绘制决策函数的等高线图
# X - some data in 2dimensional np.array
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
np.arange(y_min, y_max, h))
# here "model" is your model's prediction (classification) function
Z = model(np.c_[xx.ravel(), yy.ravel()])
# Put the result into a color plot
Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, Z, cmap=pl.cm.Paired)
plt.axis('off')
# Plot also the training points
plt.scatter(X[:, 0], X[:, 1], c=Y, cmap=pl.cm.Paired)
some examples from sklearn
documentation
sklearn
文档中的一些示例