-
reshape
reshape函数用于改变数据的维度;
# 使用data.shape data.size()查看数据大小
# reshape 前后元素个数不变
data = torch.tensor([[1,2,3],[4,5,6]]) # torch.Size([2, 3])
data1 = data.reshape(3,2) # torch.Size([3, 2])
# 使用-1省略形状
data2 = data.reshape(1,-1) # torch.Size([1, 6])
data3 = data.reshape(-1,1) # torch.Size([6, 1])
-
transpose/permute
transpose把两个维度位置进行交换;permute一次性更换维度位置;
-
view
只可用于存储在整块内存中的张量(有些张量由不同数据块组成(经过transpose/permute操作后使得张量不连续)——先使用contiguous函数使之在一块内存);
# transpose 只可两个维度交换
data = torch.randint(0,10,[3,4,5]) # torch.Size([3, 4, 5])
data1 = data.transpose(0,2) # torch.Size([5, 4, 3]) or data1 = torch.transpose(data,0,2)
# permute
data2 = data.permute(0,2,1) # torch.Size([3, 5, 4]) or torch.permute(data,0,2,1)
# view
data3 = data.view(3,2,10) # torch.Size([3, 2, 10])
print(data2.is_contiguous()) # False
data4 = data2.contiguous().view(3,10,2) # torch.Size([3, 10, 2])
-
squeeze/unsqueeze
squeeze删除shape为1的维度;unsqueeze在某一位置添加为1的维度;
data = torch.randint(0,10,[2,1,2,1]) # torch.Size([2, 1, 2])
# squeeze 默认去掉所有为1的维度
data1 = data.squeeze() # torch.Size([2, 2])
# squeeze 指定去掉为1的维度
data2 = data.squeeze(1) # torch.Size([2, 2, 1])
# unsqueeze
data3 = data.unsqueeze(0) # torch.Size([1, 2, 1, 2, 1])
data4 = data.unsqueeze(-1) # torch.Size([2, 1, 2, 1, 1])