【发布时间】:2020-01-14 02:29:08
【问题描述】:
我在 Python 的 Scikit-Learn 中使用 Kmeans 对文本数据进行聚类。 我对数据进行矢量化有问题,因为当我使用不同的矢量化器时会得到非常不同的结果。 我想对文本数据进行聚类(数据是关于美国政治的 instagram cmets),我想找到每个聚类的关键词。但我不知道我应该使用什么矢量化器
例如当我使用时:
cv = CountVectorizer(analyzer = 'word', max_features = 8000, preprocessor=None, lowercase=True, tokenizer=None, stop_words = 'english')
x = cv.fit_transform(x)
#should I scale x value?
#x = scale(x, with_mean=False)
#If I do this I get the graph just one dot and silhouette_score less than 0.01
根据silhouette_score,我的最佳聚类数是 2,这给了我 0.87 的分数。我的图表如下所示:
当我使用时:
cv = TfidfVectorizer(analyzer = 'word',max_features = 8000, preprocessor=None, lowercase=True, tokenizer=None, stop_words = 'english')
x = cv.fit_transform(x)
根据silhouette_score,我得到的最佳聚类数是 13,这给了我 0.0159 的分数。我的图表如下所示:
这就是我进行聚类的方式:
my_list = []
list_of_clusters = []
for i in range(2,15):
kmeans = KMeans(n_clusters = i, init = 'k-means++', random_state = 42)
kmeans.fit(x)
my_list.append(kmeans.inertia_)
cluster_labels = kmeans.fit_predict(x)
silhouette_avg = silhouette_score(x, cluster_labels)
print(round(silhouette_avg,2))
list_of_clusters.append(round(silhouette_avg, 1))
plt.plot(range(2,15),my_list)
plt.show()
number_of_clusters = max(list_of_clusters)
number_of_clusters = list_of_clusters.index(number_of_clusters)+2
print('Number of clusters: ', number_of_clusters)
kmeans = KMeans(n_clusters = number_of_clusters, init = 'k-means++', random_state = 42)
kmeans.fit(x)
这就是我绘制数据的方式:
# reduce the features to 2D
pca = PCA(n_components=2, random_state=0)
reduced_features = pca.fit_transform(x.toarray())
# reduce the cluster centers to 2D
reduced_cluster_centers = pca.transform(kmeans.cluster_centers_)
plt.scatter(reduced_features[:,0], reduced_features[:,1], c=kmeans.predict(x), s=3)
plt.scatter(reduced_cluster_centers[:, 0], reduced_cluster_centers[:,1], marker='x', s=50, c='r')
plt.show()
我认为这是非常大的区别,所以我确定我做错了什么,但我不知道是什么。
感谢您的帮助:)
【问题讨论】:
标签: python scikit-learn