首页 > 解决方案 > 当数组具有不同维度时如何计算欧几里得距离?

问题描述

我正在尝试逐步计算欧几里得距离。由于欧几里得距离是:Dsqr = S+R-2*G,我分别计算每个元素。

这是我到目前为止所拥有的:

import numpy as np
# Create X matrix
X = np.array([[1,2],[3,4]])
Z = np.array([[1,4],[2,5],[3,6]])


# Calculate G from X using inner product
G = np.inner(X,Z)
print(G)


# Calculating S
def calculate_S(X, n, m):
    assert n == X.shape[0]
    assert m == X.shape[0]
    S = np.diag(np.inner(X,X))[:,None]
    S = S.repeat(3,axis=1)
    print("shape of S at the end ={}".format(S.shape))
    return S

n,d1=X.shape
m,d2=X.shape
S= calculate_S(X,n,m)
print(S)


# Calculating R
def calculate_R(Z, n, m):
    R = np.inner(Z,Z)
    R = np.diag(np.inner(Z,Z))[None,:]
    R = R.repeat(2,axis=0)
    print("shape of R at the end ={}".format(R.shape))
    return R

n,d1=Z.shape
m,d2=Z.shape
R = calculate_R(Z, n, m)
print(R)


# calcuate Dsqr
def l2distance(X,Z=None):
    if Z is None:
        Z=X;
    n,d1=X.shape
    m,d2=Z.shape
    assert (d1==d2),
    return S+R-2*G

Dsqr = l2distance(X,Z)
print(Dsqr)

这适用于我的示例中的数组。现在,当我将 X 和 Y 的值切换为:

X = np.random.rand(700,100)
Z = np.random.rand(800,100) 

我不确定如何重塑数组以使上述功能正常工作。我做了很多研究,到处都能找到两个数组很简单并且尺寸完全匹配的例子。

因此,任何建议都值得赞赏。

标签: python-3.xnumpy

解决方案


考虑距离:

  • 在二维地图 X 上,从大本营到珠穆朗玛峰顶峰的距离是一回事
  • 在现实世界的情况 Z 它是 3 维的,所以它是另一回事

我认为使用数据的内容来找到不同维度之间的适应比通过算法来做更合适。


推荐阅读