torch.cdist(x1, x2, p=2.0, compute_mode=‘use_mm_for_euclid_dist_if_necessary’)
x1 (Tensor) – input tensor of shape B×P×M .
x2 (Tensor) – input tensor of shape B×R×M .
output (Tensor) – will have shape B×P×R
import torch
x1 = torch.randn([16,1536]) #此处模拟抽取到的特征值,16为16个样本
x1 = x1.unsqueeze(0) #升维度
print(x1.shape) #torch.Size([1, 16, 1536])
dist = torch.cdist(x1,x1) #torch.Size([1, 16, 16])
dist = dist.squeeze(0) #降维
print(dist.shape) #torch.Size([16, 16]) #最终求出每个样本之间的距离,即相似度
L0、L1、L2范数参考以下链接:
https://blog.csdn.net/fantacy10000/article/details/90647686
https://blog.csdn.net/jinping_shi/article/details/52433975
https://www.jianshu.com/p/de05e6745fb6
import torch
a = torch.tensor([[1.0,1.0]])
b = torch.tensor([[3.0,3.0]])
print(torch.cdist(a,b,0)) #tensor([[2.]])
print((3-1)**0+(3-1)**0) # 2
import torch
a = torch.tensor([[1.0,1.0]])
b = torch.tensor([[3.0,3.0]])
print(torch.cdist(a,b,1)) # tensor([[4.]])
print((3-1)**1+(3-1)**1) # 4
import torch
import math
a = torch.tensor([[1.0,1.0]])
b = torch.tensor([[3.0,3.0]])
print(torch.cdist(a,b,2)) #tensor([[2.8284]])
print(math.sqrt((3-1)**2+(3-1)**2)) #2.8284271247461903
#三维L2正则
a = torch.tensor([[1, 1], [2,1], [1,2]])
b = torch.tensor([[2, 2], [1, 2]])
print(a)
tensor([[1, 1],
[2, 1],
[1, 2]])
print(b)
tensor([[2, 2],
[1, 2]])
torch.cdist(a.float(),b.float())
tensor([[1.4142, 1.0000], # ((2-1)**2+(2-1)**2)*(1/2),((1-1)**2+(2-1)**2)*(1/2)
[1.0000, 1.4142], # ((2-2)**2+(2-1)**2)*(1/2),((1-2)**2+(2-1)**2)*(1/2)
[1.0000, 0.0000]]) #((2-1)**2+(2-2)**2)*(1/2),((1-2)**2+(2-2)**2)*(1/2)
import torch
import math
a = torch.tensor([[1.0,1.0]])
b = torch.tensor([[3.0,3.0]])
print(torch.cdist(a,b,10)) #tensor([[2.1435]])
print(math.pow((3-1)**10+(3-1)**10,1/10) #2.1435469250725863
#此段代码会报错
#builtins.RuntimeError: cdist only supports at least 2D tensors, X1 got: 1D
x1 = torch.tensor([1,2])
x2 = torch.tensor([3,3])
dist = torch.cdist(x1,x2)
#因此需要加上中括号 [],但是此处还会报错,builtins.RuntimeError: cdist only
#supports floating-point dtypes, X1 got: Long
x1 = torch.tensor([[1,2]])
x2 = torch.tensor([[3,3]])
dist = torch.cdist(x1,x2)
#因此需要定义数据的类型,或者给数据后面加个.
x1 = torch.tensor([[1,2]],dtype=float) # x1 = torch.tensor([[1.,2.]])
x2 = torch.tensor([[3,3]],dtype=float) # x2 = torch.tensor([[3.,3.]])
dist = torch.cdist(x1,x2)