一、函数简介

Pytorch中的view函数主要用于Tensor维度的重构,即返回一个有相同数据但不同维度的Tensor。

根据上面的描述可知,view函数的操作对象应该是Tensor类型。如果不是Tensor类型,可以通过tensor = torch.tensor(data)来转换。

二、实例讲解

▶view(参数a,参数b,…),其中,总的参数个数表示将张量重构后的维度。

import torch

temp = [1,2,3,4,5,6] # temp的类型为list,非Tensor

temp = torch.tensor(temp) # 将temp由list类型转为Tensor类型

print(temp) # torch.Size([6])

print(temp.view(2,3)) # 将temp的维度改为2*3

print(temp.view(2,3,1)) # 将temp的维度改为2*3*1

print(temp.view(2,3,1,1)) # 更多的维度也没有问题,只要保证维度改变前后的元素个数相同就行,即2*3*1*1=6

▶view(参数a,参数b,…),其中,如果某个参数为-1,则表示该维度取决于其它维度,由Pytorch自己补充。

import torch

temp = [[11,12,13,14,15,16],

[21,22,23,24,25,26]]

temp = torch.tensor(temp)

print(temp)

# torch.Size([2, 6])

print(temp.view(3,-1,2))

# 这里的-1表示该维度取决于其它维度,即等于(2*6)÷3÷2=2

# torch.Size([3, 2, 2])

▶view(-1)表示将Tensor转为一维Tensor。

import torch

temp = [1,2,3,4,5,6] # temp的类型为list,非Tensor

temp = torch.tensor(temp) # 将temp由list类型转为Tensor类型

print(temp) # 本身就是一维张量

print(temp.view(-1)) # 因此,转变后还是一维,没什么变换

temp1 = torch.tensor([[1,2,3],[4,5,6]])

print(temp1) # torch.Size([2, 3])

print(temp1.view(-1)) # 多维张量转为一维张量

欢迎各位伙伴们在评论区交流!

相关阅读

评论可见,请评论后查看内容,谢谢!!!评论后请刷新页面。