改变tensor向量的形状。注意的是:view目前只是tensor向量的方法。
示例如下:
c = torch.arange(8)
torch.reshape(c, (2, 4))
# 以下两种写法功能相同
# c.reshape(2, 3)
# c.view(2, 3)
【output】
tensor([[0, 1, 2, 3],
[4, 5, 6, 7]])
2、cat
多个tensor向量在某个维度上进行拼接。注意的是:cat只是torch的函数。
a = torch.zeros(2, 3)
b = torch.ones(2, 3)
torch.cat([a, b], axis=1)
【output】
tensor([[0., 0., 0., 1., 1., 1.],
[0., 0., 0., 1., 1., 1.]])
3、stack
多个tensor向量在某个维度上进行堆叠。注意的是:stack只是torch的函数。
a = torch.zeros(2, 3)
b = torch.ones(2, 3)
torch.stack([a, b], dim=1)
【output】
tensor([[[0., 0., 0.],
[1., 1., 1.]],
[[0., 0., 0.],
[1., 1., 1.]]])
4、squeeze
对tensor向量进行压缩,删除元素个数为1的维度。
示例如下:
c = torch.arange(6).reshape(1, 2, 3)
torch.squeeze(c)
# c.squeeze()
【output】
tensor([[0, 1, 2],
[3, 4, 5]])
5、unsqueeze
对tensor向量的维度进行扩充,添加元素个数为1的维度。
c = torch.arange(6).reshape(2, 3)
torch.unsqueeze(c, dim=1)
# c.unsqueeze(dim=1)
【output】
tensor([[[0, 1, 2]],
[[3, 4, 5]]])
6、transpose
对tensor向量的两个维度进行转置。
c = torch.arange(6).reshape(1, 2, 3)
torch.transpose(c, 1, 2)
# c.transpose(1, 2)
【output】
tensor([[[0, 3],
[1, 4],
[2, 5]]])
7、permute
对tensor向量的多个维度进行转置。注意的是:permute只是tensor向量的方法。
c = torch.arange(6).reshape(1, 2, 3)
c.permute(1, 2, 0)
【output】
tensor([[[0],
[1],
[2]],
[[3],
[4],
[5]]])