[英]How do I find which cluster my data belongs to using Python?
I just ran PCA and then K-means Clustering algorithm on my data, after running the algorithm I get 3 clusters. 我只运行了PCA,然后对数据运行了K-means聚类算法,运行该算法后,我得到了3个聚类。 I am trying to figure out which clusters my input belongs to , in order to gather some qualitative attributes about the input. 我试图弄清楚我的输入属于哪个群集,以便收集有关输入的一些定性属性。 My input is customer ID and the variables I used for clustering were the spend patterns on certain products 我输入的是客户ID,用于聚类的变量是某些产品的支出模式
Below is the code I ran for K means, looking for some inputs on how to map this back to the source data to see which cluster the input belongs to : 以下是我为K表示的代码,寻找一些有关如何将此映射回源数据以查看输入属于哪个集群的输入:
kmeans= KMeans(n_clusters=3)
X_clustered=kmeans.fit_predict(x_10d)
LABEL_COLOR_MAP = {0:'r', 1 : 'g' ,2 : 'b'}
label_color=[LABEL_COLOR_MAP[l] for l in X_clustered]
#plot the scatter diagram
plt.figure(figsize=(7,7))
plt.scatter(x_10d[:,0],x_10d[:,2] , c=label_color, alpha=0.5)
plt.show()
Thanks 谢谢
If you want to add the cluster labels back in your dataframe, and assuming x_10d is your dataframe, you can do: 如果要将群集标签重新添加到数据框中,并假设x_10d是数据框,则可以执行以下操作:
x_10d["cluster"] = X_clustered x_10d [“ cluster”] = X_clustered
This will add a new column in your dataframe called "cluster" which should contain the cluster label for each of your rows. 这将在您的数据框中添加一个名为“群集”的新列,该列应包含每行的群集标签。
To group instances by their assigned cluster id 按实例分配的集群ID分组
N_CLUSTERS = 3
clusters = [x_10d[X_clustered == i] for i in range(N_CLUSTERS)]
# replace x_10d with where you want to retrieve data
# to have a look
for i, c in enumerate(clusters):
print('Cluster {} has {} members: {}...'.format(i, len(c), c[0]))
# which prints
# Cluster 0 has 37 members: [0.95690664 0.07578273 0.0094432 ]...
# Cluster 1 has 30 members: [0.03124354 0.97932615 0.47270528]...
# Cluster 2 has 33 members: [0.26331688 0.5039502 0.72568873]...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.