torch.Tensor — PyTorch 1.12 documentation
Data type | dtype | CPU tensor | GPU tensor |
---|---|---|---|
32-bit floating point | torch.float32 or torch.float |
torch.FloatTensor |
torch.cuda.FloatTensor |
64-bit floating point | torch.float64 or torch.double |
torch.DoubleTensor |
torch.cuda.DoubleTensor |
16-bit floating point [1] | torch.float16 or torch.half |
torch.HalfTensor |
torch.cuda.HalfTensor |
16-bit floating point [2] | torch.bfloat16 |
torch.BFloat16Tensor |
torch.cuda.BFloat16Tensor |
32-bit complex | torch.complex32 or torch.chalf |
||
64-bit complex | torch.complex64 or torch.cfloat |
||
128-bit complex | torch.complex128 or torch.cdouble |
||
8-bit integer (unsigned) | torch.uint8 |
torch.ByteTensor |
torch.cuda.ByteTensor |
8-bit integer (signed) | torch.int8 |
torch.CharTensor |
torch.cuda.CharTensor |
16-bit integer (signed) | torch.int16 or torch.short |
torch.ShortTensor |
torch.cuda.ShortTensor |
32-bit integer (signed) | torch.int32 or torch.int |
torch.IntTensor |
torch.cuda.IntTensor |
64-bit integer (signed) | torch.int64 or torch.long |
torch.LongTensor |
torch.cuda.LongTensor |
Boolean | torch.bool |
torch.BoolTensor |
torch.cuda.BoolTensor |
quantized 8-bit integer (unsigned) | torch.quint8 |
torch.ByteTensor |
/ |
quantized 8-bit integer (signed) | torch.qint8 |
torch.CharTensor |
/ |
quantized 32-bit integer (signed) | torch.qint32 |
torch.IntTensor |
/ |
quantized 4-bit integer (unsigned) | torch.quint4x2 |
torch.ByteTensor |
/ |
除了编码常见的类型,还有几种不常见的类型:
1、16-bit floating point[1]:使用 1 个符号、5 个指数和 10 个有效位。 当精度很重要以牺牲范围为代价时很有用。
2、16-bit floating point[2]:使用 1 个符号、8 个指数和 7 个有效位。 当范围很重要时很有用,因为它具有与 float32 相同数量的指数位
3、quantized 4-bit integer (unsigned):量化的 4 位整数存储为 8 位有符号整数。 目前仅在 EmbeddingBag 运算符中支持。
不指定类型的话,默认是:torch.FloatTensor
1、使用列表或者序列:
import torch
torch.tensor([[1., -1.], [1., -1.]])
torch.tensor(np.array([[1, 2, 3], [4, 5, 6]]))
注意:torch.tensor会拷贝数据,如果在改变requires_grad时避免拷贝数据,需要使用requires_grad_() or detach()。如果在使用numpy array初始化想避免拷贝,需要使用torch.as_tensor()
>>> torch.zeros([2, 4], dtype=torch.int32)
tensor([[ 0, 0, 0, 0],
[ 0, 0, 0, 0]], dtype=torch.int32)
>>> cuda0 = torch.device('cuda:0')
>>> torch.ones([2, 4], dtype=torch.float64, device=cuda0)
tensor([[ 1.0000, 1.0000, 1.0000, 1.0000],
[ 1.0000, 1.0000, 1.0000, 1.0000]], dtype=torch.float64, device='cuda:0')
>>> x = torch.tensor([[1, 2, 3], [4, 5, 6]])
>>> print(x[1][2])
tensor(6)
>>> x[0][1] = 8
>>> print(x)
tensor([[ 1, 8, 3],
[ 4, 5, 6]])
>>> x = torch.tensor([[1]])
>>> x
tensor([[ 1]])
>>> x.item()
1
>>> x = torch.tensor(2.5)
>>> x
tensor(2.5000)
>>> x.item()
2.5
>>> x = torch.tensor([[1., -1.], [1., 1.]], requires_grad=True)
>>> out = x.pow(2).sum()
>>> out.backward()
>>> x.grad
tensor([[ 2.0000, -2.0000],
[ 2.0000, 2.0000]])