python - 如何使用sklearn找到最接近K的点的索引意味着聚类中心?
问题描述
我已经使用 python 的 sklearn 包进行 K-means 聚类。到目前为止,我能够使用以下代码获取集群中心的坐标。
import numpy as np
from sklearn.cluster import KMeans
p50 = np.load('tsnep400.npy')
kmeans = KMeans(n_clusters=50).fit(p50)
np.savetxt('kmeans_50clusters_centers_tsnep400', kmeans.cluster_centers_, fmt='%1.3f')
np.savetxt('kmeans_50clusters_tsnep400.dat', kmeans.labels_, fmt='%1.1d')
centroids = {i: np.where(kmeans.labels_ == i)[0] for i in range(kmeans.n_clusters)}
np.save('kmeans_50clusters_memebers_tsnep400.npy',centroids)
如何找到最接近聚类中心的点的索引?
解决方案
根据 scikit-learn 文档,该属性.labels_
包含每个点的标签,按它们的索引。因此,您可以使用它将每个点分组到一个集群中,然后计算到每个集群中心的距离。您可以为此使用以下代码:
from scipy.spatial.distance import euclidean
# Loop over all clusters and find index of closest point to the cluster center and append to closest_pt_idx list.
closest_pt_idx = []
for iclust in range(kmeans.n_clusters):
# get all points assigned to each cluster:
cluster_pts = p50[kmeans.labels_ == iclust]
# get all indices of points assigned to this cluster:
cluster_pts_indices = np.where(kmeans.labels_ == iclust)[0]
cluster_cen = kmeans.cluster_centers_[iclust]
min_idx = np.argmin([euclidean(p50[idx], cluster_cen) for idx in cluster_pts_indices])
# Testing:
print('closest point to cluster center: ', cluster_pts[min_idx])
print('closest index of point to cluster center: ', cluster_pts_indices[min_idx])
print(' ', p50[cluster_pts_indices[min_idx]])
closest_pt_idx.append(cluster_pts_indices[min_idx])
推荐阅读
- wordpress - 如何在 divi 代码块中使用 acf-number
- python - "
没有相应的文件和目录” - gitlab - 当包含 .yml 包含工作流规则时,CI 管道不会自动运行
- sapui5 - SAPUI5 与 SAP Business One (SQL Server)
- c# - 为什么只创建了一张表?
- css - wordpress中的英雄图像背景没有将它的孩子放在里面
- ruby - 在 ruby 中使用 octokit 在 github 中检索最新的发布版本和最后 3 个各自的提交
- c# - C# Web Api - Salesforce - 如何通过 api 调用而不是通过浏览器获取身份验证代码
- android - 如何在不中断振铃的情况下更新现有的振铃通知?
- python - 找到“Y”行时如何删除“X”行