Pytorch入坑一:Tensor及其基本操作

在这里插入图片描述
Tensor attributes:
在tensor attributes中有三个类,分别为torch.dtype, torch.device, 和 torch.layout。
其中, torch.dtype 是展示 torch.Tensor 数据类型的类,pytorch 有八个不同的数据类型,下表是完整的 dtype 列表.
在这里插入图片描述
创建tensor
1、直接创建
torch.tensor(data, dtype=None, device=None,requires_grad=False)
data - 可以是list, tuple, numpy array, scalar或其他类型
dtype - 可以返回想要的tensor类型
device - 可以指定返回的设备
requires_grad - 可以指定是否进行记录图的操作,默认为False
需要注意的是,torch.tensor 总是会复制 data, 如果你想避免复制,可以使 torch.Tensor. detach(),如果是从 numpy 中获得数据,那么你可以用 torch.from_numpy(), 注from_numpy() 是共享内存的

>>> torch.tensor([[0.1, 1.2], [2.2, 3.1], [4.9, 5.2]])
tensor([[ 0.1000,  1.2000],
        [ 2.2000,  3.1000],
        [ 4.9000,  5.2000]])
 
>>> torch.tensor([0, 1])  # Type inference on data
tensor([ 0,  1])
 
>>> torch.tensor([[0.11111, 0.222222, 0.3333333]],
                 dtype=torch.float64,
                 device=torch.device('cuda:0'))  # creates a torch.cuda.DoubleTensor
tensor([[ 0.1111,  0.2222,  0.3333]], dtype=torch.float64, device='cuda:0')
 
>>> torch.tensor(3.14159)  # Create a scalar (zero-dimensional tensor)
tensor(3.1416)
 
>>> torch.tensor([])  # Create an empty tensor (of size (0,))
tensor([])

2、从numpy中获得数据
torch.from_numpy(ndarry)
注:生成返回的tensor会和ndarry共享数据,任何对tensor的操作都会影响到ndarry,反之亦然

>>> a = numpy.array([1, 2, 3])
>>> t = torch.from_numpy(a)
>>> t
tensor([ 1,  2,  3])
>>> t[0] = -1
>>> a
array([-1,  2,  3])

3、创建特定的tensor
根据数值要求:

torch.zeros(*sizes, out=None, ..)# 返回大小为sizes的零矩阵 
 
torch.zeros_like(input, ..) # 返回与input相同size的零矩阵
 
torch.ones(*sizes, out=None, ..) #f返回大小为sizes的单位矩阵
 
torch.ones_like(input, ..) #返回与input相同size的单位矩阵
 
torch.full(size, fill_value,) #返回大小为sizes,单位值为fill_value的矩阵
 
torch.full_like(input, fill_value,) 返回与input相同size,单位值为fill_value的矩阵
 
torch.arange(start=0, end, step=1,) #返回从start到end, 单位步长为step的1-d tensor.
 
torch.linspace(start, end, steps=100,)  #返回从start到end, 间隔中的插值数目为steps的1-d tensor
 
torch.logspace(start, end, steps=100,) #返回1-d tensor ,从10^start到10^end的steps个对数间隔

4、根据矩阵要求:

torch.eye(n, m=None, out=None,) #返回2-D 的单位对角矩阵
 
torch.empty(*sizes, out=None,) #返回被未初始化的数值填充,大小为sizes的tensor
 
torch.empty_like(input,) # 返回与input相同size,并被未初始化的数值填充的tensor

5、随机采用生成:

torch.normal(mean, std, out=None)
 
torch.rand(*size, out=None, dtype=None,) #返回[0,1]之间均匀分布的随机数值
 
torch.rand_like(input, dtype=None,) #返回与input相同size的tensor, 填充均匀分布的随机数值
 
torch.randint(low=0, high, size,) #返回均匀分布的[low,high]之间的整数随机值
 
torch.randint_like(input, low=0, high, dtype=None,) #
 
torch.randn(*sizes, out=None,) #返回大小为size,由均值为0,方差为1的正态分布的随机数值
 
torch.randn_like(input, dtype=None,)
 
torch.randperm(n, out=None, dtype=torch.int64) # 返回0到n-1的数列的随机排列
 

操作tensor
1、获取python number:

>>> a = torch.Tensor([1,2,3])
>>> a[0]   #直接取索引返回的是tensor数据
tensor(1.)
>>> a[0].item()  #获取python number
1

查看维度
1、查看当前 tensor 的维度

>>> import torch
>>> a = torch.Tensor([[[1, 2], [3, 4], [5, 6]]])
>>> a.size()
torch.Size([1, 3, 2])

