python - 是否可以在 Python 中加速这个循环?

标签 python numpy

numpy.narray 中映射函数的常规方法,例如 np.array[map(some_func,x)]vectorize(f)( x) 无法提供索引。 以下代码只是一个在许多应用程序中常见的简单示例。

dis_mat = np.zeros([feature_mat.shape[0], feature_mat.shape[0]])

for i in range(feature_mat.shape[0]):
    for j in range(i, feature_mat.shape[0]):
        dis_mat[i, j] = np.linalg.norm(
            feature_mat[i, :] - feature_mat[j, :]
        )
        dis_mat[j, i] = dis_mat[i, j]

有没有办法加快速度?


感谢您的帮助!使用 @user2357112 评论的函数,加快此代码速度的最快方法是:

    from scipy.spatial.distance import pdist,squareform
    dis_mat = squareform(pdist(feature_mat))

@Julienmethod 如果 feature_mat 很小也不错,但是当 feature_mat 到 2000 年为 1000 时,它需要将近 40 GB 的内存。

最佳答案

SciPy 带有一个专门用于计算您正在计算的成对距离类型的函数。它是 scipy.spatial.distance.pdist , 它以压缩格式生成距离,基本上只存储距离矩阵的上三角形,但您可以使用 scipy.spatial.distance.squareform 将结果转换为正方形形式:

from scipy.spatial.distance import pdist, squareform

distance_matrix = squareform(pdist(feature_mat))

这样做的好处是避免了直接矢量化解决方案所需的巨大中间数组,因此它更快并且适用于更大的输入。它失去了到 an approach that uses algebraic manipulations to have dot handle the heavy lifting 的时间。 ,不过。

pdist 还支持多种替代距离指标,如果您决定想要欧几里德距离以外的其他指标。

# Manhattan distance!
distance_matrix = squareform(pdist(feature_mat, 'cityblock'))

# Cosine distance!
distance_matrix = squareform(pdist(feature_mat, 'cosine'))

# Correlation distance!
distance_matrix = squareform(pdist(feature_mat, 'correlation'))

# And more! Check out the docs.

关于python - 是否可以在 Python 中加速这个循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47566072/

相关文章:

python - pandas str.split给我一个意想不到的语法错误

python - 列表展平的时间复杂度

python - h5py:如何使用keys()循环HDF5组和数据集

python - 二维数组上的 Numpy 滚动窗口,作为具有嵌套数组作为数据值的一维数组

c++ - libtorch 中 numpy.spacing(1) 的等价物是什么?

python - 使用 genfromtxt 导入 numpy 中缺失值的 csv 数据

python - 将列表与其他列表的元素按保留顺序进行比较

python - 正则表达式的pattern.match不起作用

python - 在 numpy 中,将 3 维数组的第二维乘以 1 维数组的最快方法是什么?

python - 在 pandas.DataFrame 中保留最后 24 小时的日志