索引与切片
#隔行采样
#每个图片从0开始到28,每隔两个像素进行采样
a[:,:,0:28:2,0:28:2].shape
隔行采样
#生成4个图片,每个图片有3个通道,像素为28*28
a=torch.randn(4,3,28,28)
#取前两个图片
a[:2].shape
out:torch.Size([2,3,28,28])
给定值进行采样
#对第一张图片进行采样
a.index_select(0,torch.tensor([1,2]))shape
维度变换
- view()
- unsqueeze()
- squeeze()
- expand()
- permute()
View()
a=torch.rand(4,1,28,28)
#使用view进行维度的变换
#前提:保证原矩阵各维度的乘积等于变换后的维度乘积
a=a.view(4,28,28)
print(a)
unsqueeze()/squeeze()
#unsqueeze 插入一个维度
print(a.shape)
res=a.unsqueeze(0).shape
print(res)
#squeeze 删减一个维度,只能挤压(Size=1)
#空参情况,删除所有可以删除的维度
res=a.squeeze()
print(res.shape)
#带参数的情况,删除指定维度
res=a.squeeze(0)
print(res.shape)
expand()
#扩展维度
b=torch.rand([1,32,1,1])
#print(b.shape)
res=b.expand(4,32,14,14)
print(res.shape)#torch.Size([4, 32, 14, 14])
#当不想改变某个维度时,使用-1代替
res=b.expand(-1,32,14,-1)
print(res.shape)#torch.Size([1, 32, 14, 1])
permute()
#使用permute()交换维度
print(b.shape)#torch.Size([1, 32, 1, 1])
res=b.permute(0,2,3,1)
print(res.shape)#torch.Size([1, 1, 1, 32])