python-3.x - 当数组具有不同维度时如何计算欧几里得距离?
问题描述
我正在尝试逐步计算欧几里得距离。由于欧几里得距离是: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)
我不确定如何重塑数组以使上述功能正常工作。我做了很多研究,到处都能找到两个数组很简单并且尺寸完全匹配的例子。
因此,任何建议都值得赞赏。
解决方案
考虑距离:
- 在二维地图 X 上,从大本营到珠穆朗玛峰顶峰的距离是一回事
- 在现实世界的情况 Z 它是 3 维的,所以它是另一回事
我认为使用数据的内容来找到不同维度之间的适应比通过算法来做更合适。
推荐阅读
- c++ - 仅当条件为真 C++ 时,如何将 cString 分配给结构变量?
- python - Pandas:将所有<= 0的值按组设置为列中的最大值,但仅在该组中的最后一个正值之后
- c++ - 如何将字符串迭代器变量传递给C++中的函数?
- angular - 我的 Angular 应用程序在 app.component.ts 文件中有错误
- string - 如何在 Ansible 中处理可以是字符串或列表的输出
- java - Android espresso 在层次结构中找不到匹配的视图
- c++ - 是否可以使用 C 中的套接字 RAW_PACKET 选项通过 100% TCP 数据包检测进行嗅探?
- javascript - 当我尝试将 js 文件(带有节点模块)导入到我的主电子 js 文件时出现“未定义要求”错误
- c++ - 如何使用 C++ 在另一个程序中读取源代码的输出
- python - How can I link a variable between two running python programs?