Python matplotlib:如何画一条线,将图形完美地划分为两个部分并给它们上色

Python matplotlib:如何画一条线,将图形完美地划分为两个部分并给它们上色,python,pandas,scikit-learn,Python,Pandas,Scikit Learn,您好,所以我尝试使用matplotlib在python中实现我的svm,并且能够做到这一点,正如您在下面看到的 代码: 图表: 看到上面的图表,我如何有效地画一条线来分隔紫色和黄色簇,并给背景上色,以显示它们是不同的。可以使用coef\uu和intercept\u属性来计算边界线的方程式。想想直线方程,a*x_1+b*x_2+c=0。这里a是coef[0][0],b是coef[0][1],c是intercept。您可以查看下面的代码,了解如何计算和绘制这条线 import numpy as n

您好,所以我尝试使用matplotlib在python中实现我的svm,并且能够做到这一点,正如您在下面看到的 代码:

图表:


看到上面的图表,我如何有效地画一条线来分隔紫色和黄色簇,并给背景上色,以显示它们是不同的。

可以使用
coef\uu
intercept\u
属性来计算边界线的方程式。想想直线方程,
a*x_1+b*x_2+c=0
。这里
a
coef[0][0]
b
coef[0][1]
,c是
intercept
。您可以查看下面的代码,了解如何计算和绘制这条线

import numpy as np
import matplotlib.pyplot as plt

length = np.random.uniform(0, 1, 100)
angle = np.pi * np.random.uniform(0, 2, 100)
c1 = np.array((length * np.cos(angle), length * np.sin(angle))).T
length = np.random.uniform(0, 1, 100)
angle = np.pi * np.random.uniform(0, 2, 100)
c2 = np.array((2 + length * np.cos(angle), 2 + length * np.sin(angle))).T
X = np.vstack((c1, c2))

y = np.ones(200)
y[100:] = 2
plt.scatter(X[:,0][y==1], X[:,1][y==1])
plt.scatter(X[:,0][y==2], X[:,1][y==2])

from sklearn.svm import SVC
clf = SVC(kernel='linear')
clf.fit(X, y) 
print(clf.coef_)
print(clf.intercept_)

x_line = np.linspace(-2, 4, 2)

# I think this line is what you are looking for
y_line = (-1 * clf.intercept_ - clf.coef_[0][0] * x_line) / clf.coef_[0][1]
plt.plot(x_line, y_line)
plt.show()
输出:


这是一个关于如何绘制分隔线并为两部分着色的问题,还是一个关于如何计算哪条线最能分隔两个总体的问题?除此之外,这不是一个问题,如果你问如何绘制边界线或区域,这个链接可能很有用:@MrT如何计算哪条线最能区分这两个群体。@SelçukGülcan它很有帮助,谢谢!但这并不完全是我所需要的,我正在寻找一种方法来绘制/创建一条线,它可以完美地映射自身,从而将这两个群体分开。:)@捷运好了。很抱歉给您带来不便,我不习惯在堆栈溢出上发布。y_行=(-1*clf.intercept-clf.coef[0][0]*x_行)/clf.coef[0][1]plt.plot(x_行,y_行)确实是我想要的,谢谢:)
import numpy as np
import matplotlib.pyplot as plt

length = np.random.uniform(0, 1, 100)
angle = np.pi * np.random.uniform(0, 2, 100)
c1 = np.array((length * np.cos(angle), length * np.sin(angle))).T
length = np.random.uniform(0, 1, 100)
angle = np.pi * np.random.uniform(0, 2, 100)
c2 = np.array((2 + length * np.cos(angle), 2 + length * np.sin(angle))).T
X = np.vstack((c1, c2))

y = np.ones(200)
y[100:] = 2
plt.scatter(X[:,0][y==1], X[:,1][y==1])
plt.scatter(X[:,0][y==2], X[:,1][y==2])

from sklearn.svm import SVC
clf = SVC(kernel='linear')
clf.fit(X, y) 
print(clf.coef_)
print(clf.intercept_)

x_line = np.linspace(-2, 4, 2)

# I think this line is what you are looking for
y_line = (-1 * clf.intercept_ - clf.coef_[0][0] * x_line) / clf.coef_[0][1]
plt.plot(x_line, y_line)
plt.show()