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)
相关推荐
Jackyzhe5 小时前
Flink学习笔记:整体架构
笔记·flink
徒 花5 小时前
初级网安作业笔记1
笔记
kfepiza5 小时前
Debian-10编译安装Mysql-5.7.44 笔记250706
linux·数据库·笔记·mysql·debian·bash
Magnetic_h5 小时前
【iOS】方法与消息底层分析
笔记·学习·macos·ios·objective-c·cocoa
今天背单词了吗9806 小时前
算法学习笔记:19.牛顿迭代法——从原理到实战,涵盖 LeetCode 与考研 408 例题
笔记·学习·算法·牛顿迭代法
DKPT7 小时前
Java设计模式之行为型模式(观察者模式)介绍与说明
java·笔记·学习·观察者模式·设计模式
xian_wwq9 小时前
【学习笔记】Nginx常用安全配置
笔记·学习·nginx
love-self-discipline11 小时前
带货视频评论洞察 Baseline 学习笔记 (Datawhale Al夏令营)
人工智能·笔记·学习
蜡笔小电芯11 小时前
【STM32】const 变量存储学习笔记
笔记·stm32·学习
金心靖晨12 小时前
笔记-极客-DDD实战-基于DDD的微服务拆分与设计
java·笔记·微服务