2、张量变形:torch.Tensor.view(*args) → Tensor
返回一个有相同数据但大小不同的 tensor。 返回的 tensor 必须有与原 tensor 相同的数据和相同数目的元素,但可以有不同的大小。一个 tensor 必须是连续的 contiguous() 才能被查看。

>>> x = torch.randn(2, 9)
>>> x.size()
torch.Size([2, 9])
>>> x
tensor([[-1.6833, -0.4100, -1.5534, -0.6229, -1.0310, -0.8038,  0.5166,  0.9774,
          0.3455],
        [-0.2306,  0.4217,  1.2874, -0.3618,  1.7872, -0.9012,  0.8073, -1.1238,
         -0.3405]])
>>> y = x.view(3, 6)
>>> y.size()
torch.Size([3, 6])
>>> y
tensor([[-1.6833, -0.4100, -1.5534, -0.6229, -1.0310, -0.8038],
        [ 0.5166,  0.9774,  0.3455, -0.2306,  0.4217,  1.2874],
        [-0.3618,  1.7872, -0.9012,  0.8073, -1.1238, -0.3405]])
>>> z = x.view(2, 3, 3)
>>> z.size()
torch.Size([2, 3, 3])
>>> z
tensor([[[-1.6833, -0.4100, -1.5534],
         [-0.6229, -1.0310, -0.8038],
         [ 0.5166,  0.9774,  0.3455]],

        [[-0.2306,  0.4217,  1.2874],
         [-0.3618,  1.7872, -0.9012],
         [ 0.8073, -1.1238, -0.3405]]])

import torch as t 
a = t.arange(0, 6) 
print(a) b = a.view(2, 3) 
# 当某一维是-1时,会自动计算他的大小。 
c = a.view(-1, 3) 
d = a.view(2, -1) 
print(b) 
print(c) 
print(d) 
将会得到:

tensor([0, 1, 2, 3, 4, 5])
tensor([[0, 1, 2],
        [3, 4, 5]])
tensor([[0, 1, 2],
        [3, 4, 5]])
tensor([[0, 1, 2],
        [3, 4, 5]])

3、压缩 / 解压张量:torch.squeeze()、torch.unsqueeze()
torch.squeeze(input, dim=None, out=None)
将输入张量形状中的 1 去除并返回。如果输入是形如(A×1×B×1×C×1×D),那么输出形状就为: (A×B×C×D)
当给定 dim 时,那么挤压操作只在给定维度上。例如,输入形状为: (A×1×B),squeeze(input, 0) 将会保持张量不变,只有用 squeeze(input, 1),形状会变成 (A×B)。
返回张量与输入张量共享内存,所以改变其中一个的内容会改变另一个。

>>> x = torch.randn(3, 1, 2)
>>> x
tensor([[[-0.1986,  0.4352]],

        [[ 0.0971,  0.2296]],

        [[ 0.8339, -0.5433]]])
>>> x.squeeze().size()	# 不加参数,去掉所有为元素个数为1的维度
torch.Size([3, 2])
>>> x.squeeze()
tensor([[-0.1986,  0.4352],
        [ 0.0971,  0.2296],
        [ 0.8339, -0.5433]])
>>> torch.squeeze(x, 0).size()	# 加上参数,去掉第一维的元素,不起作用,因为第一维有2个元素
torch.Size([3, 1, 2])
>>> torch.squeeze(x, 1).size()	# 加上参数,去掉第二维的元素,正好为 1,起作用
torch.Size([3, 2])

torch.unsqueeze(input, dim, out=None)
返回一个新的张量,对输入的制定位置插入维度 1
返回张量与输入张量共享内存,所以改变其中一个的内容会改变另一个。
如果 dim 为负,则将会被转化 dim+input.dim()+1

>>> x.unsqueeze(0).size()
torch.Size([1, 3, 1, 2])
>>> x.unsqueeze(0)
tensor([[[[-0.1986,  0.4352]],

         [[ 0.0971,  0.2296]],

         [[ 0.8339, -0.5433]]]])
>>> x.unsqueeze(-1).size()
torch.Size([3, 1, 2, 1])
>>> x.unsqueeze(-1)
tensor([[[[-0.1986],
          [ 0.4352]]],


        [[[ 0.0971],
          [ 0.2296]]],


        [[[ 0.8339],
          [-0.5433]]]])

转载于:https://blog.csdn.net/weixin_30511107/article/details/99657044
转载于:https://blog.csdn.net/weixin_44613063/article/details/89521464

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值