计算向量的2个矩阵之间的距离

时间:2018-09-29 09:16:01

标签: python numpy numpy-broadcasting

我对两个矩阵之间的Numpy广播有问题。我需要为knn分类器计算2个矩阵之间的欧式距离。我已经用两个循环和一个循环完成了,但是速度太慢了。我正在寻找不带任何显式循环的Numpy广播来做到这一点,但我遇到了麻烦。

两个循环的版本:

num_test = X.shape[0]
num_train = self.X_train.shape[0]
dists = np.zeros((num_test, num_train))
for i in range(num_test):
    for j in range(num_train):
        dists[i, j] = np.sqrt(np.sum(np.power(self.X_train[j, :] - X[i, :], 2)))
return dists

一个循环版本:

num_test = X.shape[0]
num_train = self.X_train.shape[0]
dists = np.zeros((num_test, num_train))
for i in range(num_test):
    dists[i, :] = np.sqrt(np.sum(np.power(self.X_train - X[i, :], 2), axis=1))
return dists

X_train的形状为(5000,784),X为(500,784)。输出的形状必须为(500,5000)。

您有什么办法帮助我吗?

1 个答案:

答案 0 :(得分:1)

您可以使用scipy的欧式距离:

[root@localhost mbuni-1.5.0]# make install
Making install in autotools
make[1]: Entering directory `/home/roy/mbuni-1.5.0/autotools'
make[2]: Entering directory `/home/roy/mbuni-1.5.0/autotools'
make[2]: Nothing to be done for `install-exec-am'.
make[2]: Nothing to be done for `install-data-am'.
make[2]: Leaving directory `/home/roy/mbuni-1.5.0/autotools'
make[1]: Leaving directory `/home/roy/mbuni-1.5.0/autotools'
Making install in doc
make[1]: Entering directory `/home/roy/mbuni-1.5.0/doc'
Making install in examples
make[2]: Entering directory `/home/roy/mbuni-1.5.0/doc/examples'
make[3]: Entering directory `/home/roy/mbuni-1.5.0/doc/examples'
make[3]: Nothing to be done for `install-exec-am'.
make[3]: Nothing to be done for `install-data-am'.
make[3]: Leaving directory `/home/roy/mbuni-1.5.0/doc/examples'
make[2]: Leaving directory `/home/roy/mbuni-1.5.0/doc/examples'
Making install in images
make[2]: Entering directory `/home/roy/mbuni-1.5.0/doc/images'
make[3]: Entering directory `/home/roy/mbuni-1.5.0/doc/images'
make[3]: Nothing to be done for `install-exec-am'.
make[3]: Nothing to be done for `install-data-am'.
make[3]: Leaving directory `/home/roy/mbuni-1.5.0/doc/images'
make[2]: Leaving directory `/home/roy/mbuni-1.5.0/doc/images'
make[2]: Entering directory `/home/roy/mbuni-1.5.0/doc'
make[3]: Entering directory `/home/roy/mbuni-1.5.0/doc'
make[3]: Nothing to be done for `install-exec-am'.
make[3]: Nothing to be done for `install-data-am'.
make[3]: Leaving directory `/home/roy/mbuni-1.5.0/doc'
make[2]: Leaving directory `/home/roy/mbuni-1.5.0/doc'
make[1]: Leaving directory `/home/roy/mbuni-1.5.0/doc'
Making install in mmlib
make[1]: Entering directory `/home/roy/mbuni-1.5.0/mmlib'
rm -f libmms.a
make[1]: AR@: Command not found
make[1]: *** [libmms.a] Error 127
make[1]: Leaving directory `/home/roy/mbuni-1.5.0/mmlib'
make: *** [install-recursive] Error 1
[root@localhost mbuni-1.5.0]#