矩阵之间欧式距离的快捷计算方法(无循环)

最近工作中需要用到矩阵中各个样本之间欧氏距离,因此记录一下,如何简便快捷地进行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变量进行的演示,对于矩阵,原理也是相同的。学会这个方法,以后就可以很高效地,而不必通过循环的方式计算矩阵间的欧氏距离了。

  • 20
    点赞
  • 71
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值