两者用法完全相同
x=torch.rand(4,3,28,28)
a=x.view(4,3,28*28)
print(a.shape)
一定要记住原始数据的存储方式,不然无法恢复数据
如果维度变换后数据量出现变化,则会提示不能变换维度
squeeze——减少维度
unsqueeze——增加维度
# 在哪一个位置增加一个维度
x=torch.rand(4,3,28,28)
print(x.unsqueeze(0).shape) # [1, 4, 3, 28, 28]
print(x.unsqueeze(-1).shape) # [4, 3, 28, 28, 1]
print(x.unsqueeze(-3).shape) # [4, 3, 1, 28, 28]
# 没有参数默认将维度是1的全部挤压,给定参数如果指定维度的不是1维的,则不能挤压
x=torch.rand(1,32,1,1)
print(x.squeeze().shape) # [32]
print(x.squeeze(1).shape) # [1, 32, 1, 1]
print(x.squeeze(-1).shape) # [1, 32, 1]
print(x.squeeze(-3).shape) # [1, 32, 1, 1]
expend——不会主动重复数据
repeat——会主动重复数据
# 1->n是可以的,n->m会出错,如果想保持这个维度不变,填-1
x=torch.rand(1,32,1,1)
print(x.expand(4,32,4,4).shape) # [4, 32, 4, 4]
print(x.expand(4,-1,3,-1).shape) # [4, 32, 3, 1]
# 参数表示每个维度要重复多少次
x=torch.rand(1,32,1,1)
print(x.repeat(4,32,1,1).shape) # [4, 1024, 1, 1]
x=torch.randn(2,3)
print(x)
print(x.t())
x=torch.randn(4,3,32,32)
# 交换两个维度
print(x.transpose(1,2).shape) # [4, 32, 3, 32]
# 新张量我维度来源与旧向量的哪一维
print(x.permute(0,3,1,2).shape) # [4, 32, 3, 32]
# 将张量的在内存中连续,如果上述操作出现问题可能是内存中张量存储不连续导致的
x.contiguous()