pytorch 笔记:dist 和 cdist

1 dist

1.1 基本使用方法

python 复制代码
torch.dist(input, other, p=2)

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

1.2 主要参数

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

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

1.3 举例

python 复制代码
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)
python 复制代码
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 基本使用方法

python 复制代码
torch.cdist(x1, x2, p=2.0, compute_mode='use_mm_for_euclid_dist_if_necessary')

2.2 主要参数

|----------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| x1 | B × P × M大小的tensor |
| x2 | B × 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" 可能是更好的选择
python 复制代码
%%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)
相关推荐
zhdy567893 小时前
最简单方法 设置matlab坐标轴刻度标签的字号,设置坐标轴标题和图形标题,并指定字号。画出的图片背景设置为白色,
笔记
崇山峻岭之间3 小时前
Matlab学习笔记02
笔记·学习·matlab
木木em哈哈3 小时前
C语言多线程
笔记
hssfscv5 小时前
Javaweb 学习笔记——html+css
前端·笔记·学习
Dream Algorithm6 小时前
自古英雄多寂寥
笔记
yuhaiqun19897 小时前
Typora 技能进阶:从会写 Markdown 到玩转配置 + 插件高效学习笔记
经验分享·笔记·python·学习·学习方法·ai编程·markdown
apcipot_rain7 小时前
汇编语言与逆向分析 一轮复习笔记
汇编·笔记·逆向
Lv11770087 小时前
Visual Studio中的多态
ide·笔记·c#·visual studio
HollowKnightZ7 小时前
论文阅读笔记:Class-Incremental Learning: A Survey
论文阅读·笔记
AA陈超8 小时前
枚举类 `ETriggerEvent`
开发语言·c++·笔记·学习·ue5