Pytorch基础:张量Tensor

1. 张量类(Tensor)

张量类(Tensor)是深度学习框架必须提供的基础数据结构,神经网络的前向传播和反向传播都是基于 Tensor 类进行的。Tensor 类应具有以下多方面的功能:

  1. Tensor 应该具有不同的数值类型,以满足不同的精度需求。
  2. Tensor 的维度应该可以索引、改变。
  3. 不同类型的 Tensor 之间应可以相互转换。
  4. Tensor 应该支持常见的数值计算,比如加、减、乘、除。
  5. Tensor 的设备应该可以在 CPU 和 GPU 之间切换。

2. 数值类型

数据类型CPUGPU
32位浮点数torch.FloatTensortorch.cuda.FloatTensor
64位浮点数torch.DoubleTensortorch.cuda.DoubleTensor
8位有符号整型torch.CharTensortorch.cuda.CharTensor
8位无符号整型torch.ByteTensortorch.cuda.ByteTensor
布尔类型torch.BoolTensortorch.cuda.BoolTensor

3. 创建方法

3.1 从内置数据类型创建

>>> import torch
>>>
>>> x1=[1,2,3]
>>> x1_tensor=torch.tensor(x1,dtype=torch.int32)
>>> print(x1_tensor)
tensor([1, 2, 3], dtype=torch.int32)
>>>
>>> x1_tensor2=torch.tensor([4,5,6],dtype=torch.int32)
>>> print(x1_tensor2)
tensor([4, 5, 6], dtype=torch.int32)
>>>
>>>
>>> x2 = torch.Tensor([7,8,9])
>>> print(x2,x2.dtype)
tensor([7., 8., 9.]) torch.float32   //默认为torch.float32类型
>>>

3.2 从numpy创建

>>> import numpy as np
>>> x2_numpy=np.array([1,2,3])
>>> x2.tensor=torch.from_numpy(x2_numpy)
>>> x2_tensor=torch.from_numpy(x2_numpy)
>>> print(x2_tensor)
tensor([1, 2, 3], dtype=torch.int32)
>>>

3.3 从已有Tensor创建新的Tensor

接着上面的,直接复制Tensor,但是新的Tensor与旧Tensor只是形状相同,数值却是使用特定的数值进行填充的。

>>> x3_tensor=torch.ones_like(x2_tensor)
>>> print(x3_tensor)
tensor([1, 1, 1], dtype=torch.int32)

3.4 创建随机值或特定值的Tensor

>>> size=[1,3]
>>> x4_tensor=torch.randn(size)
>>> x5_tensor=torch.zeros(size)
>>> print(x4_tensor)
tensor([[-0.0643,  0.8212,  0.1565]])
>>> print(x5_tensor)
tensor([[0., 0., 0.]])
>>>

4. 类型转换

>>> x=torch.tensor([1,2,3],dtype=torch.int32)
>>> print(x.dtype)
torch.int32
>>> x=x.half()
>>> print(x.dtype)
torch.float16
>>> x=x.float()
>>> print(x.dtype)
torch.float32
>>> x=x.double()
>>> print(x.dtype)
torch.float64
>>>

5. 维度分析

>>> x= torch.randn(1,3,4,4)
>>> print("ndimension:",x.ndimension()) //张量的维度
ndimension: 4

>>> print("nelement:",x.nelement()) //张量包含的元素总数 
nelement: 48

>>> print("size",x.size()) //张量的尺寸信息
size torch.Size([1, 3, 4, 4])

>>> print("shape:",x.shape)  //
shape: torch.Size([1, 3, 4, 4])
>>>

>>> x_view=x.view(1,3,4*4)
>>> print("x_view:",x_view.size())
x_view: torch.Size([1, 3, 16])
>>>
>>> x_view=x.view(1,-1)
>>> print("x_view:",x_view.size()) //view的一个参数是-1,pytorch会根据其他维度自动计算这一维度的大小
x_view: torch.Size([1, 48])
>>>

