随机生成一个4x4张量,view类似于numpy的reshape函数
a=torch.randn(4,4)
tensor([[ 0.1212, -0.4321, 1.9495, -0.2867],
[-0.1386, 1.8068, -0.8957, -1.2897],
[ 0.1581, -0.7511, 1.4206, 0.9387],
[ 0.1972, -0.6240, -1.3137, 0.4474]])
确定行数,列数
a.view(2,8)
tensor([[ 0.1212, -0.4321, 1.9495, -0.2867, -0.1386, 1.8068, -0.8957, -1.2897],
[ 0.1581, -0.7511, 1.4206, 0.9387, 0.1972, -0.6240, -1.3137, 0.4474]])
确定行数
a.view(2,-1)
tensor([[ 0.1212, -0.4321, 1.9495, -0.2867, -0.1386, 1.8068, -0.8957, -1.2897],
[ 0.1581, -0.7511, 1.4206, 0.9387, 0.1972, -0.6240, -1.3137, 0.4474]])
确定列数
a.view(-1,8)
tensor([[ 0.1212, -0.4321, 1.9495, -0.2867, -0.1386, 1.8068, -0.8957, -1.2897],
[ 0.1581, -0.7511, 1.4206, 0.9387, 0.1972, -0.6240, -1.3137, 0.4474]])
行数,列数,并不可以随便设置
a.view(3,-1)
RuntimeError: shape '[3, -1]' is invalid for input of size 16