SVM画分界线不出结果图,那位大佬帮忙解释一下,代码和错误结果图如下

220 阅读1分钟
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from sklearn.svm import LinearSVC
from sklearn.model_selection import train_test_split
from sklearn.datasets import make_classification


# 生成数据
X, y = make_classification(n_samples=100, n_features=2,
                           n_redundant=0, random_state=42)
train_X, test_X, train_y, test_y = train_test_split(X, y, random_state=42)

# 构建模型
model = LinearSVC()

# 使用 train_X 和 train_y 对模型进行训练
model.fit(train_X, train_y)

# 使用 test_X 和 test_y 对模型的准确率进行输出
print(model.score(test_X, test_y))


# 对生成的数据进行绘制
plt.scatter(X[:, 0], X[:, 1], c=y, marker=".",
            cmap=matplotlib.cm.get_cmap(name="bwr"), alpha=0.7)

# 对经过学习并导出的分界线进行绘制
Xi = np.linspace(-10, 10)
Y = -model.coef_[0][0] / model.coef_[0][1] * Xi - model.intercept_ / model.coef_[0][1]
plt.plot(Xi, Y)

# 调整图表的缩放尺度
plt.xlim(min(X[:, 0]) - 0.5, max(X[:, 0]) + 0.5)
plt.ylim(min(X[:, 1]) - 0.5, max(X[:, 1]) + 0.5)
plt.axes().set_aspect("equal", "datalim")
# 设置图表的标题
plt.title("classification data using LinearSVC")
# 分别为 x 轴和 y 轴设置名称
plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.show()

代码.png