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)絡中的是同樣一張圖片,反傳優(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內置的**進行平方操作,然后
# -*-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用法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
ansible-playbook實現(xiàn)自動部署KVM及安裝python3的詳細教程
這篇文章主要介紹了ansible-playbook實現(xiàn)自動部署KVM及安裝python3的詳細教程,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-05-05
Python Flask全棧項目實戰(zhàn)構建在線書店流程
這篇文章主要為大家介紹了Python Flask全流程全棧項目實戰(zhàn)之在線書店構建實現(xiàn)過程,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-11-11
Python?數(shù)據(jù)可視化實現(xiàn)5種炫酷的動態(tài)圖
數(shù)據(jù)可以幫助我們描述這個世界、闡釋自己的想法和展示自己的成果,但如果只有單調乏味的文本和數(shù)字,我們卻往往能難抓住觀眾的眼球。而很多時候,一張漂亮的可視化圖表就足以勝過千言萬語2022-01-01

