【学习笔记】Pytorch的Tensor形状操作

Torch库对张量的形状操作

torch库对张量形状的操作有以下几个函数:torch.reshape()、torch.permute()、torch.transpose()、torch.view()。
相关的函数还有:torch.contiguous。

torch.view()

torch.view(*shape)的输入参数为:torch.size()或者int
且返回的数据大小需要与原数据相同,此时新的数据与原数据共享同一内存空间,只是由于读取的方式不同,从而生成了不同的形状。

torch官方的运行例子:

x = torch.randn(4, 4)
x.size()
# torch.Size([4, 4])
y = x.view(16)
# torch.Size([16])
y.size()
z = x.view(-1, 8)  # -1 表示由其他维度决定该维度的大小
z.size()
# torch.Size([2, 8])

torch.reshape()

torch.reshape(input,shape)的输入参数为:
input:原张量
shape:由int组成的tuple
torch官方的运行例子:

a = torch.arange(4.)
torch.reshape(a, (2, 2))
# tensor([[ 0.,  1.],
#        [ 2.,  3.]])
b = torch.tensor([[0, 1], [2, 3]])
torch.reshape(b, (-1,))
# tensor([ 0,  1,  2,  3])

当reshape之后的张量维度与原张量相同时,reshape的操作与view相同。

a = torch.randn(1, 2, 3, 4)
a.size()
# torch.Size([1, 2, 3, 4])
b = a.reshape(1, 3, 2, 4)  # Swaps 2nd and 3rd dimension
b.size()
# torch.Size([1, 3, 2, 4])
c = a.view(1, 3, 2, 4)  # Does not change tensor layout in memory
c.size()
# torch.Size([1, 3, 2, 4])
torch.equal(b, c)
# True

torch官方的运行例子:

a = torch.randn(1, 2, 3, 4)
a.size()
# torch.Size([1, 2, 3, 4])
b = a.transpose(1, 2)  # Swaps 2nd and 3rd dimension
b.size()
# torch.Size([1, 3, 2, 4])
c = a.view(1, 3, 2, 4)  # Does not change tensor layout in memory
c.size()
# torch.Size([1, 3, 2, 4])
torch.equal(b, c)
# False

torch.contiguous()

返回的为以当前形状张量的构成的内存结构。

t = torch.tensor([[2, 1, 3], [4, 5, 9]])
t2 = t.transpose(0, 1)

t3 = t2.contiguous()
print(t3.view(-1))
# tensor([2, 4, 1, 5, 3, 9])
t4 = t2.reshape(-1)
print(t4)
# tensor([2, 4, 1, 5, 3, 9])

当reshape的维度与原张量不符时,原张量就会进行contiguous操作之后再进行view。

torch.transpose()

torch.transpose(input,dim0,dim1) 的输入参数为:
input:输入的张量
dim0,dim1:张量的维度,为int类型

能够交换两个维度

torch.permute()

torch.permute(input,dims)的输入参数为:
imput:输入的张量
dims:新构成的张量维度,由int组成的tuple。

参考链接:https://blog.csdn.net/qq_37828380/article/details/107855070

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

看远方的星是否听得见

求打赏求问问题~

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

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

打赏作者

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

抵扣说明:

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

余额充值