簡體   English   中英

使用Matplotlib繪制決策邊界時出錯

[英]Error while Plotting Decision Boundary using Matplotlib

我最近使用Scikit模塊編寫了Logistic回歸模型。 但是,我在繪制決策邊界線時非常困難。 我明確地將系數和截距相乘並繪制它們(從而拋出錯誤的數字)。

有人可以為我指出正確繪制決策邊界的正確方向嗎?

有沒有一種簡單的方法可以繪制線而無需手動乘以系數和截距?

太感謝了!

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

#Import Dataset
dataset = pd.read_csv("Students Exam Dataset.txt", names=["Exam 1", "Exam 2", "Admitted"])
print(dataset.head())

#Visualizing Dataset
positive = dataset[dataset["Admitted"] == 1]
negative = dataset[dataset["Admitted"] == 0]

plt.scatter(positive["Exam 1"], positive["Exam 2"], color="blue", marker="o", label="Admitted")
plt.scatter(negative["Exam 1"], negative["Exam 2"], color="red", marker="x", label="Not Admitted")
plt.title("Student Admission Plot")
plt.xlabel("Exam 1")
plt.ylabel("Exam 2")
plt.legend()
plt.plot()
plt.show()

#Preprocessing Data
col = len(dataset.columns)
x = dataset.iloc[:,0:col].values
y = dataset.iloc[:,col-1:col].values
print(f"X Shape: {x.shape}   Y Shape: {y.shape}")

x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=1306)

#Initialize Model
reg = LogisticRegression()
reg.fit(x_train, y_train)

#Output
predictions = reg.predict(x_test)
accuracy = accuracy_score(y_test, predictions) * 100
coeff = reg.coef_
intercept = reg.intercept_
print(f"Accuracy Score : {accuracy} %")
print(f"Coefficients = {coeff}")
print(f"Intercept Coefficient = {intercept}")

#Visualizing Output
xx = np.linspace(30,100,100)
decision_boundary = (coeff[0,0] * xx + intercept.item()) / coeff[0,1]
plt.scatter(positive["Exam 1"], positive["Exam 2"], color="blue", marker="o", label="Admitted")
plt.scatter(negative["Exam 1"], negative["Exam 2"], color="red", marker="x", label="Not Admitted")
plt.plot(xx, decision_boundary, color="green", label="Decision Boundary")
plt.title("Student Admission Plot")
plt.xlabel("Exam 1")
plt.ylabel("Exam 2")
plt.legend()
plt.show()

數據集: Student Dataset.txt

有沒有一種簡單的方法可以繪制線而無需手動乘以系數和截距?

是的,如果您不需要從頭開始構建它,可以使用mlxtend包中的scikit-learn分類器繪制決策邊界的出色實現。 該文檔在所提供的鏈接中非常pip install mlxtend通過pip install mlxtend輕松pip install mlxtend

首先,關於您發布的代碼的Preprocessing塊的幾點要點:
1. x不應包含類標簽。
2. y應該是一1d數組。

#Preprocessing Data
col = len(dataset.columns)
x = dataset.iloc[:,0:col-1].values # assumes your labels are always in the final column.
y = dataset.iloc[:,col-1:col].values
y = y.reshape(-1) # convert to 1d

現在,繪制就像:

from mlxtend.plotting import plot_decision_regions
plot_decision_regions(x, y,
                      X_highlight=x_test,
                      clf=reg,
                      legend=2)

此特定圖通過將x_test數據點包圍起來突出顯示它們。

在此處輸入圖片說明

暫無
暫無

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

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