tensor属性

tensor attributes

每一个torch.Tensor 都有一个 torch.dtypetorch.devicetorch.layout

1、torch.dtype

torch.dtype 表示 torch.Tensor 的数据类型。PyTorch 共有9种数据类型,每种又分为CPU和GPU:

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 pointtorch.float16 or torch.halftorch.HalfTensortorch.cuda.HalfTensor
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

2、torch.decive

torch.device 表示分配torch.Tensor的设备。

torch.device 包含设备类型(cpu或 cuda)和可选的设备序号。若设备序号不存在,则表示该类型当前设备,即使在调用 torch.cuda.set_device() 后也是如此。例如,在‘cuda’上构建 torch.Tensor 等价于'cuda:X' ,X为 torch.cuda.current_device() 返回的结果。

torch.Tensor 的device可以通过 Tensor.device 属性访问。
torch.device 可通过字符串或字符串和序号构建。

#字符串构建

>>> torch.device('cuda:0')
device(type='cuda', index=0)

>>> torch.device('cpu')
device(type='cpu')

>>> torch.device('cuda')  # current cuda device
device(type='cuda')
#字符串和序号构建

>>> torch.device('cuda', 0)
device(type='cuda', index=0)

>>> torch.device('cpu', 0)
device(type='cpu', index=0)

注意

1.函数中的 torch.device 参数可以用字符串替换。

>> # Example of a function that takes in a torch.device
>> cuda1 = torch.device('cuda:1')
>> torch.randn((2,3), device=cuda1)
>> # You can substitute the torch.device with a string
>> torch.randn((2,3), device='cuda:1')

2.以 device 为参数的方法,通常接受一个字符串或是整型设备号作为参数。
下面三种表示方法等价:

>> torch.randn((2,3), device=torch.device('cuda:1'))
>> torch.randn((2,3), device='cuda:1')
>> torch.randn((2,3), device=1)  # legacy

3、torch.layout

torch.layout 表示 torch.Tensor 的内存布局。当前支持 torch.strided(稠密tensor)并且实验性的支持 torch.sparse__coo(稀疏COO tensor)。

torch.strided 表示稠密tensor,并且是最常用的内存布局。每个strided型的tensor都关联一个torch.Storage,后者保存数据。torch.Storage 是单个数据类型的连续一维数组。 stride是一个整数列表,第k个值表示在tensor的第k维上,从一个元素到达下一个元素在内存中所需的跳数。该概念使得可以有效地执行许多tensor操作。

示例:

>>> x = torch.Tensor([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
>>> x.stride()
(5, 1)

>>> x.t().stride()
(1, 5)
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值