yas*_*sar 1 python numpy k-means
我正在尝试在 Python 中实现 K 均值算法(我知道有相应的库,但我想学习如何自己实现它。)这是我遇到问题的函数:
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)
Run Code Online (Sandbox Code Playgroud)
该函数的目的是,给定 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
Run Code Online (Sandbox Code Playgroud)
我该如何解决这个问题,或者如果我不能,你建议我如何计算我在这里想要计算的内容?
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)
Run Code Online (Sandbox Code Playgroud)
尝试这个:
np.sqrt(((points[np.newaxis] - centroids[:,np.newaxis]) ** 2).sum(axis=2)).argmin(axis=0)
Run Code Online (Sandbox Code Playgroud)
或者:
diff = points[np.newaxis] - centroids[:,np.newaxis]
norm = np.sqrt((diff*diff).sum(axis=2))
closest = norm.argmin(axis=0)
Run Code Online (Sandbox Code Playgroud)
不要问它在做什么:D
编辑:不,开玩笑。中间的广播 ( points[np.newaxis] - centroids[:,np.newaxis]) 是根据原始数组“制作”两个 3D 数组。结果是每个“平面”包含所有点与其中一个质心之间的差异。我们就这样称呼它吧diffs。
然后我们进行常规操作来计算欧氏距离(差值平方的平方根):np.sqrt((diffs ** 2).sum(axis=2))。我们最终得到一个(k, m)矩阵,其中第 0 行包含到 等的距离centroids[0]。因此,.argmin(axis=0)给出了您想要的结果。
| 归档时间: |
|
| 查看次数: |
3103 次 |
| 最近记录: |