我正在尝试为小型项目实现 k 均值聚类算法。我偶然发现 this article这表明
K-Means is much faster if you write the update functions using operations on numpy arrays, instead of manually looping over the arrays and updating the values yourself.
我正在对数组的每个元素使用迭代来更新它。对于数据集 z
中的每个元素,我通过迭代每个元素从最近的质心分配簇数组。
for i in range(z):
clstr[i] = closest_center(data[i], cen)
我的更新函数是
def closest_center(x, clist):
dlist = [fabs(x - i) for i in clist]
return clist[dlist.index(min(dlist))]
由于我使用的是灰度图像,所以我使用绝对值来计算欧氏距离。
我注意到 opencv
也有这个算法。执行算法不到 2 秒,而我的算法需要 70 多秒。我可以知道这篇文章在暗示什么吗?
我的图像被导入为灰度,并表示为 2d numpy 数组。我进一步转换为一维数组,因为它更容易处理一维数组。
最佳答案
列表理解可能会减慢执行速度。我会建议向量化函数closest_center
。这对于一维数组来说很简单:
import numpy as np
def closest_center(x, clist):
return clist[np.argmin(np.abs(x - clist))]
关于python - 使用 numpy 数组函数更新元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36828543/