【Pytorch】expand()用法==》扩展某个维度

 有两点需要注意,无论是 expand() 还是 expand_as():

  1. 只能在第0维扩展一个维数,比如原来是是(1,3,4)==》(2,1,3,4),而在其他维度扩展不可以(1,3,4)==》(1,2,3,4)【错误】
  2. 如果不增加维数,只是增加维度,要增加的原维度必须是1才可以在该维度增加维度,其他值均不可以
import torch
#1
x = torch.randn(2, 1, 1)#为1可以扩展为3和4
x = x.expand(2, 3, 4)
print('x :', x.size())
>>> x : torch.Size([2, 3, 4])
#2
#扩展一个新的维度必须在最前面,否则会报错
x = x.expand(2, 3, 4, 6)
>>> RuntimeError: The expanded size of the tensor (3) must match the existing size (2) at non-singleton dimension 1.
x = x.expand(6, 2, 3, 4)
>>> x : torch.Size([6, 2, 3, 4])
#3
#某一个维度为-1表示不改变该维度的大小
x = x.expand(6, -1, -1, -1)
>>> x : torch.Size([6, 2, 1, 1])
import torch
#1
x = torch.randn(2, 1, 1)#原维度为1可以扩展为其他维度
y = torch.randn(2, 3, 3)
x = x.expand_as(y)
print('x :', x.size())
>>> x : torch.Size([2, 3, 3])
#2
x = torch.randn(2, 2, 2)#原维度为其他不是1的值不可以扩展为其他维度
y = torch.randn(2, 3, 4)
x = x.expand_as(y)
print('x :', x.size())
>>> RuntimeError: The expanded size of the tensor (4) must match the existing size (2) at non-singleton dimension 2.  Target sizes: [2, 3, 4].

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

马鹏森

太谢谢了

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

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

打赏作者

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

抵扣说明:

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

余额充值