[英]How to plot my own logistic regression decision boundaries and SKlearn's ones on the same figure
我有一項作業需要比較我自己的多類邏輯回歸和內置的 SKlearn 回歸。
作為其中的一部分,我需要在同一張圖上繪制每個的決策邊界(分別用於 2、3 和 4 類)。
這是我模型的 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-')
結果
我知道這是由於 1dim vs 2dim 網格造成的,但我不明白如何解決它。
我還嘗試使用內置的DecisionBoundaryDisplay
但我無法弄清楚如何用我的邊界繪制它+它不僅繪制線條而且整個背景都繪制成相應的顏色。
一些修復:
將clf.intercept_[1]
更改為clf.intercept_[i]
如果圖中的xlimits
和ylimits
看起來很奇怪,你可以約束它們。
ax.set_xlim([x1_min, x1_max])
ax.set_ylim([x2_min, x2_max])
先生:
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.