简体   繁体   English

使用MatplotLib可视化来自SKlearn Kmeans的稀疏输入

[英]Visualize Sparse Input from SKlearn Kmeans with MatplotLib

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans

cc_tfid = TfidfVectorizer().fit_transform(cc_corpus)
cc_km = KMeans(n_clusters = 3, init = 'k-means++', max_iter = 99, n_init = 4, verbose = False )
cc_km.fit(cc_tfid)

plt.scatter(cc_tfid[:, 0], cc_tfid[:, 1])
centroids = cc_km.cluster_centers_
plt.scatter(centroids[:, 0], centroids[:, 1], c='red', s=200, alpha=0.5)
plt.show()

I can visualize the centroids but not the points because they are from a sparse matrix. 我可以显示质心,但不能显示点,因为它们来自稀疏矩阵。 How do I plot this please? 我该如何绘制?

You can convert the sparse matrices to dense arrays using .toarray() : 您可以使用.toarray()将稀疏矩阵转换为密集数组:

plt.scatter(cc_tfid[:, 0].toarray(), cc_tfid[:, 1].toarray())

Note that projecting all points on the first two dimensions of the TF-IDF vector space is likely to result in quite the useless plot. 请注意,将所有点投影在TF-IDF向量空间的前两个维度上可能会导致非常无用的绘图。 You would be better off piping the data through PCA or t-SNE to reduce the dimensionality to 2. 您最好通过PCA或t-SNE传递数据,以将维数减少到2。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM