我在 PyTorch 中有 2 个张量:
a.shape, b.shape
# (torch.Size([1600, 2]), torch.Size([128, 2]))
我想计算“b”中 128 个值之间的 L2 范数距离,其中“a”中的所有 1600 个值具有 2-dim 值。目前,我有一个低效的 for 循环来对 b 中的每个值执行此操作,如下所示:
# Need to compute l2-norm squared dist b/w each b from a-
l2_dist_squared = list()
for bmu in bmu_locs:
l2_dist_squared.append(torch.norm(input = a.to(torch.float32) - b, p = 2, dim = 1))
l2_dist_squared = torch.stack(l2_dist_squared)
# l2_dist_squared.shape
# torch.Size([128, 1600])
作为一个班轮有更好的方法吗?
torch.cdist
计算批量p-范数,它在形状为x1
的B×P×M
和形状为x2
的B×R×M
之间运行,返回形状为B×P×R
的张量。这意味着公共维度 M
是减少的维度。首先,解压缩两个输入上的一个单一维度以将它们转换为 3D,然后应用该函数:
>>> torch.cdist(a[None], b[None]).shape
>>> torch.Size([1, 1600, 128])