Skip to main content
 首页 » 编程设计

python之无法理解 SVM 和 LR 中决策边界的绘制

2025年05月04日17birdshome

例如,我们有 f(x) = x。如何绘制它?我们取一些 x 然后计算 y 并再次执行此操作,然后按点绘制图表。简单明了。

但我无法理解如此清楚地绘制决策边界 - 当我们没有 y 来绘制时,只有 x。

SVM 的 Python 代码:

h = .02  # step size in the mesh 
Y = y 
# we create an instance of SVM and fit out data. We do not scale our 
# data since we want to plot the support vectors 
C = 1.0  # SVM regularization parameter 
svc = svm.SVC(kernel='linear', C=C).fit(X, Y) 
rbf_svc = svm.SVC(kernel='rbf', gamma=0.7, C=C).fit(X, Y) 
poly_svc = svm.SVC(kernel='poly', degree=3, C=C).fit(X, Y) 
lin_svc = svm.LinearSVC(C=C).fit(X, Y) 
 
# create a mesh to plot in 
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)) 
 
 
for i, clf in enumerate((svc, rbf_svc, poly_svc, lin_svc)): 
    # Plot the decision boundary. For that, we will asign a color to each 
    # point in the mesh [x_min, m_max]x[y_min, y_max]. 

绘制图表的所有内容都在这里,我是如何理解的:

    pl.subplot(2, 2, i + 1) 
    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) 
 
    # Put the result into a color plot 
    Z = Z.reshape(xx.shape) 
    pl.contourf(xx, yy, Z, cmap=pl.cm.Paired) 
    pl.axis('off') 
 
    # Plot also the training points 
    pl.scatter(X[:, 0], X[:, 1], c=Y, cmap=pl.cm.Paired) 
 
pl.show() 

谁能用文字解释一下这个阴谋是如何运作的?

请您参考如下方法:

基本上,您正在绘制函数 f : R^2 -> {0,1} 所以它是一个从二维空间到只有两个值的退化空间的函数 - 0 和 1。

首先,您生成要在其上可视化函数的网格。对于您使用 f(x)=y 的示例,您将选择一些间隔 [x_min,x_max],您将在该间隔上取具有一定距离的点 eps 并绘制相应的 f

值
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)) 

接下来,我们计算函数值,在我们的例子中它是一个 SVM.predict 函数,结果是 0 或 1

Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) 

这与您为所有分析的 x 计算 f(x) 的示例相同

现在,可能导致误解的“棘手”部分是

pl.contourf(xx, yy, Z, cmap=pl.cm.Paired) 

此函数绘制您的 f 函数的等高线。要在平面上可视化 3 维函数,通常会创建等高线图,它就像函数高度图。如果在点周围检测到 f 的值发生较大变化,则在点之间画一条线。

来自 mathworld 的好例子

显示此类图的示例。

在 SVM 的情况下,我们只有两个可能的值 - 0 和 1,因此,等高线位于恰好在二维空间的这些部分中,一侧是 f(x)=0,另一侧是 f(x)=1。因此,尽管它看起来像一个“2d 图”,但实际上并非如此 - 您可以观察到的这种形状(决策边界)是 3d 函数中最大差异的可视化。

在 sklearn 文档中为多分类示例可视化它,当我们有 f : R^2 -> {0,1,2} 时,所以idea 完全相同,但是等高线绘制在相邻的 x1 和 x2 之间,f(x1)!=f(x2)。