【问题标题】:More efficient way of computing distance matrix in Python在 Python 中计算距离矩阵的更有效方法
【发布时间】:2016-09-22 08:18:20
【问题描述】:

大家好,我正在尝试编写代码(使用 python 2),它返回一个包含所有行对之间距离的矩阵。下面是我写的一个实现。它按预期工作,但随着行数变大会变得非常慢。因此,我想知道是否有人对如何使代码更高效地处理大量行有任何建议。

提前致谢

def gendist(x,alpha=2):
    (n,p) = x.shape
    len = 0
    for ii in range(1,n):
        len = len + ii
    d = np.empty((len,p))
    ind = 0
    for ii in range(0,n):
        for jj in range(1,n):
            if ii < jj:
                d[ind,] = (x[ii,]-x[jj,])**alpha
                ind = ind + 1
    return d

【问题讨论】:

标签: python performance distance-matrix


【解决方案1】:

我看到你使用X.shape,对我来说,假设你使用NumPy

代码:

#!/usr/bin/env python3
import numpy as np
import scipy.spatial.distance as dist

a = np.random.randint(0, 10, (5, 3))
b = dist.pdist(a)
print('Matrix:')
print(a)
print('Pdist')
for d in b:
    print(d)

输出:

Matrix:
[[4 7 6]
 [8 2 8]
 [8 3 5]
 [2 4 7]
 [0 7 5]]
Pdist
6.7082039325
5.74456264654
3.74165738677
4.12310562562
3.16227766017
6.40312423743
9.89949493661
6.40312423743
8.94427191
4.12310562562

其中组合的顺序为 (0,1), (0,2), (0,3), (0,4), (1,2), (1,3), (1,4) , (2,3), (2,4), ...

默认度量是欧几里得距离。 请参阅 pdist 以应用其他指标。

【讨论】:

    【解决方案2】:

    没有 scipy(可以在没有 scipy 的情况下获得 numpy,例如使用 Abaqus 安装)会有点困难。

    def gendist(x,alpha=2):
        xCopies=x.repeat(x.shape[0],axis=0).reshape(np.conatenate(([a.shape[0]],a.shape))
        #n x n x p matrix filled with copies of x
        xVecs=xCopies-xCopies.swapaxes(0,1) #matrix of distance vectors
        xDists=np.sum(xVecs**alpha,axis=-1)**(1/alpha) #n x n matrix of distances
        Return xDists
    

    这应该是健壮的,至少这是我必须使用的。

    【讨论】:

      【解决方案3】:

      我认为您正在寻找的是 sklearn pairwise_distances。 scipy distance_matrix 在我的机器上需要大约 115 秒来计算 512 维向量上的 10Kx10K 距离矩阵。 scipy cdist 需要约 50 秒。 sklearn pairwise_distances 需要约 9 秒。来自文档:

      请注意,对于“cityblock”、“cosine”和“euclidean”(其中 是有效的 scipy.spatial.distance 指标),scikit-learn 将使用实现,它更快并且支持 稀疏矩阵(“cityblock”除外)。

      【讨论】:

        猜你喜欢
        • 2018-11-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-05
        • 1970-01-01
        • 2023-03-18
        相关资源
        最近更新 更多