pytorch 笔记:dist 和 cdist

1 dist

1.1 基本使用方法

torch.dist(input, other, p=2)

计算两个Tensor之间的p-范数

1.2 主要参数

input输入张量
other另一个输入张量
p范数

input 和 other的形状需要是可广播的

1.3 举例

import torch

x=torch.randn(4)
x
#tensor([ 1.2698, -0.1209,  0.0462, -1.3271])

y=torch.randn(4)
y
#tensor([ 0.6590, -0.8689, -1.0083,  0.5733])

torch.dist(x,y)
#tensor(2.3783)
z=torch.randn((2,4))
z
'''
tensor([[-0.9118,  1.8019, -0.0162, -0.1969],
        [ 0.2998, -0.1147,  1.1427, -0.9425]])
'''

torch.dist(x,z)
#tensor(3.4683)

2 cdist

2.1 基本使用方法

torch.cdist(x1, x2, p=2.0, compute_mode='use_mm_for_euclid_dist_if_necessary')

2.2 主要参数

x1B  × P × M大小的tensor
x2B × R × M 大小的tensor
p范数
compute_mode指定计算欧几里得距离(p=2)时的方法。有三个选项:
  • use_mm_for_euclid_dist_if_necessary:如果 P > 25 或 R > 25,则使用矩阵乘法方法计算欧几里得距离。
  • use_mm_for_euclid_dist:总是使用矩阵乘法方法计算欧几里得距离。
  • donot_use_mm_for_euclid_dist:永不使用矩阵乘法方法计算欧几里得距离。

返回的大小是B × P × R

如果p∈(0,∞),那么这个方法和scipy.spatial.distance.cdist(input,’minkowski’, p=p)是一样的

如果p=0,那么这个方法和scipy.spatial.distance.cdist(input,‘hamming’)是一样的

2.4 使用矩阵乘法速度变慢?

  • 如果数据集较大,或者你有访问高性能计算资源(如GPU),则使用 "use_mm_for_euclid_dist" 可能会更快。
  • 相反,如果数据集较小,或者你的计算资源有限(如只使用CPU),那么 "donot_use_mm_for_euclid_dist" 可能是更好的选择
%%timeit
points1 = torch.rand((5120, 2))
points2 = torch.rand((5120, 2))
torch.cdist(points1, points2, p=2.0, compute_mode="donot_use_mm_for_euclid_dist")
#24 ms ± 4.54 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%%timeit
points1 = torch.rand((5120, 2))
points2 = torch.rand((5120, 2))
torch.cdist(points1, points2, p=2.0)
#36.7 ms ± 2.68 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

  • 10
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

UQI-LIUWJ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值