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)文章
django學(xué)習(xí)之a(chǎn)jax post傳參的2種格式實例
AJAX除了異步的特點外,還有一個就是:瀏覽器頁面局部刷新,下面這篇文章主要給大家介紹了關(guān)于django學(xué)習(xí)之a(chǎn)jax post傳參的2種格式的相關(guān)資料,需要的朋友可以參考下2021-05-05解決python web項目意外關(guān)閉,但占用端口的問題
今天小編就為大家分享一篇解決python web項目意外關(guān)閉,但占用端口的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12ansible-playbook實現(xiàn)自動部署KVM及安裝python3的詳細教程
這篇文章主要介紹了ansible-playbook實現(xiàn)自動部署KVM及安裝python3的詳細教程,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-05-05Python Flask全棧項目實戰(zhàn)構(gòu)建在線書店流程
這篇文章主要為大家介紹了Python Flask全流程全棧項目實戰(zhàn)之在線書店構(gòu)建實現(xiàn)過程,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-11-11PyPDF2讀取PDF文件內(nèi)容保存到本地TXT實例
這篇文章主要介紹了PyPDF2讀取PDF文件內(nèi)容保存到本地TXT實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05Python?數(shù)據(jù)可視化實現(xiàn)5種炫酷的動態(tài)圖
數(shù)據(jù)可以幫助我們描述這個世界、闡釋自己的想法和展示自己的成果,但如果只有單調(diào)乏味的文本和數(shù)字,我們卻往往能難抓住觀眾的眼球。而很多時候,一張漂亮的可視化圖表就足以勝過千言萬語2022-01-01