view()的作用相当于numpy中的reshape,重新定义矩阵的形状。
import torch
x=torch.randn(4,4)
print(x)
tensor([[-1.2099, 1.0978, 1.0094, 1.3966], [ 0.2889, -0.5096, 1.8754, 0.7503], [ 1.8894, 1.7621, -1.3559, 0.5547], [ 0.4342, -0.3919, 0.0501, 0.0693]])
y=x.view(16)
print(y)
tensor([-1.2099, 1.0978, 1.0094, 1.3966, 0.2889, -0.5096, 1.8754, 0.7503, 1.8894, 1.7621, -1.3559, 0.5547, 0.4342, -0.3919, 0.0501, 0.0693])
z=x.view(-1,4)
print(z)
tensor([[-1.2099, 1.0978, 1.0094, 1.3966], [ 0.2889, -0.5096, 1.8754, 0.7503], [ 1.8894, 1.7621, -1.3559, 0.5547], [ 0.4342, -0.3919, 0.0501, 0.0693]])
a=x.view(-1,8)
print(a)
tensor([[-1.2099, 1.0978, 1.0094, 1.3966, 0.2889, -0.5096, 1.8754, 0.7503], [ 1.8894, 1.7621, -1.3559, 0.5547, 0.4342, -0.3919, 0.0501, 0.0693]])
**
view中一个参数定为-1,代表动态调整这个维度上的元素个数,以保证元素的总数不变
**
a=torch.randn(1,2,3,4)
print(a.size())
print(a)
torch.Size([1, 2, 3, 4]) tensor([[[[ 0.6739, -0.8965, 0.1655, 0.3740], [ 0.1047, -0.0298, 2.7693, 0.8594], [ 0.3082, -0.5268, -1.9893, 1.9362]], [[ 0.3390, -0.6727, 0.2975, 0.1019], [-0.0172, -1.3910, -1.0128, -0.0642], [ 0.6479, 0.0241, -0.9451, -1.3098]]]])
b=a.transpose(1,2)
print(b.size())
print(b)
torch.Size([1, 3, 2, 4]) tensor([[[[ 0.6739, -0.8965, 0.1655, 0.3740], [ 0.3390, -0.6727, 0.2975, 0.1019]], [[ 0.1047, -0.0298, 2.7693, 0.8594], [-0.0172, -1.3910, -1.0128, -0.0642]], [[ 0.3082, -0.5268, -1.9893, 1.9362], [ 0.6479, 0.0241, -0.9451, -1.3098]]]])
c= a.view(1,3,2,4)
print(c.size())
print(c)
torch.Size([1, 3, 2, 4]) tensor([[[[ 0.6739, -0.8965, 0.1655, 0.3740], [ 0.1047, -0.0298, 2.7693, 0.8594]], [[ 0.3082, -0.5268, -1.9893, 1.9362], [ 0.3390, -0.6727, 0.2975, 0.1019]], [[-0.0172, -1.3910, -1.0128, -0.0642], [ 0.6479, 0.0241, -0.9451, -1.3098]]]])
|