torch中在分类器中,经常会遇到:
x = x.view(x.size(0),-1)
其实在torch里面,view函数就相当于numpy的reshape,执行的操作就是对tensor进行维度转换。
import torch
x = torch.rand(2, 3, 4, 5)
print("x.shape ==",x.shape)
print(x)
x.shape ==torch.Size([2, 3, 4, 5])
tensor([[[[0.8908, 0.6414, 0.0420, 0.7996, 0.9227],
[0.2762, 0.7432, 0.3551, 0.3446, 0.8214],
[0.1160, 0.8383, 0.3293, 0.7381, 0.6932],
[0.0908, 0.6651, 0.0795, 0.7784, 0.3064]],
[[0.7468, 0.7852, 0.7840, 0.8366, 0.4010],
[0.6459, 0.7750, 0.9180, 0.6683, 0.2039],
[0.5624, 0.7804, 0.1549, 0.4298, 0.1371],
[0.0257, 0.4955, 0.4415, 0.9154, 0.4475]],
[[0.3002, 0.7349, 0.3610, 0.6736, 0.8499],
[0.9952, 0.8350, 0.6259, 0.7300, 0.6564],
[0.1684, 0.1463, 0.8989, 0.9147, 0.5497],
[0.6582, 0.9883, 0.6334, 0.7694, 0.0705]]],
[[[0.7365, 0.5310, 0.1505, 0.2687, 0.0552],
[0.2524, 0.9815, 0.8873, 0.9709, 0.1493],
[0.3636, 0.2131, 0.1404, 0.9743, 0.6833],
[0.2626, 0.3598, 0.7807, 0.0799, 0.3007]],
[[0.7043, 0.9580, 0.7539, 0.6319, 0.0233],
[0.7431, 0.5125, 0.5095, 0.9650, 0.5780],
[0.8587, 0.1340, 0.9132, 0.9606, 0.3745],
[0.9142, 0.6857, 0.0358, 0.1492, 0.3507]],
[[0.1944, 0.9274, 0.3656, 0.0507, 0.7060],
[0.3474, 0.9570, 0.1847, 0.0829, 0.0384],
[0.5568, 0.5580, 0.8348, 0.4870, 0.2888],
[0.1907, 0.5136, 0.1139, 0.0645, 0.5830]]]])
x.size(0)
2
执行view函数
x = x.view(x.size(0),-1)
x
——————————————————————————————————————output————————————————————————————————————————
tensor([[0.8908, 0.6414, 0.0420, 0.7996, 0.9227, 0.2762, 0.7432, 0.3551, 0.3446,
0.8214, 0.1160, 0.8383, 0.3293, 0.7381, 0.6932, 0.0908, 0.6651, 0.0795,
0.7784, 0.3064, 0.7468, 0.7852, 0.7840, 0.8366, 0.4010, 0.6459, 0.7750,
0.9180, 0.6683, 0.2039, 0.5624, 0.7804, 0.1549, 0.4298, 0.1371, 0.0257,
0.4955, 0.4415, 0.9154, 0.4475, 0.3002, 0.7349, 0.3610, 0.6736, 0.8499,
0.9952, 0.8350, 0.6259, 0.7300, 0.6564, 0.1684, 0.1463, 0.8989, 0.9147,
0.5497, 0.6582, 0.9883, 0.6334, 0.7694, 0.0705],
[0.7365, 0.5310, 0.1505, 0.2687, 0.0552, 0.2524, 0.9815, 0.8873, 0.9709,
0.1493, 0.3636, 0.2131, 0.1404, 0.9743, 0.6833, 0.2626, 0.3598, 0.7807,
0.0799, 0.3007, 0.7043, 0.9580, 0.7539, 0.6319, 0.0233, 0.7431, 0.5125,
0.5095, 0.9650, 0.5780, 0.8587, 0.1340, 0.9132, 0.9606, 0.3745, 0.9142,
0.6857, 0.0358, 0.1492, 0.3507, 0.1944, 0.9274, 0.3656, 0.0507, 0.7060,
0.3474, 0.9570, 0.1847, 0.0829, 0.0384, 0.5568, 0.5580, 0.8348, 0.4870,
0.2888, 0.1907, 0.5136, 0.1139, 0.0645, 0.5830]])
x.shape == torch.Size([2, 60])
view(xxx,-1) 即,这边的这里-1表示一个不确定的数,就是你如果不确定你想要reshape成几行,但是你很肯定要reshape成xxx列。
上述例子中,
x = x.view(x.size(0),-1) 等价于 x = x.view(x.size(0),60)
|