Pytorch基本变量类型FloatTensor与Variable用法

pytorch中基本的变量类型当属FloatTensor(以下都用floattensor),而Variable(以下都用variable)是floattensor的封装,除了包含floattensor还包含有梯度信息

pytorch中的dochi给出一些对于floattensor的基本的操作,比如四则运算以及平方等(链接),这些操作对于floattensor是十分的不友好,有时候需要写一个正则化的项需要写很长的一串,比如两个floattensor之间的相加需要用torch.add()来实现

然而正确的打开方式并不是这样

韩国一位大神写了一个pytorch的turorial,其中包含style transfer的一个代码实现

for step in range(config.total_step):

    # Extract multiple(5) conv feature vectors
    target_features = vgg(target)  # 每一次输入到网络中的是同样一张图片,反传优化的目标是输入的target
    content_features = vgg(Variable(content))
    style_features = vgg(Variable(style))

    style_loss = 0
    content_loss = 0
    for f1, f2, f3 in zip(target_features, content_features, style_features):
      # Compute content loss (target and content image)
      content_loss += torch.mean((f1 - f2)**2) # square 可以进行直接加-操作?可以,并且mean对所有的元素进行均值化造作

      # Reshape conv features
      _, c, h, w = f1.size() # channel height width
      f1 = f1.view(c, h * w) # reshape a vector
      f3 = f3.view(c, h * w) # reshape a vector

      # Compute gram matrix
      f1 = torch.mm(f1, f1.t())
      f3 = torch.mm(f3, f3.t())

      # Compute style loss (target and style image)
      style_loss += torch.mean((f1 - f3)**2) / (c * h * w)  # 总共元素的数目?

其中f1与f2,f3的变量类型是Variable,作者对其直接用四则运算符进行加减,并且用python内置的**进行平方操作,然后

# -*-coding: utf-8 -*-
import torch
from torch.autograd import Variable

# dtype = torch.FloatTensor
dtype = torch.cuda.FloatTensor # Uncomment this to run on GPU

# N is batch size; D_in is input dimension;
# H is hidden dimension; D_out is output dimension.
N, D_in, H, D_out = 64, 1000, 100, 10

# Randomly initialize weights
w1 = torch.randn(D_in, H).type(dtype) # 两个权重矩阵
w2 = torch.randn(D_in, H).type(dtype)
# operate with +-*/ and **
w3 = w1-2*w2
w4 = w3**2
w5 = w4/w1

# operate the Variable with +-*/ and **
w6 = Variable(torch.randn(N, D_in).type(dtype))
w7 = Variable(torch.randn(N, D_in).type(dtype))
w8 = w6 + w7
w9 = w6*w7
w10 = w9**2
print(1)

基本上调试的结果与预期相符

所以,对于floattensor以及variable进行普通的+-×/以及**没毛病

