簡體   English   中英

如何在同一張圖上繪制我自己的邏輯回歸決策邊界和 SKlearn 的決策邊界

[英]How to plot my own logistic regression decision boundaries and SKlearn's ones on the same figure

我有一項作業需要比較我自己的多類邏輯回歸和內置的 SKlearn 回歸。

作為其中的一部分,我需要在同一張圖上繪制每個的決策邊界(分別用於 2、3 和 4 類)。

這是我模型的 3 個類的決策邊界:

我的模型 - 3 類

使用此代碼制作:

x1_min, x1_max = X[:,0].min()-.5, X[:,0].max()+.5
x2_min, x2_max = X[:,1].min()-.5, X[:,1].max()+.5

xx1, xx2 = np.meshgrid(np.linspace(x1_min, x1_max), np.linspace(x2_min, x2_max))
grid = np.c_[xx1.ravel(), xx2.ravel()]
for i in range(len(ws)):
    probs = ol.predict_prob(grid, ws[i]).reshape(xx1.shape)
    plt.contour(xx1, xx2, probs, [0.5], linewidths=1, colors='green')

在哪里

  • ol - 是我自己的線性回歸
  • ws - 當前權重

這就是我試圖繪制 Sklearn 邊界的方式:

for i in range(len(clf.coef_)):
    w = clf.coef_[i]
    a = -w[0] / w[1]
    xx = np.linspace(x1_min, x1_max)
    yy = a * xx - (clf.intercept_[0]) / w[1]
    plt.plot(xx, yy, 'k-')

結果

SKlearn - 3 節課

我知道這是由於 1dim vs 2dim 網格造成的,但我不明白如何解決它。

我還嘗試使用內置的DecisionBoundaryDisplay但我無法弄清楚如何用我的邊界繪制它+它不僅繪制線條而且整個背景都繪制成相應的顏色。

一些修復:

  1. clf.intercept_[1]更改為clf.intercept_[i]

  2. 如果圖中的xlimitsylimits看起來很奇怪,你可以約束它們。

ax.set_xlim([x1_min, x1_max])
ax.set_ylim([x2_min, x2_max])

散點圖和線圖對比訓練邏輯回歸的多項式與單項對比休息方法。 Multinomial 具有三個相交線,而 one-versus-rest 具有分別代表三個博客的線。

先生

import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import make_blobs
from sklearn.linear_model import LogisticRegression

X, y = make_blobs(n_features=2, centers=3, random_state=42)
fig, ax = plt.subplots(1, 2)

x1_min, x1_max = X[:,0].min()-.5, X[:,0].max()+.5
x2_min, x2_max = X[:,1].min()-.5, X[:,1].max()+.5

def draw_coef_lines(clf, X, y, ax, title):
    for i in range(len(clf.coef_)):
        w = clf.coef_[i]
        a = -w[0] / w[1]
        xx = np.linspace(x1_min, x1_max)
        yy = a * xx - (clf.intercept_[i]) / w[1]
        ax.plot(xx, yy, 'k-')
    ax.scatter(X[:, 0], X[:, 1], c=y)
    ax.set_xlim([x1_min, x1_max])
    ax.set_ylim([x2_min, x2_max])
    ax.set_title(title)

clf1 = LogisticRegression().fit(X, y)
clf2 = LogisticRegression(multi_class="ovr").fit(X, y)

draw_coef_lines(clf1, X, y, ax[0], "Multinomial")
draw_coef_lines(clf2, X, y, ax[1], "OneVsRest")
plt.show()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM