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)
相关推荐
码途漫谈5 小时前
Easy-Vibe开发篇阅读笔记(四)——前端开发之结合 Agent Skills 美化界面
人工智能·笔记·ai·开源·ai编程
糖炒栗子03267 小时前
【笔记】高分卫星影像 TIF 切片处理
笔记
Nice_Fold8 小时前
Kubernetes DaemonSet、StatefulSet与Service(自用笔记)
笔记·容器·kubernetes
ZhiqianXia11 小时前
《The Design of Design》阅读笔记
前端·笔记·microsoft
祁白_11 小时前
nmap工具笔记整理
笔记·web安全·测试
南境十里·墨染春水11 小时前
C++笔记 STL——set
开发语言·c++·笔记
d111111111d11 小时前
直流电机位置式 PID 控制 和 舵机的区别
笔记·stm32·单片机·嵌入式硬件·学习
LZYmarks12 小时前
小白买车笔记
笔记
码途漫谈12 小时前
Easy-Vibe开发篇阅读笔记(二)——前端开发之Figma与MasterGo入门
人工智能·笔记·ai·开源·ai编程·figma
LaLaLa_OvO12 小时前
jetbrains 的 datagrip 导出csv,中文乱码
笔记