//====transpose方法,将2行3列的张量变换成3行2列的张量
>>> x= torch.randn(2,3)
>>> print(x)
tensor([[-0.7116,  1.0912, -1.3217],
        [ 0.1371, -0.6021, -0.9689]])
>>> x_trans=x.transpose(1,0)
>>> print(x_trans)
tensor([[-0.7116,  0.1371],
        [ 1.0912, -0.6021],
        [-1.3217, -0.9689]])
>>>

//=======squeeze删除1维度,此时张量的数据内容不变
>>> x=torch.randn(1,3,16,16)
>>> x=x.squeeze(0)
>>> print(x.size())
torch.Size([3, 16, 16])
//=======squeeze增加1维度,此时张量的数据内容不变
>>> x=x.unsqueeze(0)
>>> print(x.size())
torch.Size([1, 3, 16, 16])
>>>

6. 常用操作

6.1 获取Tensor存储地址

>>> x= torch.tensor([1,2])
>>> y=torch.tensor([1,2])
>>> z=y.clone() //地址不同
>>> q=y.detach() //地址相同

//=====通过clone 方法获得的张量与原始张量的内存地址是不同的,通过detach方法获得的张量与原始张量的内存地址是相同的。
>>> print(x.data_ptr())
5447746589376
>>> print(y.data_ptr())
5447746589312
>>> print(z.data_ptr())
5447746589632
>>> print(q.data_ptr())
5447746589312

6.2 切片索引

>>> x=torch.tensor([1,2,3,4,5])
>>> print(x[1:3]) //获取1~3数值
tensor([2, 3])
>>> print(x[:]) //获取全部数值
tensor([1, 2, 3, 4, 5])
>>> print(x[-1]) //获取最后一个数值
tensor(5)

6.3 拼接不同的Tensor

  • torch.cat 函数提供了拼接不同 Tensor 的功能,它需要指定两个参数,第一个参数 tensors 表示需要拼接的所有 Tensor 对象,第二参数 dim 表示在哪个维度上进行拼接。
  • 在拼接不同的 Tensor 时,需要保证各 Tensor 除堆叠维度外其他维度是一致的,否则无法完成拼接。
>>> x1=torch.tensor([1,2])
>>> x2=torch.tensor([3,4])
>>> x3=torch.tensor([5,6])
>>>
>>> x_cat=torch.cat(tensors=(x1,x2,x3),dim=0)
>>> print(x_cat)
tensor([1, 2, 3, 4, 5, 6])

6.4 四则运算

6.4.1 torch.add 和 torch.sub

>>> x1=torch.tensor([[1,2],[3,4]])
>>> x2=torch.tensor([[1,2],[3,4]])
>>> print(torch.add(x1,x2))
tensor([[2, 4],
        [6, 8]])
>>> print(torch.sub(x1,x2))
tensor([[0, 0],
        [0, 0]])
>>>

6.4.2 inplace 原地加减法

>>> x1=torch.tensor([[1,2],[3,4]])
>>> x2=torch.tensor([[1,2],[3,4]])
>>> print(x1.add_(x2))
tensor([[2, 4],
        [6, 8]])
>>> print(x1.sub_(x2))
tensor([[0, 0],
        [0, 0]])

6.4.3 x1 + x2(将调用重载的加法运算符)

>>> x1=torch.tensor([[1,2],[3,4]])
>>> x2=torch.tensor([[1,2],[3,4]])
>>> print(x1+x2+x1+x2)
tensor([[ 4,  8],
        [12, 16]])

6.5 逐元素乘法和矩阵乘法

>>> x1=torch.tensor([[1,2],[3,4]])
>>> x2=torch.tensor([[1,2],[3,4]])
>>> print(torch.mul(x1,x2))
tensor([[ 1,  4],
        [ 9, 16]])
>>> print(torch.mm(x1,x2))
tensor([[ 7, 10],
        [15, 22]])
  • 25
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

MechMaster

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

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

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

打赏作者

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

抵扣说明:

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

余额充值