先创建一个tensor

>>> import torch
>>> a = torch.rand(1, 4, 3)
>>> print(a)
tensor([[[0.0132, 0.7809, 0.0468],
[0.2689, 0.6871, 0.2538],
[0.7656, 0.5300, 0.2499],
[0.2500, 0.4967, 0.0685]]])

分类进行reshape操作时,假如第二维代表类别,直接reshape使得数据对应结果会错

>>> b = a.reshape(-1,4)
>>> print(b)
tensor([[0.0132, 0.7809, 0.0468, 0.2689],
[0.6871, 0.2538, 0.7656, 0.5300],
[0.2499, 0.2500, 0.4967, 0.0685]])

要得到正确的结果,必须先transpose,再进行reshape

>>> c = a.transpose(1,2)
>>> print(c.shape)
torch.Size([1, 3, 4])
>>> d = c.reshape(-1,4)
>>> print(d)
tensor([[0.0132, 0.2689, 0.7656, 0.2500],
[0.7809, 0.6871, 0.5300, 0.4967],
[0.0468, 0.2538, 0.2499, 0.0685]])