【发布时间】:2012-02-08 06:50:32
【问题描述】:
我正在尝试在 Python 中实现 K-means 算法(我知道有相关库,但我想学习如何自己实现它。)这是我遇到问题的函数:
def AssignPoints(points, centroids):
"""
Takes two arguments:
points is a numpy array such that points.shape = m , n where m is number of examples,
and n is number of dimensions.
centroids is numpy array such that centroids.shape = k , n where k is number of centroids.
k < m should hold.
Returns:
numpy array A such that A.shape = (m,) and A[i] is index of the centroid which points[i] is assigned to.
"""
m ,n = points.shape
temp = []
for i in xrange(n):
temp.append(np.subtract.outer(points[:,i],centroids[:,i]))
distances = np.hypot(*temp)
return distances.argmin(axis=1)
这个函数的目的,给定 n 维空间中的 m 个点,以及 n 维空间中的 k 个质心,生成一个 (x1 x2 x3 x4 ... xm) 的 numpy 数组,其中 x1 是最接近的质心的索引第一点。这工作正常,直到我用 4 维示例进行了尝试。当我尝试放置 4 维示例时,出现此错误:
File "/path/to/the/kmeans.py", line 28, in AssignPoints
distances = np.hypot(*temp)
ValueError: invalid number of arguments
我该如何解决这个问题,或者如果我不能,你建议我如何计算我要在这里计算的内容?
我的答案
def AssignPoints(points, centroids):
m ,n = points.shape
temp = []
for i in xrange(n):
temp.append(np.subtract.outer(points[:,i],centroids[:,i]))
for i in xrange(len(temp)):
temp[i] = temp[i] ** 2
distances = np.add.reduce(temp) ** 0.5
return distances.argmin(axis=1)
【问题讨论】:
-
您意识到
len(temp) == n和np.hypot只承认三个参数,不是吗? -
说实话,我对 np.hypot 的作用不是很清楚。当我第一次编写该函数时,我只是从另一个问题中复制了它。我认为无论尺寸如何,这都会起作用。你建议我应该如何编写这个函数?
-
np.hypot计算三角形的斜边。它接受两个参数:leg1和leg2,以及第三个可选参数,用于放置结果。当然,这个想法是一次性计算很多斜边,因此leg1和leg2应该是数组,包含你要计算的n三角形的相应边。