有一些我想聚类的坐标。使用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被聚为第七个簇。如何从集群中获取坐标?
发布于 2021-02-22 17:31:13
我假设你想把坐标影响到第七个星系团。您可以通过将结果存储在字典中来执行此操作:
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)来获得。
https://stackoverflow.com/questions/66312861
复制相似问题