两组点之间的成对距离

2024-04-24 22:45:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用numpy来计算两组点之间的成对(平方)欧氏距离(存储为两个矩阵的行)。以下是我目前拥有的代码:

import numpy as np

def squared_pair_dist(x, y):
    x = np.expand_dims(x, -2)
    return np.sum(np.square(x - y), axis=-1)

p = 10
x = np.random.standard_normal((100, p))
y = np.random.standard_normal((1000, p))

d = squared_pair_dist(x, y) # get 100x1000 squared-distance matrix

我的程序大部分运行时间都在计算np.sum(np.square(x - y), axis=-1)。有没有办法加快速度?你知道吗

在我的应用程序中,p总是相对较小,典型值的范围是1到15。其他维度通常很大。你知道吗


Tags: 代码importnumpy距离distnp矩阵random