python - 使用 numpy 数组函数更新元素

标签 python algorithm numpy

我正在尝试为小型项目实现 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/

相关文章:

python - 如何返回值名称(Alive、Dead)而不是返回 1 和 0

python - 如何将 XML 文件转换为 Pandas 数据框

java - Java中给定的long类型的正数的所有数字的总和

java - 计算递归算法的时间复杂度。

python - 在 Python 中快速笛卡尔到极坐标到笛卡尔

python - 动态类定义的 pickle

python - 更改 matplotlib 中选择的标记颜色

algorithm - 如何生成分配球到箱子的所有组合,包括空分配和满分配?

python - 您可以通过 numpy 数组广播字典定义吗?

python - 比较两个不同大小的数组 - python numpy