Pytorch Tensor维度变换

Tensor维度变换

1、View/reshape

a=torch.rand(4,1,28,28)–>可理解为4张1通道的28*28图片
a.view(4,28×28)–>生成一个2维的矩阵,不改变a本身
a.shape–>[4,2,28,28]–>4维
a.view(-1,28)–>-1表示从其他位置的维度自动推出此处的维度–>[4*28,28]

2、Squeeze/unsqueeze

1)a=torch.rand(4,1,28,28)
a.unsqueeze(0)–>[1,4,1,28,28]–>可理解为1组4张1通道的28*28图片
a.unsqueeze(-1)–>[4,1,28,28,1]
在这里0 1 2 3 4分别代表从左边维度开始在第1 2 3 4 5个位置添加维度
在这里-1 -2 -3 -4-5分别代表从右边边维度开始在第1 2 3 4 5个位置添加维度

实例:如何给torch.size([4,1,28,28])各个像素位置加偏置bias
=>bias=torch.ones(32)
=>bias=bias.unsqueeze(1).unsqueeze(2).unsqueeze(3)–>[1,32,1,1]
=>扩展见第4点

2)b=torch.rand(1,32,1,1)–>可理解为1张32通道的1*1的图片
b.squeeze().shape–>[32]–>若不添加参数,则表示挤压无关紧要维度1
b…squeeze(0).shape–>[32,1,1]
b…squeeze(-1).shape–>[1,32,1]
在这里0 1 2 3 4分别代表从左边维度开始在第1 2 3 4 5个位置挤压维度
在这里-1 -2 -3 -4-5分别代表从右边边维度开始在第1 2 3 4 5个位置挤压维度

实例:y=torch.rand(4,1,28,28)
y.squeeze(-1)、y.squeeze(-2)、y.squeeze(-4)、y.squeeze(0)、y.squeeze(2)、y.squeeze(3)
均返回[4,1,28,28]–>只能挤压1维度
y.squeeze(1)、y.squeeze(-3)–>[4,28,28]

3、Transpose/t/permute

1)a.torch.size([3,4])
a.t()—>[4.3]–>仅适用于2D,矩阵转置

2)tanspose-->交换维度
a.torch.size([4,3,32,32])
a.tanspose(1,3)–>[4,32,32,3]

3)permute–>交换维度
a.torch.size([4,3,32,32]) 位置->数: 0:4 1:3 2:32 3:32
Permute–>调整维度位置
a.permute(0,2,3,1)–>[4,32,32,3]

4、Expand/repeat

1)b.torch.size([1,32,1,1])
b.expand(4,32,28,28).shape–>[4,32,28,28]
–>expand操作是将各维度进行拷贝到N维度(1–>N),仅支持1到多维度的拷贝

2)a.torch.size([1,32,1,1])
b.repeat(4,1,28,28).shape–>[4,32,28,28]
–>repeat操作是指在各个维度上要执行拷贝的次数
b.repeat(4,32,28,28).shape–>[4,1024,28,28]

猜你喜欢

转载自blog.csdn.net/qq_40859802/article/details/103758333