Pytorch之view及view_as使用详解

yipeiwu_com6年前Python基础

view()函数是在torch.Tensor.view()下的一个函数,可以有tensor调用,也可以有variable调用。

其作用在于返回和原tensor数据个数相同,但size不同的tensor

【Numpy中的size是元素个数,但是在Pytorch中size等价为Numpy中的shape】

view函数的-1参数的作用在于基于另一参数,自动计算该维度的大小

很重要的一点

view函数只能由于contiguous的张量上,具体而言,就是在内存中连续存储的张量。

具体而言,可以参看 /post/177564.htm

所以,当tensor之前调用了transpose, permute函数就会是tensor内存中变得不再连续,就不能调用view函数。

所以,应该提前做tensor.contiguous()的操作

view函数与Pytorch0.4中新增的reshape的区别

reshape函数调用是不依赖于tensor在内存中是不是连续的。

reshape ≈ tensor.contiguous().view

代码

import numpy as np
import torch
from torch.autograd import Variable
 
x = torch.Tensor(2,2,2)
print(x)
 
y = x.view(1,8)
print(y)
 
z = x.view(-1,4) # the size -1 is inferred from other dimensions
print(z)
 
t = x.view(8)
print(t)

输出

tensor([[[1.3712e-14, 6.4069e+02],
   [4.3066e+21, 1.1824e+22]],

  [[4.3066e+21, 6.3828e+28],
   [3.8016e-39, 0.0000e+00]]])

#x.view(1,8)生成的是[1,8]的张量
tensor([[1.3712e-14, 6.4069e+02, 4.3066e+21, 1.1824e+22, 4.3066e+21, 6.3828e+28,
   3.8016e-39, 0.0000e+00]])

#x.view(-1,4)其中-1是在4下的另一个维度的大小,也就是8/4=2,所以生成的是[2,4]的张量
tensor([[1.3712e-14, 6.4069e+02, 4.3066e+21, 1.1824e+22],
  [4.3066e+21, 6.3828e+28, 3.8016e-39, 0.0000e+00]])

x.view(8)生成的是[8,]的张量,是个数组
tensor([1.3712e-14, 6.4069e+02, 4.3066e+21, 1.1824e+22, 4.3066e+21, 6.3828e+28,
  3.8016e-39, 0.0000e+00])

view_as

返回被视作与给定的tensor相同大小的原tensor。 等效于:

self.view(tensor.size())

具体用法为:

代码

a = torch.Tensor(2, 4)
b = a.view_as(torch.Tensor(4, 2))
print (b)

输出

tensor([[1.3712e-14, 6.4069e+02],
  [4.3066e+21, 1.1824e+22],
  [4.3066e+21, 6.3828e+28],
  [3.8016e-39, 0.0000e+00]])

以上这篇Pytorch之view及view_as使用详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python读写文件基础知识点

Python读写文件基础知识点

在 Python 中,读写文件有 3 个步骤:  1.调用 open()函数,返回一个 File 对象。  2.调用 File 对象的 read()或 write()...

Python values()与itervalues()的用法详解

dict 对象有一个 values() 方法,这个方法把dict转换成一个包含所有value的list,这样,我们迭代的就是 dict的每一个 value: d = { 'Adam'...

简介Django中内置的一些中间件

认证支持中间件 中间件类: django.contrib.auth.middleware.AuthenticationMiddleware . django.contrib.auth.m...

python在指定目录下查找gif文件的方法

本文实例讲述了python在指定目录下查找gif文件的方法。分享给大家供大家参考。具体实现方法如下: #!/usr/bin/python # Use the standard fin...

python3.6使用pymysql连接Mysql数据库

python3.6使用pymysql连接Mysql数据库

python3.6使用pymysql连接Mysql数据库及简单的增删改查操作,供大家参考,具体内容如下 折腾好半天的数据库连接,由于之前未安装pip ,而且自己用的Python 版本为3...