0
Follow
4
View

使用没有循环的PyTorch计算欧氏距离(仅使用向量化)

dengluanshun 注册会员
2022-11-19 10:44

输入张量可能应该有两个维度,以便计算成对距离。所以我假设这些x × x矩阵应该加起来像(N, x, x) =>(N)

def euc_no_loop(x, y):
  # Suppose x has (N, x, x) and Y has (M, x, x) dimensions
  xsq = torch.sum(x**2, dim=(1, 2))  # (N,)
  print(xsq.shape)
  ysq = torch.sum(y**2, dim=(1, 2))  # (M,)
  print(ysq.shape)

  mixprod = -2 * x.view(x.shape[0], -1) @ y.view(y.shape[0], -1).T  # (N, M)
  print(mixprod.shape)

  euc_dist = torch.sqrt(xsq.unsqueeze(1) + mixprod + ysq.unsqueeze(0))  # (N,1)+(N,M)+(1,M) => (N, M)
  return euc_dist

或者将输入张量压平

x = x.flatten(start_dim=1)
y = y.flatten(start_dim=1)

About the Author

Question Info

Publish Time
2022-11-19 10:44
Update Time
2022-11-19 10:44

Related Question

Postgres—使用来自另一个数据库的外键创建一个表

自动热键循环和键按下

求解答,听说没有公网IP,就不能远程监控视频远程访问了是吗?

c++中的while循环中有多个OR条件

如何使用rxjs有条件地重复承诺

arduino开发stm32,低电平触发代码没有用。

为什么这个输入完n后就没有了?

如何在R语言中使用多变量包建立多输出回归模型?

我如何在discord.js中使用特定的公会ID ?

C语言for循环问题