在torch里面,view函数相当于numpy的reshape,来看几个例子:
a = torch.arange(1, 17) # a's shape is (16,)
a.view(4, 4) # output below
tensor([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12],
[13, 14, 15, 16]])
[torch.FloatTensor of size 4x4]
a.view(2, 2, 4) # output below
tensor([[[ 1, 2, 3, 4],
[ 5, 6, 7, 8]],
[[ 9, 10, 11, 12],
[13, 14, 15, 16]]])
[torch.FloatTensor of size 2x2x4]
在函数的参数中经常可以看到-1例如x.view(-1, 4)
这里-1表示一个不确定的数,就是你如果不确定你想要reshape成几行,但是你很肯定要reshape成4列,那不确定的地方就可以写成-1
例如一个长度的16向量x,
x.view(-1, 4)等价于x.view(4, 4)
x.view(-1, 2)等价于x.view(8,2)
以此类推
本文详细介绍了PyTorch中的view函数,该函数的作用类似于numpy中的reshape,用于改变张量的形状。通过实例展示了如何使用view函数进行不同维度的转换,并解释了参数-1在函数中的含义及用法。
1135





