我使用 KMeans 进行聚类,如下所示,但我不知道要像下图所示那样可视化聚类以查看客户的满意度。
代码:
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans
from sklearn.metrics import adjusted_rand_score
documents = ["This little kitty came to play when I was eating at a restaurant.",
"Merley has the best squooshy kitten belly.",
"Google Translate app is incredible.",
"If you open 100 tab in google you get a smileyface.",
"Best cat photo I've ever taken.",
"Climbing ninja cat.",
"Impressed with google map feedback.",
"Key promoter extension for Google Chrome."]
vectorizer = TfidfVectorizer(stop_words='english')
X = vectorizer.fit_transform(documents)
true_k = 3
model = KMeans(n_clusters=true_k, init='k-means++', max_iter=100,n_init=1)
model.fit(X)
最佳答案
假设您有办法知道 k-means 的哪个分区代表哪种情绪,您可以绘制饼图如下:
print(model.labels_) # For illustration, you can see which sentence is in which cluster
# Here we get the proportions
nb_samples = [sum(model.labels_ == j) for j in range(true_k)]
# On the next line the order is RANDOM. I do NOT know which cluster represents what.
# The first label should represent samples in cluster 0, and so on
labels = 'positive', 'neutral', 'negative'
colors = ['gold', 'red', 'lightblue'] # Same size as labels
# Pie chart
plt.pie(nb_samples, labels=labels, colors=colors, autopct='%1.1f%%')
plt.axis('equal')
plt.show()
也不是,多次运行会根据哪个聚类代表哪个类别给出不同的结果。
这可以通过设置 numpy 随机种子来避免。
import numpy as np
np.random.seed(42) # Or any other integer
关于python - Kmeans 返回的集群可视化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55837982/