【问题标题】:Error while Plotting Decision Boundary using Matplotlib使用 Matplotlib 绘制决策边界时出错
【发布时间】:2019-04-22 02:10:06
【问题描述】:

我最近使用 Scikit 模块编写了一个逻辑回归模型。但是,我真的很难绘制决策边界线。我明确地将系数和截距相乘并绘制它们(这反过来会抛出一个错误的数字)。

有人可以为我指出如何绘制决策边界的正确方向吗?

有没有一种更简单的方法来绘制直线,而无需手动将系数和截距相乘?

感谢一百万!

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

【问题讨论】:

    标签: python matplotlib scikit-learn


    【解决方案1】:

    有没有一种更简单的方法来绘制直线,而无需手动将系数和截距相乘?

    是的,如果您不需要从头开始构建它,那么 mlxtend 包中的 scikit-learn 分类器可以很好地绘制决策边界。提供的链接中包含大量文档,使用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 数据点来突出显示它们。

    【讨论】:

    • 感谢一百万!仅用于个人信息,是否可以使用具有相同简单顺序的 matplotlib 或 scikit 来实现?
    • scikit-learn 文档中的示例:DecisionTree 和 SVM。 Nice examples from a Kaggle kernel 肯定比使用mlxtend 方法要多行代码,但取决于你
    • 我最近开始遇到这个问题,我收到一条错误消息:“ValueError:当 X 具有超过 2 个训练特征时,必须提供填充值。”知道是什么原因造成的吗?
    • 请参阅 mlxtend 链接中的 Example 7。当有两个以上的特征时,它需要未绘制的特征的“填充”值。我之前评论中的链接是更直接的示例。您始终可以根据需要从x 中分割列。例如第一个和第二个特征:x[:, 0] 和 x[:, 1]。
    猜你喜欢
    • 2013-10-03
    • 2017-12-17
    • 2015-07-13
    • 2013-12-01
    • 2016-01-15
    • 2014-02-26
    • 2012-12-13
    • 2014-08-07
    相关资源
    最近更新 更多