我有以下代码,使用scikit-learn对一些示例文本进行聚类。
train = ["is this good?", "this is bad", "some other text here", "i am hero", "blue jeans", "red carpet", "red dog", "blue sweater", "red hat", "kitty blue"]
vect = TfidfVectorizer()
X = vect.fit_transform(train)
clf = KMeans(n_clusters=3)
clf.fit(X)
centroids = clf.cluster_centers_
plt.scatter(centroids[:, 0], centroids[:, 1], marker='x', s=80, linewidths=5)
plt.show()
我无法解决的问题是如何绘制聚类结果。X 是一个 csr_matrix。我想要的是每个结果的 (x, y) 坐标来进行绘图。
谢谢
回答:
你的 tf-idf 矩阵最终是 3 x 17,所以你需要进行某种投影或降维处理,以在二维中获得质心。你有几种选择;这里是一个使用 t-SNE 的示例:
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.manifold import TSNE
train = ["is this good?", "this is bad", "some other text here", "i am hero", "blue jeans", "red carpet", "red dog", "blue sweater", "red hat", "kitty blue"]
vect = TfidfVectorizer()
X = vect.fit_transform(train)
random_state = 1
clf = KMeans(n_clusters=3, random_state = random_state)
data = clf.fit(X)
centroids = clf.cluster_centers_
tsne_init = 'pca' # 也可以是 'random'
tsne_perplexity = 20.0
tsne_early_exaggeration = 4.0
tsne_learning_rate = 1000
model = TSNE(n_components=2, random_state=random_state, init=tsne_init, perplexity=tsne_perplexity, early_exaggeration=tsne_early_exaggeration, learning_rate=tsne_learning_rate)
transformed_centroids = model.fit_transform(centroids)
print transformed_centroids
plt.scatter(transformed_centroids[:, 0], transformed_centroids[:, 1], marker='x')
plt.show()
在你的示例中,如果你使用 PCA 来初始化 t-SNE,你会得到广泛分布的质心;如果你使用随机初始化,你会得到很小的质心和一张不有趣的图。