亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

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

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

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

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

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

for step in range(config.total_step):

    
    # Extract multiple(5) conv feature vectors
    target_features = vgg(target)  # 每一次輸入到網(wǎng)絡(luò)中的是同樣一張圖片,反傳優(yōu)化的目標是輸入的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)  # 總共元素的數(shù)目?

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

# -*-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) # 兩個權(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ù)期相符

所以,對于floattensor以及variable進行普通的+-×/以及**沒毛病

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

相關(guān)文章

最新評論