最近工作中需要用到矩阵中各个样本之间欧氏距离,因此记录一下,如何简便快捷地进行tensor间欧氏距离的计算(使用Pytorch框架)。
按照我之前的想法,会进行两轮或者一轮循环一个个地求出样本间的欧氏距离,但是看过了michuanhaohao/reid-strong-baseline 中Euclidean_dist()方法的运算之后才发现了新大陆---------通过矩阵的方式快速的进行计算。
一、理论分析
首先从理论上介绍 一下,矩阵之间欧氏距离的快速计算,参考了@frankzd 的博客,原文链接在
https://blog.csdn.net/frankzd/article/details/80251042
二、代码分析
接下来上代码,我会在每一行进行必要的注释(来源:https://github.com/michuanhaohao/reid-strong-baseline/blob/master/layers/triplet_loss.py)
def euclidean_dist(x, y):
"""
Args:
x: pytorch Variable, with shape [m, d]
y: pytorch Variable, with shape [n, d]
Returns:
dist: pytorch Variable, with shape [m, n]
"""
m, n = x.size(0), y.size(0)
# xx经过pow()方法对每单个数据进行二次方操作后,在axis=1 方向(横向,就是第一列向最后一列的方向)加和,此时xx的shape为(m, 1),经过expand()方法,扩展n-1次,此时xx的shape为(m, n)
xx = torch.pow(x, 2).sum(1, keepdim=True).expand(m, n)
# yy会在最后进行转置的操作
yy = torch.pow(y, 2).sum(1, keepdim=True).expand(n, m).t()
dist = xx + yy
# torch.addmm(beta=1, input, alpha=1, mat1, mat2, out=None),这行表示的意思是dist - 2 * x * yT
dist.addmm_(1, -2, x, y.t())
# clamp()函数可以限定dist内元素的最大最小范围,dist最后开方,得到样本之间的距离矩阵
dist = dist.clamp(min=1e-12).sqrt() # for numerical stability
return dist
三、demo演示
接下来用一个简单的demo实现(也便于自己查验最后结果是否正确)
import torch
def euclidean_dist(x, y):
m, n = x.size(0), y.size(0)
xx = torch.pow(x, 2).sum(1, keepdim=True).expand(m, n)
yy = torch.pow(y, 2).sum(1, keepdim=True).expand(n, m).t()
dist = xx + yy
dist.addmm_(1, -2, x, y.t())
dist = dist.clamp(min=1e-12).sqrt() # for numerical stability
return dist
if __name__ == '__main__':
x = torch.tensor([[1.0, 2.0, 3.0, 4.0], [2.0, 5.0, 7.0, 9.0]])
y = torch.tensor([[3.0, 1.0, 2.0, 5.0], [2.0, 3.0, 4.0, 6.0]])
dist_matrix = euclidean_dist(x, y)
print(dist_matrix)
最后输出的结果为:
tensor([[2.6458, 2.6458],[7.6158, 4.6904]])
理论看起来稍微有些麻烦,不过静下心来琢磨一下,还是很简单的。本文使用的是pytorch下的tensor变量进行的演示,对于矩阵,原理也是相同的。学会这个方法,以后就可以很高效地,而不必通过循环的方式计算矩阵间的欧氏距离了。