如何使用scikit-learn可视化两个类别的边界/决策函数

我在机器学习领域还是新手,所以还不明白如何在词袋模型的情况下可视化两个类别之间的边界。

我找到了以下示例来绘制数据

绘制文档tfidf二维图表

from sklearn.datasets import fetch_20newsgroupsfrom sklearn.feature_extraction.text import CountVectorizer, TfidfTransformerfrom sklearn.decomposition import PCAfrom sklearn.pipeline import Pipelineimport matplotlib.pyplot as pltnewsgroups_train = fetch_20newsgroups(subset='train',                                       categories=['alt.atheism', 'sci.space'])pipeline = Pipeline([    ('vect', CountVectorizer()),    ('tfidf', TfidfTransformer()),])        X = pipeline.fit_transform(newsgroups_train.data).todense()pca = PCA(n_components=2).fit(X)data2D = pca.transform(X)plt.scatter(data2D[:,0], data2D[:,1], c=newsgroups_train.target)plt.show()

enter image description here

在我的项目中,我使用了SVC估计器

clf = SVC(random_state=241, kernel = 'linear')clf.fit(X,newsgroups_train.target)

我尝试使用示例http://scikit-learn.org/stable/auto_examples/svm/plot_iris.html但在文本分类情况下不起作用

那么,我如何在这个图上添加两个类别的边界呢?

谢谢!


回答:

问题在于你需要选择仅2个特征来创建二维决策表面图。我将提供两个示例。第一个使用iris数据,第二个使用你的数据。

我还在这里写了一篇关于这个的文章:https://towardsdatascience.com/support-vector-machines-svm-clearly-explained-a-python-tutorial-for-classification-problems-29c539f3ad8?source=friends_link&sk=80f72ab272550d76a0cc3730d7c8af35

在这两种情况下,我都只选择了2个特征来创建图表。

使用iris数据的示例1:

from sklearn.svm import SVCimport numpy as npimport matplotlib.pyplot as pltfrom sklearn import svm, datasetsiris = datasets.load_iris()X = iris.data[:, :2]  # 我们只选择前两个特征。y = iris.targetdef make_meshgrid(x, y, h=.02):    x_min, x_max = x.min() - 1, x.max() + 1    y_min, y_max = y.min() - 1, y.max() + 1    xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))    return xx, yydef plot_contours(ax, clf, xx, yy, **params):    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])    Z = Z.reshape(xx.shape)    out = ax.contourf(xx, yy, Z, **params)    return outmodel = svm.SVC(kernel='linear')clf = model.fit(X, y)fig, ax = plt.subplots()# 图表标题title = ('线性SVC的决策表面')# 设置绘图网格X0, X1 = X[:, 0], X[:, 1]xx, yy = make_meshgrid(X0, X1)plot_contours(ax, clf, xx, yy, cmap=plt.cm.coolwarm, alpha=0.8)ax.scatter(X0, X1, c=y, cmap=plt.cm.coolwarm, s=20, edgecolors='k')ax.set_ylabel('此处填写y轴标签')ax.set_xlabel('此处填写x轴标签')ax.set_xticks(())ax.set_yticks(())ax.set_title(title)ax.legend()plt.show()

结果查看此处

使用你的数据的示例2:

from sklearn.svm import SVCimport numpy as npimport matplotlib.pyplot as pltfrom sklearn import svm, datasetsfrom sklearn.datasets import fetch_20newsgroupsfrom sklearn.feature_extraction.text import CountVectorizer, TfidfTransformerfrom sklearn.decomposition import PCAfrom sklearn.pipeline import Pipelineimport matplotlib.pyplot as pltnewsgroups_train = fetch_20newsgroups(subset='train',                                       categories=['alt.atheism', 'sci.space'])pipeline = Pipeline([('vect', CountVectorizer()), ('tfidf', TfidfTransformer())])        X = pipeline.fit_transform(newsgroups_train.data).todense()# 仅选择2个特征X = np.array(X)X = X[:, [0,1]]y = newsgroups_train.targetdef make_meshgrid(x, y, h=.02):    x_min, x_max = x.min() - 1, x.max() + 1    y_min, y_max = y.min() - 1, y.max() + 1    xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))    return xx, yydef plot_contours(ax, clf, xx, yy, **params):    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])    Z = Z.reshape(xx.shape)    out = ax.contourf(xx, yy, Z, **params)    return outmodel = svm.SVC(kernel='linear')clf = model.fit(X, y)fig, ax = plt.subplots()# 图表标题title = ('线性SVC的决策表面')# 设置绘图网格X0, X1 = X[:, 0], X[:, 1]xx, yy = make_meshgrid(X0, X1)plot_contours(ax, clf, xx, yy, cmap=plt.cm.coolwarm, alpha=0.8)ax.scatter(X0, X1, c=y, cmap=plt.cm.coolwarm, s=20, edgecolors='k')ax.set_ylabel('此处填写y轴标签')ax.set_xlabel('此处填写x轴标签')ax.set_xticks(())ax.set_yticks(())ax.set_title(title)ax.legend()plt.show()

结果

使用你的数据

重要说明:

在第二种情况下,由于我们随机选择了仅2个特征来创建图表,所以图表的效果不佳。一种使其效果更好的方法如下:你可以使用单变量排名方法(例如ANOVA F值测试)来找出你最初拥有的22464个特征中的最佳前2个特征。然后使用这些前2个特征,你可以创建一个漂亮的分离表面图表。


Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注