欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Pytorch基本變量類型FloatTensor與Variable用法

 更新時(shí)間:2020年01月08日 10:42:06   投稿:jingxian  
今天小編就為大家分享一篇Pytorch基本變量類型FloatTensor與Variable用法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧

pytorch中基本的變量類型當(dāng)屬FloatTensor(以下都用floattensor),而Variable(以下都用variable)是floattensor的封裝,除了包含floattensor還包含有梯度信息

pytorch中的dochi給出一些對(duì)于floattensor的基本的操作,比如四則運(yùn)算以及平方等(鏈接),這些操作對(duì)于floattensor是十分的不友好,有時(shí)候需要寫一個(gè)正則化的項(xiàng)需要寫很長(zhǎng)的一串,比如兩個(gè)floattensor之間的相加需要用torch.add()來(lái)實(shí)現(xiàn)

然而正確的打開方式并不是這樣

韓國(guó)一位大神寫了一個(gè)pytorch的turorial,其中包含style transfer的一個(gè)代碼實(shí)現(xiàn)

for step in range(config.total_step):

    
    # Extract multiple(5) conv feature vectors
    target_features = vgg(target)  # 每一次輸入到網(wǎng)絡(luò)中的是同樣一張圖片,反傳優(yōu)化的目標(biāo)是輸入的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 可以進(jìn)行直接加-操作?可以,并且mean對(duì)所有的元素進(jìn)行均值化造作

      # 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)  # 總共元素的數(shù)目?

其中f1與f2,f3的變量類型是Variable,作者對(duì)其直接用四則運(yùn)算符進(jìn)行加減,并且用python內(nèi)置的**進(jìn)行平方操作,然后

# -*-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) # 兩個(gè)權(quán)重矩陣
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)

基本上調(diào)試的結(jié)果與預(yù)期相符

所以,對(duì)于floattensor以及variable進(jìn)行普通的+-×/以及**沒(méi)毛病

以上這篇Pytorch基本變量類型FloatTensor與Variable用法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論