Pytorch基本變數型別FloatTensor與Variable用法
阿新 • • 發佈:2020-01-09
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用法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。