pytorch学习笔记 torchnn.ModuleList
1?nn.ModuleList原理
nn.ModuleList,它是一個儲存不同 module,并自動將每個 module 的 parameters 添加到網(wǎng)絡(luò)之中的容器。
你可以把任意 nn.Module 的子類 (比如 nn.Conv2d, nn.Linear 之類的) 加到這個 list 里面,方法和 Python 自帶的 list 一樣,無非是 extend,append 等操作。
但不同于一般的 list,加入到 nn.ModuleList 里面的 module 是會自動注冊到整個網(wǎng)絡(luò)上的,同時 module 的 parameters 也會自動添加到整個網(wǎng)絡(luò)中。
若使用python的list,則會出問題。
import torch class net_mod_lst(torch.nn.Module):def __init__(self):super(net_mod_lst,self).__init__()self.modlst=torch.nn.ModuleList([torch.nn.Conv2d(1,20,5),torch.nn.ReLU(),torch.nn.Conv2d(20,64,5)])def forward(self,x):for m in self.modlst:x=m(x)return xnet_mod=net_mod_lst() print(net_mod) ''' net_mod_lst((modlst): ModuleList((0): Conv2d(1, 20, kernel_size=(5, 5), stride=(1, 1))(1): ReLU()(2): Conv2d(20, 64, kernel_size=(5, 5), stride=(1, 1))) )'''2?nn.Sequential與nn.ModuleList的區(qū)別
2.1?不同點(diǎn)1
?
nn.Sequential內(nèi)部實(shí)現(xiàn)了forward函數(shù),因此可以不用寫forward函數(shù)。而nn.ModuleList則沒有實(shí)現(xiàn)內(nèi)部forward函數(shù)。
?
但如果Sequential是在繼承了nn.Module的類中的話,那也要forward函數(shù)了
import torch class net_mod_lst(torch.nn.Module):def __init__(self):super(net_mod_lst,self).__init__()self.seq=torch.nn.Sequential(torch.nn.Conv2d(1,20,5),torch.nn.ReLU(),torch.nn.Conv2d(20,64,5))def forward(self,x):x=self.seq(x)return xnet_mod=net_mod_lst() print(net_mod) ''' net_mod_lst((seq): Sequential((0): Conv2d(1, 20, kernel_size=(5, 5), stride=(1, 1))(1): ReLU()(2): Conv2d(20, 64, kernel_size=(5, 5), stride=(1, 1))) ) '''2.2?不同點(diǎn)2
nn.Sequential可以使用OrderedDict對每層進(jìn)行命名
見pytorch 學(xué)習(xí)筆記:nn.Sequential構(gòu)造神經(jīng)網(wǎng)絡(luò)_劉文巾的博客-CSDN博客
2.3?不同點(diǎn)3
nn.Sequential里面的模塊按照順序進(jìn)行排列的,所以必須確保前一個模塊的輸出大小和下一個模塊的輸入大小是一致的。
而nn.ModuleList 并沒有定義一個網(wǎng)絡(luò),它只是將不同的模塊儲存在一起,這些模塊之間并沒有什么先后順序可言。
《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的pytorch学习笔记 torchnn.ModuleList的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: pytorch 笔记: torch.nn
- 下一篇: pytorch笔记 pytorch模型中