torch.tensor.view(*args)

view(*args) → Tensor
返回一个有相同数据但大小不同的tensor。 返回的tensor必须有与原tensor相同的数据和相同数目的元素,但可以有不同的大小。一个tensor必须是连续的contiguous()才能被查看。

import torch
x = torch.randn(4, 5)

print('tensor原型:',x)

print('tensor维度变换,由(4,5)到(20,1):',x.view(20, 1))
#由(4,5)到(-1,1)的tensor维度变换,其中-1是tensor在1下的另一个维度的大小,即为20/1=20,也就是说在这里-1=20
print('tensor维度变换,由(4,5)到(-1,1):',x.view(-1, 1))

print('tensor维度变换,由(4,5)到(1,20):',x.view(1, 20))
#由(4,5)到(1, -1)的tensor维度变换,其中-1是tensor在1下的另一个维度的大小,即为20/1=20,也就是说在这里-1=20
print('tensor维度变换,由(4,5)到(1,-1):',x.view(1, -1))

代码运行结果:

tensor原型: tensor([[ 0.2278, -0.6850,  0.6527, -0.3206, -2.5704],
        [ 0.8447,  0.2473, -0.5029,  0.6311, -0.4551],
        [ 0.8049, -0.3084,  0.5642,  0.2411,  0.5785],
        [-0.6099, -0.8746, -0.9222,  2.0989,  1.5902]])
tensor维度变换,由(4,5)到(20,1): tensor([[ 0.2278],
        [-0.6850],
        [ 0.6527],
        [-0.3206],
        [-2.5704],
        [ 0.8447],
        [ 0.2473],
        [-0.5029],
        [ 0.6311],
        [-0.4551],
        [ 0.8049],
        [-0.3084],
        [ 0.5642],
        [ 0.2411],
        [ 0.5785],
        [-0.6099],
        [-0.8746],
        [-0.9222],
        [ 2.0989],
        [ 1.5902]])
tensor维度变换,由(4,5)到(-1,1): tensor([[ 0.2278],
        [-0.6850],
        [ 0.6527],
        [-0.3206],
        [-2.5704],
        [ 0.8447],
        [ 0.2473],
        [-0.5029],
        [ 0.6311],
        [-0.4551],
        [ 0.8049],
        [-0.3084],
        [ 0.5642],
        [ 0.2411],
        [ 0.5785],
        [-0.6099],
        [-0.8746],
        [-0.9222],
        [ 2.0989],
        [ 1.5902]])
tensor维度变换,由(4,5)到(1,20): tensor([[ 0.2278, -0.6850,  0.6527, -0.3206, -2.5704,  0.8447,  0.2473, -0.5029,
          0.6311, -0.4551,  0.8049, -0.3084,  0.5642,  0.2411,  0.5785, -0.6099,
         -0.8746, -0.9222,  2.0989,  1.5902]])
tensor维度变换,由(4,5)到(1,-1): tensor([[ 0.2278, -0.6850,  0.6527, -0.3206, -2.5704,  0.8447,  0.2473, -0.5029,
          0.6311, -0.4551,  0.8049, -0.3084,  0.5642,  0.2411,  0.5785, -0.6099,
         -0.8746, -0.9222,  2.0989,  1.5902]])

你可能感兴趣的:(Python,编程开发,PyTorch)