以列表格式获取 KMeans 之后的聚类点

Posted

技术标签:

【中文标题】以列表格式获取 KMeans 之后的聚类点【英文标题】:Get cluster points after KMeans in a list format 【发布时间】:2018-10-22 03:43:52 【问题描述】:

假设我使用sklearn's K-means 对一个数据集进行聚类。

我可以使用KMeans.cluster_centers_ 轻松查看质心,但我需要在获得质心时获取集群。

我该怎么做?

【问题讨论】:

【参考方案1】:

您需要执行以下操作(请参阅我的代码中的 cmets):

import numpy as np
from sklearn.cluster import KMeans
from sklearn import datasets

np.random.seed(0)

# Use Iris data
iris = datasets.load_iris()
X = iris.data
y = iris.target

# KMeans with 3 clusters
clf =  KMeans(n_clusters=3)
clf.fit(X,y)

#Coordinates of cluster centers with shape [n_clusters, n_features]
clf.cluster_centers_

#Labels of each point
clf.labels_

# !! Get the indices of the points for each corresponding cluster
mydict = i: np.where(clf.labels_ == i)[0] for i in range(clf.n_clusters)

# Transform the dictionary into list
dictlist = []
for key, value in mydict.iteritems():
    temp = [key,value]
    dictlist.append(temp)

结果

0: array([ 50,  51,  53,  54,  55,  56,  57,  58,  59,  60,  61,  62,  63,
            64,  65,  66,  67,  68,  69,  70,  71,  72,  73,  74,  75,  76,
            78,  79,  80,  81,  82,  83,  84,  85,  86,  87,  88,  89,  90,
            91,  92,  93,  94,  95,  96,  97,  98,  99, 101, 106, 113, 114,
           119, 121, 123, 126, 127, 133, 138, 142, 146, 149]),
 1: array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
           17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
           34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
 2: array([ 52,  77, 100, 102, 103, 104, 105, 107, 108, 109, 110, 111, 112,
           115, 116, 117, 118, 120, 122, 124, 125, 128, 129, 130, 131, 132,
           134, 135, 136, 137, 139, 140, 141, 143, 144, 145, 147, 148])


[[0, array([ 50,  51,  53,  54,  55,  56,  57,  58,  59,  60,  61,  62,  63,
             64,  65,  66,  67,  68,  69,  70,  71,  72,  73,  74,  75,  76,
             78,  79,  80,  81,  82,  83,  84,  85,  86,  87,  88,  89,  90,
             91,  92,  93,  94,  95,  96,  97,  98,  99, 101, 106, 113, 114,
             119, 121, 123, 126, 127, 133, 138, 142, 146, 149])],
 [1, array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
            17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
            34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49])],
 [2, array([ 52,  77, 100, 102, 103, 104, 105, 107, 108, 109, 110, 111, 112,
             115, 116, 117, 118, 120, 122, 124, 125, 128, 129, 130, 131, 132,
             134, 135, 136, 137, 139, 140, 141, 143, 144, 145, 147, 148])]]

【讨论】:

感谢您的回复,但我需要查看每个集群及其数据点作为列表。我该怎么做? AttributeError: 'dict' 对象没有属性 'iteritems'【参考方案2】:

您可能会寻找属性labels_

【讨论】:

你能写一个示例代码吗?这对我很有帮助。【参考方案3】:

这是一个很长的问题,所以我认为您已经有了答案,但让我发布,因为有人可以从中受益。我们可以只使用它的质心来获得聚类点。 Scikit-learn 有一个名为 cluster_centers_ 的属性,它返回 n_clusters 和 n_features。非常简单的代码,你可以在下面看到它来描述集群中心,请浏览代码中的所有 cmets。

import numpy as np
from sklearn.cluster import KMeans
from sklearn import datasets
from sklearn.preprocessing import StandardScaler

# Iris data
iris = datasets.load_iris()
X = iris.data
# Standardization
std_data = StandardScaler().fit_transform(X)

# KMeans clustering with 3 clusters
clf =  KMeans(n_clusters = 3)
clf.fit(std_data)

# Coordinates of cluster centers with shape [n_clusters, n_features]
# As we have 3 cluster with 4 features
print("Shape of cluster:", clf.cluster_centers_.shape)

# Scatter plot to see each cluster points visually 
plt.scatter(std_data[:,0], std_data[:,1], c = clf.labels_, cmap = "rainbow")
plt.title("K-means Clustering of iris data flower")
plt.show()

# Putting ndarray cluster center into pandas DataFrame
coef_df = pd.DataFrame(clf.cluster_centers_, columns = ["Sepal length", "Sepal width", "Petal length", "Petal width"])
print("\nDataFrame containg each cluster points with feature names:\n", coef_df)

# converting ndarray to a nested list 
ndarray2list = clf.cluster_centers_.tolist()
print("\nList of clusterd points:\n")
print(ndarray2list)

输出: This is the output of the above code.

【讨论】:

以上是关于以列表格式获取 KMeans 之后的聚类点的主要内容,如果未能解决你的问题,请参考以下文章

基于线性接近度的聚类点

如何使用 KMEANS 计算每个记录的聚类距离?

关于k-means算法的聚类分析

记一次百G数据的聚类算法实施过程

R语言聚类分析之基于划分的聚类KMeans实战:基于菌株数据

用于在 KMeans 聚类中选择适当数量的聚类的轮廓索引