使用scikit-learn.k-means库输出最接近每个聚类中心的50个样本 [英] Output 50 samples closest to each cluster center using scikit-learn.k-means library
问题描述
我使用python scikit-learn库为5000多个样本拟合了k-means算法.我想将最接近聚类中心的50个样本作为输出.如何执行此任务?
I have fitted a k-means algorithm on 5000+ samples using the python scikit-learn library. I want to have the 50 samples closest to a cluster center as an output. How do I perform this task?
推荐答案
如果km
是k均值模型,则数组X
中每个点到j
的重心的距离是>
If km
is the k-means model, the distance to the j
'th centroid for each point in an array X
is
d = km.transform(X)[:, j]
这给出了一个len(X)
距离的数组.最接近质心j
的50个索引是
This gives an array of len(X)
distances. The indices of the 50 closest to centroid j
are
ind = np.argsort(d)[::-1][:50]
最接近质心的50个点是
so the 50 points closest to the centroids are
X[ind]
(或如果您使用 argpartition
最近有足够的NumPy,因为速度要快得多.
(or use argpartition
if you have a recent enough NumPy, because that's a lot faster).
这篇关于使用scikit-learn.k-means库输出最接近每个聚类中心的50个样本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!