python - 如何在python中使没有簇质心的簇不可见?

Posted

技术标签:

【中文标题】python - 如何在python中使没有簇质心的簇不可见?【英文标题】:How can i make invisible the clusters without cluster centroid in python? 【发布时间】:2021-04-04 16:29:59 【问题描述】:

我有一个包含 15 个集群的 kmeans 集群对象。我重新排列了对象的 cluster_centers 并从该列表中删除了 5 个特定的集群中心。现在我想可视化我的对象和集群中心。但我找不到使某些集群不可见的方法。

我最初的聚类数据是:

当我尝试使用其新的集群质心来可视化我的 kmeans 数据对象时,我得到以下输出:

我想让没有“X”标记的集群不可见。我该怎么做?

我用这段代码绘制了上面的图:

plt.scatter(X_train[:,0], X_train[:,1],c=TrainData[1],cmap='gist_rainbow')
plt.scatter(new_centroids[:,0], new_centroids[:, 1],s = 150, c = 'black', label = 'Centroid', marker="x")
plt.show()

【问题讨论】:

【参考方案1】:

您可以构建一个过滤器来排除不需要的值。 您需要使用 np.array(TrainData[1]) 将您的 TrainData[1] 转换为 numpy 数组(如果还没有的话)。

这是一个使用 sklearns 的示例KMeans


import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
import numpy as np

X_train = np.random.normal(size=(5000, 2))
kmeans_result = KMeans(n_clusters=15).fit(X_train)
new_centroids = kmeans_result.cluster_centers_
cluster_ids = kmeans_result.labels_
# cluster_ids = np.array(TrainData[1])

undesired1 = 3
undesired2 = 5
undesired3 = 7
filter = (cluster_ids != undesired1) & (cluster_ids != undesired2) & (cluster_ids != undesired3)
plt.scatter(X_train[filter, 0], X_train[filter, 1], c=cluster_ids[filter], cmap='gist_rainbow', alpha=0.4)
desired_centroid_ids = np.array([i for i in range(len(new_centroids)) if i not in [undesired1, undesired2, undesired3]])
plt.scatter(new_centroids[desired_centroid_ids, 0], new_centroids[desired_centroid_ids, 1], s=150, c='black',
            label='Centroid', marker="x")
plt.show()

【讨论】:

感谢您的回复,我尝试了代码但它给出了错误tuple indices must be integers or slices, not tuple TrainData的类型是什么?你能把它转换成一个numpy数组吗? df = make_blobs(n_samples=5000, n_features=15,centers=15, cluster_std=1,random_state=10) 我使用该代码定义了数据并将其拆分为训练和测试。 你可能可以使用TrainData[1][filter] 非常感谢您的回答,我试图在我之前创建的质心列表中分散质心,但它们出现在不相关的地方。为什么会这样?

以上是关于python - 如何在python中使没有簇质心的簇不可见?的主要内容,如果未能解决你的问题,请参考以下文章

K-均值聚类

在python中使用k-means聚类提取质心?

机器学习经典分类算法 —— k-均值算法(附python实现代码及数据集)

如何在opencv和python中使眼睛和鼻子变大或变小

如何在 python Scikit-learn 中获得凝聚聚类“质心”

Python质心中的KMeans位置不正确,我如何“取消缩放”它们?