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)
相关推荐
X_StarX5 小时前
【Unity笔记02】订阅事件-自动开门
笔记·学习·unity·游戏引擎·游戏开发·大学生
MingYue_SSS5 小时前
开关电源抄板学习
经验分享·笔记·嵌入式硬件·学习
巴伦是只猫6 小时前
【机器学习笔记 Ⅱ】1 神经网络
笔记·神经网络·机器学习
weixin_437398216 小时前
转Go学习笔记(2)进阶
服务器·笔记·后端·学习·架构·golang
teeeeeeemo7 小时前
回调函数 vs Promise vs async/await区别
开发语言·前端·javascript·笔记
致***锌11 小时前
期权标准化合约是什么?
笔记
Wilber的技术分享11 小时前
【机器学习实战笔记 14】集成学习:XGBoost算法(一) 原理简介与快速应用
人工智能·笔记·算法·随机森林·机器学习·集成学习·xgboost
V我五十买鸡腿13 小时前
顺序栈和链式栈
c语言·数据结构·笔记·算法
麟城Lincoln14 小时前
【RHCSA-Linux考试题目笔记(自用)】servera的题目
linux·笔记·考试·rhcsa
丰锋ff14 小时前
计网学习笔记第2章 物理层(灰灰题库)
笔记·学习