torch.cdist---求解正则项p-norm

官方给出参数形状的维度:

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

L1、L2目的是为了防止过拟合

L0-norm:
在这里插入图片描述

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

L1-norm:
在这里插入图片描述

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

L2-norm:
在这里插入图片描述

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)

Ln-norm:
在这里插入图片描述

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

#注意:在定义X1和X2时,必须是二维数据,并且要定义数据的类型

#此段代码会报错
#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)

纸上得来终觉浅,绝知此事要躬行。

  • 6
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值