1.torch.unsqueeze
(input, dim) → Tensor
增加新维度dim,新维度的长度为1.
import torch
x = torch.Tensor([[[1.0],[2.0],[3.0]],[[7.0],[9.0],[10.0]]])
print(x.dim(),x.size())
print(x.unsqueeze(1).dim(),x.unsqueeze(1).size())
x.unsqueeze(1)
print(x.dim(),x.size()) # x不改变
x.unsqueeze_(1)
print(x.dim(),x.size()) # x改变
###
3 torch.Size([2, 3, 1])
4 torch.Size([2, 1, 3, 1])
3 torch.Size([2, 3, 1])
4 torch.Size([2, 1, 3, 1])
2.torch.
squeeze
(input, dim=None, *, out=None) → Tensor
降维操作,去除维度长度为1的维度,如果输入是形如(A×1×B×1×C×1×D),那么输出形状就为: (A×B×C×D)。如果有指定的dim时,只去除指定维度。
import torch
x = torch.zeros(2, 1, 2, 1, 2)
print(x.squeeze().size())
print(x.size())
print(x.squeeze(1).size())
###
torch.Size([2, 2, 2])
torch.Size([2, 1, 2, 1, 2])
torch.Size([2, 2, 1, 2])
3.view(*args) → Tensor
返回一个有相同数据但大小不同的tensor。 返回的tensor必须有与原tensor相同的数据和相同数目的元素,但可以有不同的大小。一个tensor必须是连续的contiguous()
才能被查看。
view_as(tensor)
返回被视作与给定的tensor相同大小的原tensor。 等效于:self.view(tensor.size())
import torch
x = torch.zeros(16)
y = torch.zeros(8,2)
print(x.view(4,4).size())
print(x.size())
print(x.view(2,-1).size())
print(x.view_as(y).size())
print(x.view(y.size()).size())
###
torch.Size([4, 4])
torch.Size([16])
torch.Size([2, 8])
torch.Size([8, 2])
torch.Size([8, 2])
4.expand(*sizes)、expand_as(tensor)
expand返回tensor的一个新视图,单个维度扩大为更大的尺寸。 tensor也可以扩大为更高维,新增加的维度将附在前面。 扩大tensor不需要分配新内存,只是仅仅新建一个tensor的视图,其中通过将stride
设为0,一维将会扩展位更高维。任何一个一维的在不分配新内存情况下可扩展为任意的数值。将维度长度为1的维度通过复制拓展,其余维度应与原tensor维度一致。
expand_as(tensor) 等价于self.expand(tensor.size())
import torch
y = torch.arange(5).view(5,1)
x = torch.arange(15).view(5,3)
print(y.size())
print(y,y.expand(5,3))
print(y.expand_as(x))
###
torch.Size([5, 1])
tensor([[0],
[1],
[2],
[3],
[4]])
tensor([[0, 0, 0],
[1, 1, 1],
[2, 2, 2],
[3, 3, 3],
[4, 4, 4]])
tensor([[0, 0, 0],
[1, 1, 1],
[2, 2, 2],
[3, 3, 3],
[4, 4, 4]])
5.torch.
cat
(tensors, dim=0, *, out=None) → Tensor
torch.
stack
(tensors, dim=0, *, out=None) → Tensor
tensors (sequence of Tensors) – sequence of tensors to concatenate
dim (int) – dimension to insert. Has to be between 0 and the number of dimensions of concatenated tensors (inclusive)
区别:
(1)cat不拓展维数,stack自动拓展维数(参数dim上增加一个维度)
(2)cat允许输入的tensors在dim方向上具有不同的长度,而stack因为要拓展维度,要求输入的所有tensors形状一致。
cat可以用在data和label之间的拼接,stack可以用在将多张图片合并成一个batch。
注:numpy 中的concaten和stack也是有此效果。np可用expand_dims(array, axis)拓展维度。
import torch
a = torch.tensor([[1,2],[3,4]])
b = torch.tensor([[5,6],[7,8]])
print(torch.cat((a,b), dim=0))
print(torch.stack((a,b), dim=0))
print(torch.cat((a.unsqueeze(0),b.unsqueeze(0)), dim=0))
#cat 不拓展维度
tensor([[1, 2],
[3, 4],
[5, 6],
[7, 8]])
#stack 自动在维度上拓展
tensor([[[1, 2],
[3, 4]],
[[5, 6],
[7, 8]]])
#stack等价于在向量拓展的基础上cat
tensor([[[1, 2],
[3, 4]],
[[5, 6],
[7, 8]]])