简体   繁体   English

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

[英]Compute distances between 2 matrix of vector

I have a problem with Numpy broadcasting between two matrix.我在两个矩阵之间进行 Numpy 广播时遇到问题。 I need to compute the euclidean distance between 2 matrix for a knn classifier.我需要计算 knn 分类器的 2 个矩阵之间的欧几里得距离。 I have already done it with two loop and one loop but it too slow.我已经用两个循环和一个循环完成了它,但它太慢了。 I'm looking for doing it with Numpy broadcasting without any explicit loop but I'm stuck.我正在寻找没有任何显式循环的 Numpy 广播,但我被卡住了。

The two loop version:两个循环版本:

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

The one loop version:单循环版本:

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

The shape of X_train is (5000, 784) and X is (500,784). X_train 的形状是 (5000, 784),X 是 (500,784)。 The output need to have the shape (500, 5000).输出需要具有形状 (500, 5000)。

Have you any idea to help me?你有什么想法可以帮我吗?

You can use scipy's euclidean distance:您可以使用 scipy 的欧几里德距离:

from scipy.spatial import distance
x1 = np.asarray([[1,2,3],[4,5,6]])
x2 = np.asarray([[1,2,40],[14,5,6]])

for i in range(0,x1.shape[0]):
    print distance.euclidean(x1[i], x2[i])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM