【Pytorch】：x.view() view()方法的使用

一.按照传入数字使数据维度进行转换

import torch
b=torch.randn(3,2)#也可以写成b=torch.randn([3,2])，效果是一样的
print(b)

tensor([[-0.0035, -0.7276],
[ 2.5166, -0.0649],
[ 2.3062, -1.1144]])

import torch
b=torch.randn(3,2)
print(b)
print(b.view(1,6))
print(b.view(6,1))

tensor([[-0.0035, -0.7276],
[ 2.5166, -0.0649],
[ 2.3062, -1.1144]])
tensor([[-0.0035, -0.7276,  2.5166, -0.0649,  2.3062, -1.1144]])
tensor([[-0.0035],
[-0.7276],
[ 2.5166],
[-0.0649],
[ 2.3062],
[-1.1144]])

二.传入数字-1，自动对维度进行变换

import torch
a=torch.randn(3,5,2)
print(a)
print(a.view(3,1,-1).size())
print(a.view([3,1,-1]).size()) #不管加不加上列表符号，最后reshape的结果是一样的
print(a.view([5,2,-1]).size())

tensor([[[ 1.6498, -0.4354],
[-1.0042, -0.1582],
[ 1.2794, -0.1203],
[ 0.9198,  2.8475],
[ 0.0065,  1.5481]],

[[ 0.7220, -1.1230],
[ 0.2665, -0.6645],
[-0.6159, -0.3833],
[-1.4767,  0.8378],
[-0.3257,  0.2394]],

[[ 0.3784,  0.4233],
[-0.5807,  1.2695],
[ 1.7632,  0.7828],
[ 1.0076,  0.6205],
[ 0.9948, -1.2256]]])
torch.Size([3, 1, 10])
torch.Size([3, 1, 10])
torch.Size([5, 2, 3])

remark：我们能不能使用view（）方法将三维的数据，变成二维的数据呢？

import torch
a=torch.randn(3,5,2)
print(a.size())
print(a.view([3,-1]).size())

torch.Size([3, 5, 2])
torch.Size([3, 10])

posted @ 2021-07-20 11:41  Geeksongs  阅读(2564)  评论(0编辑  收藏  举报