深入浅出Pytorch函数——torch.Tensor

分类目录:《深入浅出Pytorch函数》总目录
相关文章:
· 深入浅出TensorFlow2函数——tf.constant
· 深入浅出Pytorch函数——torch.tensor
· 深入浅出Pytorch函数——torch.as_tensor
· 深入浅出Pytorch函数——torch.Tensor
· 深入浅出PaddlePaddle函数——paddle.to_tensor

torch.Tensor是包含单一数据类型元素的多维矩阵。有几种主要的方法来创建张量,这取决于你的用途:

  • 要使用预先存在的数据创建张量,可使用torch.tensor()
  • 要创建具有特定大小的张量,请使用torch.*张量创建操作
  • 要创建与另一个张量大小相同(类型相似)的张量,请使用torch.*_like张量创建操作
  • 要创建与另一个张量类型相似但大小不同的张量,请使用tensor.new_*张量创建操作

数据类型

Torch定义了10种具有CPU和GPU变体的张量类型,如下所示:

数据类型dtypeCPUGPU
32位浮点数torch.float32/torch.floattorch.FloatTensortorch.cuda.FloatTensor
64位浮点数torch.float64/torch.doubletorch.DoubleTensortorch.cuda.DoubleTensor
16位浮点数①torch.float16/torch.halftorch.HalfTensortorch.cuda.HalfTensor
16位浮点数②torch.bfloat16torch.BFloat16Tensortorch.cuda.BFloat16Tensor
32位复数torch.complex32/torch.chalf
64位复数torch.complex64/torch.cfloat
128位复数torch.complex128/torch.cdouble
8位整数(无符号)torch.uint8torch.ByteTensortorch.cuda.ByteTensor
8位整数(有符号)torch.int8torch.CharTensortorch.cuda.CharTensor
116位整数(有符号)torch.int16/torch.shorttorch.ShortTensortorch.cuda.ShortTensor
32位整数(有符号)torch.int32/torch.inttorch.IntTensortorch.cuda.IntTensor
64位整数(有符号)torch.int64/torch.longtorch.LongTensortorch.cuda.LongTensor
布尔代数torch.booltorch.BoolTensortorch.cuda.BoolTensor
量化的8位整数(无符号)torch.quint8torch.ByteTensor
量化的8位整数(带符号)torch.qint8torch.CharTensor
量化的32位整数(带符号)torch.qint32torch.IntTensor
量化的4位整数(无符号)torch.quint4x2torch.ByteTensor

实例

>>> torch.tensor([[1., -1.], [1., -1.]])
tensor([[ 1.0000, -1.0000],
        [ 1.0000, -1.0000]])
>>> torch.tensor(np.array([[1, 2, 3], [4, 5, 6]]))
tensor([[ 1,  2,  3],
        [ 4,  5,  6]])

可以使用Python的索引和切片符号来访问和修改张量的内容:

>>> 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]])

张量可以通过requires_grad=True方式创建以便torch.autograd记录对它们的操作,以便自动微分:

>>> 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]])

每个张量都有一个相关的torch.Storage,它保存其数据。张量类还提供多维的,大步前进存储器的视图,并在其上定义数字操作。

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
青葱年少的头像青葱年少普通用户
上一篇 2023年6月10日
下一篇 2023年6月10日

相关推荐