pytorch中Parameter函數(shù)用法示例
用法介紹
pytorch中的Parameter函數(shù)可以對(duì)某個(gè)張量進(jìn)行參數(shù)化。它可以將不可訓(xùn)練的張量轉(zhuǎn)化為可訓(xùn)練的參數(shù)類型,同時(shí)將轉(zhuǎn)化后的張量綁定到模型可訓(xùn)練參數(shù)的列表中,當(dāng)更新模型的參數(shù)時(shí)一并將其更新。
torch.nn.parameter.Parameter
- data (Tensor):表示需要參數(shù)化的張量
- requires_grad (bool, optional):表示是否該張量是否需要梯度,默認(rèn)值為True
代碼介紹
pytorch中的Parameter函數(shù)具體的代碼示例如下所示
import torch import torch.nn as nn class NeuralNetwork(nn.Module): def __init__(self, input_dim, output_dim): super(NeuralNetwork, self).__init__() self.linear = nn.Linear(input_dim, output_dim) self.linear.weight = torch.nn.Parameter(torch.zeros(input_dim, output_dim)) self.linear.bias = torch.nn.Parameter(torch.ones(output_dim)) def forward(self, input_array): output = self.linear(input_array) return output if __name__ == '__main__': net = NeuralNetwork(4, 6) for param in net.parameters(): print(param)
代碼的結(jié)果如下所示:

當(dāng)神經(jīng)網(wǎng)絡(luò)的參數(shù)不是用Parameter函數(shù)參數(shù)化直接賦值給權(quán)重參數(shù)時(shí),則會(huì)報(bào)錯(cuò),具體的程序
import torch import torch.nn as nn class NeuralNetwork(nn.Module): def __init__(self, input_dim, output_dim): super(NeuralNetwork, self).__init__() self.linear = nn.Linear(input_dim, output_dim) self.linear.weight = torch.zeros(input_dim, output_dim) self.linear.bias = torch.ones(output_dim) def forward(self, input_array): output = self.linear(input_array) return output if __name__ == '__main__': net = NeuralNetwork(4, 6) for param in net.parameters(): print(param)
代碼運(yùn)行報(bào)錯(cuò)結(jié)果如下所示:

以上就是pytorch中Parameter函數(shù)用法示例的詳細(xì)內(nèi)容,更多關(guān)于pytorch中Parameter函數(shù)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python sklearn中的.fit與.predict的用法說明
這篇文章主要介紹了Python sklearn中的.fit與.predict的用法說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-06-06
Python 中urls.py:URL dispatcher(路由配置文件)詳解
這篇文章主要介紹了Python 中urls.py:URL dispatcher(路由配置文件)詳解的相關(guān)資料,需要的朋友可以參考下2017-03-03
Python操作MySQL簡單實(shí)現(xiàn)方法
這篇文章主要介紹了Python操作MySQL簡單實(shí)現(xiàn)方法,通過一個(gè)簡單的實(shí)例講述了Python針對(duì)mysql數(shù)據(jù)庫的增刪改查技巧,需要的朋友可以參考下2015-01-01
python實(shí)現(xiàn)的簡單猜數(shù)字游戲
這篇文章主要介紹了python實(shí)現(xiàn)的簡單猜數(shù)字游戲,涉及Python操作隨機(jī)數(shù)的技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-04-04
Python數(shù)據(jù)結(jié)構(gòu)之棧詳解
棧和隊(duì)列是在程序設(shè)計(jì)中常見的數(shù)據(jù)類型,從數(shù)據(jù)結(jié)構(gòu)的角度來講,棧和隊(duì)列也是線性表,是操作受限的線性表。本文將詳細(xì)介紹一下Python中的棧,感興趣的可以了解一下2022-03-03
淺談Django自定義模板標(biāo)簽template_tags的用處
這篇文章主要介紹了淺談Django自定義模板標(biāo)簽template_tags的用處,具有一定借鑒價(jià)值,需要的朋友可以參考下。2017-12-12