以上这篇Pytorch基本变量类型FloatTensor与Variable用法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • Pytorch之Variable的用法

    1.简介 torch.autograd.Variable是Autograd的核心类,它封装了Tensor,并整合了反向传播的相关实现 Variable和tensor的区别和联系 Variable是篮子,而tensor是鸡蛋,鸡蛋应该放在篮子里才能方便拿走(定义variable时一个参数就是tensor) Variable这个篮子里除了装了tensor外还有requires_grad参数,表示是否需要对其求导,默认为False Variable这个篮子呢,自身有一些属性 比如grad,梯度vari

  • PyTorch基本数据类型(一)

    PyTorch基础入门一:PyTorch基本数据类型 1)Tensor(张量) Pytorch里面处理的最基本的操作对象就是Tensor(张量),它表示的其实就是一个多维矩阵,并有矩阵相关的运算操作.在使用上和numpy是对应的,它和numpy唯一的不同就是,pytorch可以在GPU上运行,而numpy不可以.所以,我们也可以使用Tensor来代替numpy的使用.当然,二者也可以相互转换. Tensor的基本数据类型有五种: 32位浮点型:torch.FloatTensor.pyorch.T

  • PyTorch中的Variable变量详解

    一.了解Variable 顾名思义,Variable就是 变量 的意思.实质上也就是可以变化的量,区别于int变量,它是一种可以变化的变量,这正好就符合了反向传播,参数更新的属性. 具体来说,在pytorch中的Variable就是一个存放会变化值的地理位置,里面的值会不停发生片花,就像一个装鸡蛋的篮子,鸡蛋数会不断发生变化.那谁是里面的鸡蛋呢,自然就是pytorch中的tensor了.(也就是说,pytorch都是有tensor计算的,而tensor里面的参数都是Variable的形式).如果

  • pytorch: tensor类型的构建与相互转换实例

    Summary 主要包括以下三种途径: 使用独立的函数: 使用torch.type()函数: 使用type_as(tesnor)将张量转换为给定类型的张量. 使用独立函数 import torch tensor = torch.randn(3, 5) print(tensor) # torch.long() 将tensor投射为long类型 long_tensor = tensor.long() print(long_tensor) # torch.half()将tensor投射为半精度浮点类型

  • Pytorch Tensor的统计属性实例讲解

    1. 范数 示例代码: import torch a = torch.full([8], 1) b = a.reshape([2, 4]) c = a.reshape([2, 2, 2]) # 求L1范数(所有元素绝对值求和) print(a.norm(1), b.norm(1), c.norm(1)) # 求L2范数(所有元素的平方和再开根号) print(a.norm(2), b.norm(2), c.norm(2)) # 在b的1号维度上求L1范数 print(b.norm(1, dim=

  • Pytorch中的variable, tensor与numpy相互转化的方法

    在使用pytorch作为深度学习的框架时,经常会遇到变量variable.张量tensor与矩阵numpy的类型的相互转化的问题,本章结合这实际图像对此转化方法进行实现. 1.加载需要用到的模块 import torch from torch.autograd import Variable import matplotlib.pyplot as plt import matplotlib.image as mpimg 2.显示图片与图片中的一部分区域 test_img = mpimg.imre

  • Pytorch Tensor基本数学运算详解

    1. 加法运算 示例代码: import torch # 这两个Tensor加减乘除会对b自动进行Broadcasting a = torch.rand(3, 4) b = torch.rand(4) c1 = a + b c2 = torch.add(a, b) print(c1.shape, c2.shape) print(torch.all(torch.eq(c1, c2))) 输出结果: torch.Size([3, 4]) torch.Size([3, 4]) tensor(1, dt

  • Pytorch基本变量类型FloatTensor与Variable用法

    pytorch中基本的变量类型当属FloatTensor(以下都用floattensor),而Variable(以下都用variable)是floattensor的封装,除了包含floattensor还包含有梯度信息 pytorch中的dochi给出一些对于floattensor的基本的操作,比如四则运算以及平方等(链接),这些操作对于floattensor是十分的不友好,有时候需要写一个正则化的项需要写很长的一串,比如两个floattensor之间的相加需要用torch.add()来实现 然而

  • 基于pytorch 预训练的词向量用法详解

    如何在pytorch中使用word2vec训练好的词向量 torch.nn.Embedding() 这个方法是在pytorch中将词向量和词对应起来的一个方法. 一般情况下,如果我们直接使用下面的这种: self.embedding = torch.nn.Embedding(num_embeddings=vocab_size, embedding_dim=embeding_dim) num_embeddings=vocab_size 表示词汇量的大小 embedding_dim=embeding

  • js中判断变量类型函数typeof的用法总结

    1.作用: typeof 运算符返回一个用来表示表达式的数据类型的字符串. 可能的字符串有:"number"."string"."boolean"."object"."function" 和 "undefined". 2.常用返回值说明 表达式 返回值 typeof undefined 'undefined' typeof null 'object' typeof true 'boole

  • C语言变量类型与输出控制用法实例教程

    本文实例讲述了C语言变量类型与输出控制用法,有助于读者很好的对其进行总结与归纳.该实例分享给大家供大家参考借鉴之用.具体如下: 完整实例代码如下: /********************************************** **<Beginning C 4th Edition>Notes codes ** Created by Goopand ** Compiler: gcc 4.7.0 *******************************************

  • Python学习笔记基本数据结构之序列类型list tuple range用法分析

    本文实例讲述了Python学习笔记基本数据结构之序列类型list tuple range用法.分享给大家供大家参考,具体如下: list 和 tuple list:列表,由 [] 标识: 有序:可改变列表元素 tuple:元组,由 () 标识: 有序:不可改变元组元素(和list的主要区别) list 和 tuple 的创建: print([]) # 空list print(["a",1,True]) # 元素类型不限 print([x for x in range(0,6)]) #

  • pytorch:model.train和model.eval用法及区别详解

    使用PyTorch进行训练和测试时一定注意要把实例化的model指定train/eval,eval()时,框架会自动把BN和DropOut固定住,不会取平均,而是用训练好的值,不然的话,一旦test的batch_size过小,很容易就会被BN层导致生成图片颜色失真极大!!!!!! Class Inpaint_Network() ...... Model = Inpaint_Nerwoek() #train: Model.train(mode=True) ..... #test: Model.ev

  • 解决Pytorch自定义层出现多Variable共享内存错误问题

    错误信息: RuntimeError: in-place operations can be only used on variables that don't share storage with any other variables, but detected that there are 4 objects sharing it 自动求导是很方便, 但是想想, 如果两个Variable共享内存, 再对这个共享的内存的数据进行修改, 就会引起错误! 一般是由于 inplace操作或是ind

  • Pytorch 卷积中的 Input Shape用法

    先看Pytorch中的卷积 class torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True) 二维卷积层, 输入的尺度是(N, C_in,H,W),输出尺度(N,C_out,H_out,W_out)的计算方式 这里比较奇怪的是这个卷积层居然没有定义input shape,输入尺寸明明是:(N, C_in, H,W),但是定义中却只需

  • 支持PyTorch的einops张量操作神器用法示例详解

    目录 基础用法 高级用法 今天做visual transformer研究的时候,发现了einops这么个神兵利器,决定大肆安利一波. 先看链接:https://github.com/arogozhnikov/einops 安装: pip install einops 基础用法 einops的强项是把张量的维度操作具象化,让开发者"想出即写出".举个例子: from einops import rearrange # rearrange elements according to the

随机推荐