1 dist
1.1 基本使用方法
torch.dist(input, other, p=2)
計算兩個Tensor之間的p-范數
1.2 主要參數
input | 輸入張量 |
other | 另一個輸入張量 |
p | 范數 |
input 和 other的形狀需要是可廣播的
1.3 舉例
import torchx=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 主要參數
x1 | B? × P × M大小的tensor |
x2 | B × R × M 大小的tensor |
p | 范數 |
compute_mode | 指定計算歐幾里得距離(p=2)時的方法。有三個選項:
|
返回的大小是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)