Pytorch维度操作-unsqueeze、squeeze、view与permute

view

在pytorch中view函数的作用为重构张量的维度,相当于numpy中resize()的功能。

a = [1,2,3]
b = [2,3,4]
c = [3,5,5]
d = [4,5,6]
e = np.array([a,b,c,d])
e = torch.from_numpy(e)
print(e.shape)

e = e.view(2,6)
print(e.shape)

e = e.view(3,4)
print(e.shape)

e = e.view(1,-1)
print(e.shape)

unsqueeze

作用是用于增加维度,操作是针对于tensor张量,增加一个维数为1的维度。

生成一个张量

a = [1,2,3]
b = [2,3,4]
c = [3,5,5]
d = [4,5,6]

e = np.array([a,b,c,d])
e = torch.from_numpy(e)
print(e)
print(e.shape)

 unsqueeze的用法通过tensor.unsqueeze(dim)进行维度扩张。dim是维度,如果要扩张第一维就是tensor.unsqueeze(0)

e = e.unsqueeze(0)
print(e)
print(e.shape)

 

如果要在第二维扩张就是tensor.unsqueeze(1)

最后一维就是tensor.unsqueeze(-1) 

unsqueeze_和unsqueeze实现一样的功能, 区别在于unsqueeze_是in_place操作,即unsqueeze不会对使用unsqueeze的tensor进行改变,想要获取unsqueeze后的值必须赋予个新值,unsqueeze_则会对自己改变 

squeeze

作用是用于压缩维度,操作是针对于tensor张量。与unsqueeze一样,传入参数为维度,只是作用变成了压缩(挤压)维度,去掉一个维数为1的维度。

a = torch.normal(0,1,size=(1,3,4))
print(a)
print(a.shape)
c = a.squeeze(0)
print(c)
print(c.shape)

用tensor.squeeze也可以,传入参数为一个张量,去掉其中为1的维度。

a = torch.squeeze(a)
print(a)
print(a.shape)

 

如果有多个维数为1的维度,就全部去掉。

a = torch.normal(0,1,size=(1,3,1))
print(a)
print(a.shape)
a = torch.squeeze(a)
print(a)
print(a.shape)

 如果要去掉指定位置的维度

a = torch.squeeze(a,0)
print(a)
print(a.shape)

Permute

用于进行维度的调整换位,传入的参数为维度的下标,比如将第1和第2维度进行交换:

a = torch.ones(2,3,4)
print(a.shape)
a = a.permute(1,0,2)
print(a.shape)

 

将最后一维放到第1维,然后其他后移: 

a = torch.ones(2,3,4)
print(a.shape)
a = a.permute(-1,0,1)
print(a.shape)

 

 

  • 6
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值