【发布时间】:2021-06-10 17:25:45
【问题描述】:
我对一些数据X 进行了一些聚类分析,得到了标签y 和质心c。现在,我正在尝试计算X 和它们分配的集群的质心 c 之间的距离。当我们有少量点时,这很容易:
import numpy as np
# 10 random points in 3D space
X = np.random.rand(10,3)
# define the number of clusters, say 3
clusters = 3
# give each point a random label
# (in the real code this is found using KMeans, for example)
y = np.asarray([np.random.randint(0,clusters) for i in range(10)]).reshape(-1,1)
# randomly assign location of centroids
# (in the real code this is found using KMeans, for example)
c = np.random.rand(clusters,3)
# calculate distances
distances = []
for i in range(len(X)):
distances.append(np.linalg.norm(X[i]-c[y[i][0]]))
不幸的是,实际数据有更多行。有没有办法以某种方式对其进行矢量化(而不是使用for loop)?我似乎无法理解映射。
【问题讨论】:
-
你可以试试
scypi的cdist。
标签: python numpy cluster-analysis k-means