pytorch中Parameter函數(shù)用法示例
用法介紹
pytorch中的Parameter函數(shù)可以對某個(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í),則會報(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ù)的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
基于Python編寫將文本轉(zhuǎn)換為語音的簡易應(yīng)用
這篇文章主要介紹了如何使用Python編寫一個(gè)簡單的應(yīng)用程序,將文本轉(zhuǎn)換為語音,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以動手嘗試一下2023-08-08python?包?requests?實(shí)現(xiàn)請求操作
這篇文章主要介紹了python?包?requests?實(shí)現(xiàn)請求操作,文章介紹內(nèi)容包括帶參數(shù)請求、自定義headers,文章內(nèi)容詳細(xì)具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-04-04如何使用python3獲取當(dāng)前路徑及os.path.dirname的使用
這篇文章主要介紹了如何使用python3獲取當(dāng)前路徑及os.path.dirname的使用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-12-12Python 如何實(shí)時(shí)向文件寫入數(shù)據(jù)(附代碼)
這篇文章主要介紹了Python 如何實(shí)時(shí)向文件寫入數(shù)據(jù)(附代碼),具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-07-07Pycharm創(chuàng)建python文件自動添加日期作者等信息(步驟詳解)
這篇文章主要介紹了Pycharm創(chuàng)建python文件自動添加日期作者等信息(步驟詳解),本文分步驟給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-02-02Python實(shí)現(xiàn)的根據(jù)文件名查找數(shù)據(jù)文件功能示例
這篇文章主要介紹了Python實(shí)現(xiàn)的根據(jù)文件名查找數(shù)據(jù)文件功能,涉及Python針對文件與目錄的遍歷、查詢等相關(guān)操作技巧,需要的朋友可以參考下2018-05-05