2015-01-31 296 views
7

我正在实施逻辑回归。我设法从中得出概率,并且能够预测2类分类任务。绘制逻辑回归的决策边界

我的问题是:

对于我的最终模型,我有权重和训练数据。有2个功能,所以我的体重是2行的矢量。

我该如何绘制?我看到了this post,但我不太明白答案。我需要一个等高线图吗?

回答

20

Logistic回归分类器的一个优点是,一旦你符合它,你就可以得到任何样本向量的概率。情节可能更有趣。下面是使用一个例子scikit学习:

import numpy as np 
from sklearn.linear_model import LogisticRegression 
from sklearn.datasets import make_classification 
import matplotlib.pyplot as plt 
import seaborn as sns 
sns.set(style="white") 

首先,生成的数据,并符合分类训练集:

X, y = make_classification(200, 2, 2, 0, weights=[.5, .5], random_state=15) 
clf = LogisticRegression().fit(X[:100], y[:100]) 

接下来,使值的连续格栅和评估每个概率在网格(x,y)的点:

xx, yy = np.mgrid[-5:5:.01, -5:5:.01] 
grid = np.c_[xx.ravel(), yy.ravel()] 
probs = clf.predict_proba(grid)[:, 1].reshape(xx.shape) 

现在,绘制概率格作为等高线图,并且另外示出了测试样本集在它的上面:

f, ax = plt.subplots(figsize=(8, 6)) 
contour = ax.contourf(xx, yy, probs, 25, cmap="RdBu", 
         vmin=0, vmax=1) 
ax_c = f.colorbar(contour) 
ax_c.set_label("$P(y = 1)$") 
ax_c.set_ticks([0, .25, .5, .75, 1]) 

ax.scatter(X[100:,0], X[100:, 1], c=y[100:], s=50, 
      cmap="RdBu", vmin=-.2, vmax=1.2, 
      edgecolor="white", linewidth=1) 

ax.set(aspect="equal", 
     xlim=(-5, 5), ylim=(-5, 5), 
     xlabel="$X_1$", ylabel="$X_2$") 

enter image description here

Logistic回归允许根据你想要的任何门槛的分类新样品,所以它并不具有一个“决策边界。”但是,当然,使用一个通用的决策规则是p = .5。我们也可以只使用上面的代码绘制等高线:

f, ax = plt.subplots(figsize=(8, 6)) 
ax.contour(xx, yy, probs, levels=[.5], cmap="Greys", vmin=0, vmax=.6) 

ax.scatter(X[100:,0], X[100:, 1], c=y[100:], s=50, 
      cmap="RdBu", vmin=-.2, vmax=1.2, 
      edgecolor="white", linewidth=1) 

ax.set(aspect="equal", 
     xlim=(-5, 5), ylim=(-5, 5), 
     xlabel="$X_1$", ylabel="$X_2$") 

enter image description here

+0

我说得对已导入'seaborn',但实际上并没有在你的答案用它?我对图书馆不熟悉,只是检查是否有必要回答。 – Rhubarb 2016-03-02 17:35:49

+1

@Zhubarb:只要导入它,Seaborn就会覆盖很多matplotlib的默认配置。因此,如果您不需要seaborn直接提供的任何功能,但只希望matplotlib看起来好于默认的功能,那么您只需使用inport seaborn并使用matplotlib来开展您的业务 – Gus 2016-06-09 16:48:58

+0

@Gus我得到一个错误在'probs = clf.predict_probs(grid)[:, 1] .reshape(xx.shape)'说'AttributeError:'LogisticRegression'对象没有属性'predict_probs''我是否缺少某些东西? – 2017-12-20 04:43:59