pytorch学习笔记 torchnn.ModuleList
1?nn.ModuleList原理
nn.ModuleList,它是一個儲存不同 module,并自動將每個 module 的 parameters 添加到網絡之中的容器。
你可以把任意 nn.Module 的子類 (比如 nn.Conv2d, nn.Linear 之類的) 加到這個 list 里面,方法和 Python 自帶的 list 一樣,無非是 extend,append 等操作。
但不同于一般的 list,加入到 nn.ModuleList 里面的 module 是會自動注冊到整個網絡上的,同時 module 的 parameters 也會自動添加到整個網絡中。
若使用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的區別
2.1?不同點1
?
nn.Sequential內部實現了forward函數,因此可以不用寫forward函數。而nn.ModuleList則沒有實現內部forward函數。
?
但如果Sequential是在繼承了nn.Module的類中的話,那也要forward函數了
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?不同點2
nn.Sequential可以使用OrderedDict對每層進行命名
見pytorch 學習筆記:nn.Sequential構造神經網絡_劉文巾的博客-CSDN博客
2.3?不同點3
nn.Sequential里面的模塊按照順序進行排列的,所以必須確保前一個模塊的輸出大小和下一個模塊的輸入大小是一致的。
而nn.ModuleList 并沒有定義一個網絡,它只是將不同的模塊儲存在一起,這些模塊之間并沒有什么先后順序可言。
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的pytorch学习笔记 torchnn.ModuleList的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: pytorch 笔记: torch.nn
- 下一篇: pytorch笔记 pytorch模型中