【pytorch】数据类型及转换方式

写在前面

张量是一个包含单一数据类型元素的多维矩阵,pytorch中共定义了10种张量的数据类型。

数据类型

Data typedtypeCPU tensorGPU tensor
32-bit floating pointtorch.float32 or torch.floattorch.FloatTensortorch.cuda.FloatTensor
64-bit floating pointtorch.float64 or torch.doubletorch.DoubleTensortorch.cuda.DoubleTensor
16-bit floating point 1torch.float16 or torch.halftorch.HalfTensortorch.cuda.HalfTensor
16-bit floating point 2torch.bfloat16torch.BFloat16Tensortorch.cuda.BFloat16Tensor
32-bit complextorch.complex32\\
64-bit complextorch.complex64\\
128-bit complextorch.complex128 or torch.cdouble\\
8-bit integer (unsigned)torch.uint8torch.ByteTensortorch.cuda.ByteTensor
8-bit integer (signed)torch.int8torch.CharTensortorch.cuda.CharTensor
16-bit integer (signed)torch.int16 or torch.shorttorch.ShortTensortorch.cuda.ShortTensor
32-bit integer (signed)torch.int32 or torch.inttorch.IntTensortorch.cuda.IntTensor
64-bit integer (signed)torch.int64 or torch.longtorch.LongTensortorch.cuda.LongTensor
Booleantorch.booltorch.BoolTensortorch.cuda.BoolTensor

转换方式

方式1

直接在张量后面加.int().long().float().double()

>>> import torch
>>> a = torch.tensor([1.3, 1.5, 1.7])
>>> a
tensor([1.3000, 1.5000, 1.7000])
>>> a.dtype
torch.float32
>>> a.int()
tensor([1, 1, 1], dtype=torch.int32)
>>> a.long()
tensor([1, 1, 1])
>>> a.float()
tensor([1.3000, 1.5000, 1.7000])
>>> a.double()
tensor([1.3000, 1.5000, 1.7000], dtype=torch.float64)

方式2

使用张量的.type(dtype)方法,dtype参数填数据类型表格中的第二列,如torch.uint8

>>> import torch
>>> a = torch.tensor([-1, 1, 256])
>>> a
tensor([ -1,   1, 256])
>>> a.dtype
torch.int64
>>> a.type(torch.uint8)
tensor([255,   1,   0], dtype=torch.uint8)

方式3

使用张量的.type_as(tensor)方法将张量1转换为和张量2一样的数据类型

>>> import torch
>>> a = torch.tensor([1, 2, 3])
>>> a.dtype
torch.int64
>>> b = torch.tensor([1.1, 2.2, 3.3])
>>> b.dtype
torch.float32
>>> b = b.type_as(a)
>>> b.dtype
torch.int64
>>> b
tensor([1, 2, 3])

引用参考

https://pytorch.org/docs/stable/tensors.html

  • 1
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Xavier Jiezou

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值