有些坐标我想聚类。使用kmeans聚类的结果
[[0, 107], [0, 108], [0, 109], [0, 115], [0, 116],
[0, 117], [0, 118], [0, 125], [0, 126], [0, 127],
[0, 128], [0, 135], [0, 136], [0, 194], [0, 195],
[1, 107], [1, 108], [1, 109], [1, 110], [1, 114],
[1, 115], [1, 116], [1, 117], [1, 118], [1, 119]...]
使用kmeans聚类的结果
from sklearn.cluster import KMeans
num_clusters = 9
km = KMeans(n_clusters=num_clusters)
km_fit = km.fit(nonzero_pred_sub)
>>>array([7, 7, 7, 1, 1, 1, 1, 5, 5, 5, 5, 3, 3, 0, 0, 7, 7, 7, 7, 1, 1, 1,
1, 1, 1, 5, 5, 5...]
我想知道第 i 个簇的坐标 例如,我需要第一个簇的元素,我可以假设 [0, 107], [0, 108], [0, 109] 被聚类到第 7 个簇中。 如何从集群中获取坐标?
答案 0 :(得分:1)
我假设您希望坐标影响到第 7 个集群。您可以通过将结果存储在字典中来实现:
from sklearn.cluster import KMeans
km = KMeans(n_clusters=9)
km_fit = km.fit(nonzero_pred_sub)
d = dict() # dictionary linking cluster id to coordinates
for i in range(len(km_fit)):
cluster_id = km_fit[i]
if cluster_id not in d:
d[cluster_id] = []
d[cluster_id].append(nonzero_pred_sub[i])
# that way you can access the 7th cluster coordinates like this
d[7]
>>> [[0, 107], [0, 108], [0, 109], [1, 107], [1, 108], [1, 109], [1, 110], ...]
要删除循环中的“if”部分,您可以尝试查看 defaultdict
对象。
您当然也可以使用 Pandas 数据框来管理它,以便更轻松地处理更复杂的结果。
如果我误解了你的问题,而你想要的是第 i 个簇的中心坐标,你可以通过调用 km_fit.cluster_centers_[i]
(cf. doc) 来获得。