美文网首页
pytorch张量torch.Tensor类型的构建、相互转换与

pytorch张量torch.Tensor类型的构建、相互转换与

作者: top_小酱油 | 来源:发表于2020-03-12 18:43 被阅读0次

构建

  • 构建一个n∗mn*mn∗m的Float类型张量(也是默认张量类型)
    torch.FloatTensor(n, m)
  • 构建一个n∗mn*mn∗m的Double类型张量
    torch.DoubleTensor(n, m)
  • 构建一个n∗mn*mn∗m的Byte类型张量
    torch.ByteTensor(n, m)
  • 构建一个n∗mn*mn∗m的Char类型张量
    torch.CharTensor(n, m)
  • 构建一个n∗mn*mn∗m的Short类型张量
    torch.ShortTensor(n, m)
  • 构建一个n∗mn*mn∗m的Int类型张量
    torch.IntTensor(n, m)
  • 构建一个n∗mn*mn∗m的Long类型张量
    torch.LongTensor(n, m)

相互转换

  • 将tensor投射为long类型
    newtensor = tensor.long()
  • 将tensor投射为半精度浮点类型
    newtensor = tensor.half()
  • 将tensor投射为int类型
    newtensor = tensor.int()
  • 将tensor投射为double类型
    newtensor = tensor.double()
  • 将tensor投射为float类型
    newtensor = tensor.float()
  • 将tensor投射为char类型
    newtensor = tensor.char()
  • 将tensor投射为byte类型
    newtensor = tensor.byte()
  • 将tensor投射为short类型
    newtensor = tensor.short()
    type(new_type=None, async=False)如果未提供new_type,则返回类型,否则将此对象转换为指定的类型。 如果已经是正确的类型,则不会执行且返回原对象
tensor_A = torch.LongTensor(3, 5)
# 转换为其他类型
print(tensor_A.type(torch.FloatTensor))

使用type_as(tesnor)将张量转换为给定tensor类型的张量

tensor_A= torch.Tensor(3, 5)
tensor_B = torch.IntTensor(2,3)
print tensor_A.type_as(tensor_B )

拼接

将tensor_A与tensor_B沿dim=k合并,应注意除了dim=k以外,tensor_A与tensor_B沿其他维度的size均应相等,否则无法合并。例如一个(1, 2, 3)的tensor和(5, 2, 3)的tensor沿维度0拼接,得到的结果是(6, 2, 3)

tenor_C = torch.cat(inputs=(tensor_A, tensor_B), dimension=k)

tensor.stack()的意思是,两个(1, 2)的tenso沿维度0堆叠,则会变为(2, 1, 2)的tensor;沿维度1堆叠,则会变为(1, 2, 2)的tensor

参考文献

https://ptorch.com/news/71.html
https://www.cnblogs.com/yifdu25/p/9399047.html

相关文章

网友评论

      本文标题:pytorch张量torch.Tensor类型的构建、相互转换与

      本文链接:https://www.haomeiwen.com/subject/yrbbjhtx.html