2015-01-31 309 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