import torch
t= torch.tensor([
[1,1,1,1],
[2,2,2,2],
[3,3,3,3]
],dtype=torch.float32)
我们可以看到这个张量是一个有两个轴的二阶张量,第一个轴的长度是3,第2个轴的长度是4,第一个轴的元素是数组,第2个轴的元素是数字。
t.size()
torch.Size([3, 4])
t.shape
torch.Size([3, 4])
# 通过检查它的形状长度获得张量的秩 len(t.shape)
2
# 查看分量 t.numel()
12
# 重塑shape t.reshape(2,6)
tensor([[1., 1., 1., 1., 2., 2.],
[2., 2., 3., 3., 3., 3.]])
#改变秩 t.reshape(2,2,3)
tensor([[[1., 1., 1.],
[1., 2., 2.]],
[[2., 2., 3.],
[3., 3., 3.]]])
下一步我们可以改变张量的形状。通过压缩(squeezing)和解缩(unsqueezing)它们
压缩一个张量可以移除所有长度为1的轴。而解缩一个张量则会增加-个长度为1的维度
这些函数允许我们放大或缩小张量的秩
print(t.reshape(1,12)) print(t.reshape(1,12).shape)
tensor([[1., 1., 1., 1., 2., 2., 2., 2., 3., 3., 3., 3.]]) torch.Size([1, 12])
print(t.reshape(1,12).squeeze()) print(t.reshape(1,12).squeeze().shape)
tensor([1., 1., 1., 1., 2., 2., 2., 2., 3., 3., 3., 3.]) torch.Size([12])
print(t.reshape(1,12).squeeze().unsqueeze(dim=0)) print(t.reshape(1,12).squeeze().unsqueeze(dim=0).shape)
tensor([[1., 1., 1., 1., 2., 2., 2., 2., 3., 3., 3., 3.]]) torch.Size([1, 12])
# 通过构建一个flatten函数来压缩一个张量
# 压扁一个张量意味着除去所有的轴,只保留一个,创造了一个单轴的张量,它包含了张量的元素
# flatten的操作,是当我们从一个卷积层过度到全连接层时必须的操作
def flatten(t):
t = t.reshape(1,-1)
t = t.squeeze()
return t
flatten(t)
tensor([1., 1., 1., 1., 2., 2., 2., 2., 3., 3., 3., 3.])
t.reshape(1,12)
tensor([[1., 1., 1., 1., 2., 2., 2., 2., 3., 3., 3., 3.]])
# cat函数组合张量
t1 = torch.tensor([
[1,2],
[2,3]
])
t2 = torch.tensor([
[3,4],
[5,6]
])
torch.cat((t1,t2),dim = 0)
tensor([[1, 2],
[2, 3],
[3, 4],
[5, 6]])



