pytorch中view()函数的用法

pytorch中view的用法相当于numpy中的reshape,即对数据维度进行重新定义,view(-1, 4)其中4代表分成4列,-1代表不确定行大小,即能分成多少行让程序自行计算,如果不能整除,则程序报错。

import torch
a = torch.arange(1, 21)
print(a)

输出结果:
tensor([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
        19, 20])
---------------------------------------------------------------------------
b = a.view(-1, 4)
print(b)

输出结果:
tensor([[ 1,  2,  3,  4],
        [ 5,  6,  7,  8],
        [ 9, 10, 11, 12],
        [13, 14, 15, 16],
        [17, 18, 19, 20]])
---------------------------------------------------------------------------
c = a.view(-1, 2, 5)
print(c)

输出结果:
tensor([[[ 1,  2,  3,  4,  5],
         [ 6,  7,  8,  9, 10]],

        [[11, 12, 13, 14, 15],
         [16, 17, 18, 19, 20]]])

         [16, 17, 18, 19, 20]]])
---------------------------------------------------------------------------
d = a.view(-1, 3)
print(d)

输出结果:
RuntimeError                              Traceback (most recent call last)
Input In [9], in ()
----> 1 d = a.view(-1, 3)
      2 print(d)

RuntimeError: shape '[-1, 3]' is invalid for input of size 20

你可能感兴趣的:(pytorch)