当前位置:   article > 正文

torch tensor操作_nn.cosinesimilarity

nn.cosinesimilarity

view

view()用于改变tensor的形状

meshgrid

https://blog.csdn.net/weixin_39504171/article/details/106356977

torch.round()

四舍五入取整

gather

四维gather
https://stackoverflow.com/questions/53471716/index-pytorch-4d-tensor-by-values-in-2d-tensor
https://zhuanlan.zhihu.com/p/352877584

repeeat

https://blog.csdn.net/qq_34806812/article/details/89388210

clamp 截断

用来“截断”tensor,使每个元素都保持在min~max范围内

torch.clamp(input,min,max,out=None)
  • 1

cat 合并

沿着第dim维度将seq中的tensor合并成一个tensor

torch.cat(seq,dim=0,out=None)
  • 1

chunk 分块

torch.chunk(tensor,chunks,dim=0)

  • 1
  • 2

squeeze 压缩

对于tensor来说,可能存在某个维度上的大小为1,比如tensor a的shape为[2,1,1,2,2],那么对它使用squeeze后,将压缩所有大小为0的维度使他的shape变为[2,2,2]。如果指定了dim则指处理该维度,比如dim=0,则保持不变,因为该维度大小不为1,反之指定dim=2时,由于该维度大小为1,则压缩为[2,1,2,2]

torch.squeeze(input,dim=None,out=None)
  • 1

unsqueeze 反压缩

和squeeze相反,用来添加维度,必须指定dim,添加到第dim维上

torch.unsqueeze(input,dim=None,out=None)
  • 1

permute 重排序

这个常用与调整图像tensor,如输入图像数据为(n,224,224,3),
实际pytorch中网络需要接受(n,3,224,224)的图像,就可以使用permute 调整维度顺序。其中dim*接受改变后各维度顺序的参数,比如[0,3,1,2]即可将最后一个维度提到前面。

torch.tensor.permute(dim*)
  • 1

pading 填充

使用nn.ConstantPad2d,前面tuple里的四个参数左右上下的填充大小,最后指定填充的值。

self.pad = nn.ConstantPad2d((0, 1, 0, 1), 0)
  • 1

余弦相似度

利用pytorch提供的torch.nn.CosineSimilarity函数,但是该函数只接受shape相同的tensor,所以对于shape不同的tensor,需要通过unsqueeze和expand处理成相同的shape。

cos = torch.nn.CosineSimilarity(dim=2, eps=1e-6)

def cos_dist(x, y):
    # x: N x D
    # y: M x D
    n = x.size(0)
    m = y.size(0)
    d = x.size(1)
    assert d == y.size(1)

    x = x.unsqueeze(1).expand(n, m, d)
    y = y.unsqueeze(0).expand(n, m, d)
    

    return -cos(x,y)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/42242
推荐阅读
相关标签
  

闽ICP备14008679号