【发布时间】:2018-05-12 15:35:13
【问题描述】:
def closest_centroid(points, centroids):
"""returns an array containing the index to the nearest centroid for each point"""
distances = np.sqrt(((points - centroids[:, np.newaxis])**2).sum(axis=2))
return np.argmin(distances, axis=0)
有人能解释一下这个函数的具体工作原理吗?我目前得到points,它看起来像:
31998888119 0.94 34
23423423422 0.45 43
....
等等。在这个 numpy 数组中,points[1] 将是长 ID,而 points[2] 是 0.94,points[3] 将是 34 的第一个条目。
Centroids 只是从这个特定数组中随机选择的:
def initialize_centroids(points, k):
"""returns k centroids from the initial points"""
centroids = points.copy()
np.random.shuffle(centroids)
return centroids[:k]
现在我想从 points 的值中获取欧几里得距离,忽略 ID 的第一列和 centroids(再次忽略第一列)。我不完全理解distances = np.sqrt(((points - centroids[:, np.newaxis])**2).sum(axis=2)) 行的语法。为什么我们在第三列中求和,而新轴的减法:np.newaxis?我还应该沿着哪个轴使np.argmin 工作?
【问题讨论】:
标签: python numpy k-means euclidean-distance