绘制逻辑回归的决策边界

时间:2015-01-31 20:13:44

标签: matplotlib scikit-learn logistic-regression

我正在实施逻辑回归。我设法从中获取概率,并且能够预测2级分类任务。

我的问题是:

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

我如何策划这个?我看到this post,但我不太明白答案。我需要等高线图吗?

3 个答案:

答案 0 :(得分:34)

逻辑回归分类器的一个优点是,一旦适合它,您就可以获得任何样本向量的概率。情节可能更有趣。以下是使用scikit-learn的示例:

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

逻辑回归可让您根据所需的任何阈值对新样本进行分类,因此它本身并不具有一个决策边界。"但是,当然,使用的常见决策规则是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

答案 1 :(得分:5)

对此,可以接受的答案很好,但是当尝试理解权重的含义,将权重转换为斜率/截距形式并仅绘制决策边界时,它也很有用。

logit的格式为wx + b,但在二进制分类的情况下,xw是二维的。这些x值之一实际上代表图中的y。这意味着直线的方程将如下所示:

w[1] * y = w[0] * x + b 
# to solve for y
y = (w[0] * x)/w[1] + b / w[1]

x_np用作您的数据,将w + b用作您的学习参数,将变得很简单:

plt.scatter(x_np[:,0], x_np[:,1], c=y_np.reshape(-1),cmap=mpl.colors.ListedColormap(colors))
ax = plt.gca()
ax.autoscale(False)
x_vals = np.array(ax.get_xlim())
y_vals = -(x_vals * w_guess[0] + b_guess[0])/w_guess[1]
plt.plot(x_vals, y_vals, '--', c="red")

enter image description here

答案 2 :(得分:0)

page_image

应为:

w[1] * y = w[0] * x + b  

就像您在代码中所做的那样:

w[1] * y = **-**(w[0] * x + b)  
相关问题