pytorch中tensor进行reshape操作后原始数据的顺序

pytorch中,经常需要对tensor进行reshape操作,使其符合特定网络的输入格式。在将网络的输

出重新reshape回输入前的形状时,tensor的特征是否还是按输入的顺序进行排列?

带着疑问做了下面的实验

1
2
3
4
5
6
7
8
9
10
11
12
13
14
x1 = torch.randn(2, 3)
x2 = torch.randn(2, 3)
x3 = torch.randn(2, 3)
x4 = torch.stack((x1, x2, x3), 0)

shape = x4.shape
print("x4:", x4.shape)
print("x4:\n", x4)
x4 = x4.reshape(x4.shape[0]*x4.shape[1], x4.shape[-1])
print("reshaped x4:", x4.shape)
print("reshaped x4:\n", x4)
x4 = x4.reshape(shape[0], shape[1], shape[-1])
print("recovered x4:\n", x4, x4.shape) # print("x5:\n", x5)

输出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
x4: torch.Size([3, 2, 3])
x4:
tensor([[[-1.2061, 0.0617, 1.1632],
[-1.5008, -1.5944, -0.0187]],

[[-2.1325, -0.5270, -0.1021],
[ 0.0099, -0.4454, -1.4976]],

[[-0.9475, -0.6130, -0.1291],
[-0.4107, 1.3931, -0.0984]]])
reshaped x4: torch.Size([6, 3])
reshaped x4:
tensor([[-1.2061, 0.0617, 1.1632],
[-1.5008, -1.5944, -0.0187],
[-2.1325, -0.5270, -0.1021],
[ 0.0099, -0.4454, -1.4976],
[-0.9475, -0.6130, -0.1291],
[-0.4107, 1.3931, -0.0984]])
recovered x4:
tensor([[[-1.2061, 0.0617, 1.1632],
[-1.5008, -1.5944, -0.0187]],

[[-2.1325, -0.5270, -0.1021],
[ 0.0099, -0.4454, -1.4976]],

[[-0.9475, -0.6130, -0.1291],
[-0.4107, 1.3931, -0.0984]]]) torch.Size([3, 2, 3])

x1, x2x3三个tensor通过stack操作堆到一起后通过reshape操作改变维度的形状

接着再将reshape完的tensor变回原来的形状,发现输出数据的顺序和改变形状之前相同

表明在reshape过程中,tensor能够保持数据的顺序


pytorch中tensor进行reshape操作后原始数据的顺序
http://yojayc.github.io/2021/11/19/pytorch中tensor进行reshape操作后原始数据的顺序/
作者
Truman
发布于
2021年11月19日
更新于
2026年4月5日
许可协议