gpt4 book ai didi

python - kmeans 聚类 : how to access cluster datapoints

转载 作者:太空宇宙 更新时间:2023-11-04 02:58:23 25 4
gpt4 key购买 nike

这是我从 kmeans scikit 文档和一篇讨论 kmeans 的博客文章中整理出来的 kmeans 算法的实现:

#http://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html
#http://fromdatawithlove.thegovans.us/2013/05/clustering-using-scikit-learn.html

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

X = np.array([[10, 2 , 9], [1, 4 , 3], [1, 0 , 3],
[4, 2 , 1], [4, 4 , 7], [4, 0 , 5], [4, 6 , 3],[4, 1 , 7],[5, 2 , 3],[6, 3 , 3],[7, 4 , 13]])
kmeans = KMeans(n_clusters=3, random_state=0).fit(X)

k = 3
kmeans.fit(X)

labels = kmeans.labels_
centroids = kmeans.cluster_centers_

for i in range(k):
# select only data observations with cluster label == i
ds = X[np.where(labels==i)]
# plot the data observations
pyplot.plot(ds[:,0],ds[:,1],'o')
# plot the centroids
lines = pyplot.plot(centroids[i,0],centroids[i,1],'kx')
# make the centroid x's bigger
pyplot.setp(lines,ms=15.0)
pyplot.setp(lines,mew=2.0)
pyplot.show()

print(kmeans.cluster_centers_.squeeze())

如何打印/访问 k 个集群中每个集群的数据点。

if k = 3 : 
cluster 1 : [10, 2 , 9], [1, 4 , 3], [1, 0 , 3]
cluster 2 : [4, 0 , 5], [4, 6 , 3],[4, 1 , 7],[5, 2 , 3],[6, 3 , 3],[7, 4 , 13]
cluster 3 : [4, 2 , 1], [4, 4 , 7]

阅读 http://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html kmeans 对象上没有用于此的属性或方法吗?

更新:

kmeans.labels_ 返回 array([1, 0, 2, 0, 2, 2, 0, 2, 0, 0, 1], dtype=int32)

但这如何显示 3 个集群中每个集群中的数据点?

最佳答案

如果您使用适合的 KMeans 对象的 _labels 属性,您将获得每个训练向量的聚类分配数组。标签数组的顺序与您的训练数据相同,因此您可以压缩它们或为每个唯一标签执行 numpy.where()。

关于python - kmeans 聚类 : how to access cluster datapoints,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41703334/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com