2020-02-27 nn.sequential與nn.module

nn.Sequential和nn.Module是PyTorch中用于構(gòu)建模型的兩個模塊。
參考:https://github.com/L1aoXingyu/code-of-learn-deep-learning-with-pytorch/blob/master/chapter3_NN/nn-sequential-module.ipynb

nn.Sequential 構(gòu)建序列化模塊

# 通過nn.Sequential 搭建含一個隱藏層的深度神經(jīng)網(wǎng)絡(luò)
import torch.nn as nn
seqNet = nn.Sequential(
  nn.Linear(2, 4) # 線性層 wx + b
  nn.Tanh() # 激活函數(shù) tanh
  nn.Linear(4, 1)
)
seqNet # 打印網(wǎng)絡(luò)結(jié)構(gòu)
神經(jīng)網(wǎng)絡(luò)結(jié)構(gòu)
# 可以通過索引訪問每一層及參數(shù)
w0 = seqNet[0].weight
# 通過 parameters 可得到模型的參數(shù)
param = seqNet.parameters()

nn.Module 更靈活的模型定義方式

Module 定義的模板如下:

class 網(wǎng)絡(luò)名字(nn.Module):
    def __init__(self, 一些定義的參數(shù)): # 定義需要用的網(wǎng)絡(luò)層
        super(網(wǎng)絡(luò)名字, self).__init__()
        self.layer1 = nn.Linear(num_input, num_hidden)
        self.layer2 = nn.Sequential(...)
        ...
        
        
    def forward(self, x): # 定義前向傳播
        x1 = self.layer1(x)
        x2 = self.layer2(x)
        x = x1 + x2
        ...
        return x
  • 注: 1. Module里可以使用Sequential;2. 其靈活性體現(xiàn)在forward中。

構(gòu)建相同的神經(jīng)網(wǎng)絡(luò)模型,代碼如下:

class module_net(nn.Module):
    def __init__(self, num_input, num_hidden, num_output):
        super(module_net, self).__init__()
        self.layer1 = nn.Linear(num_input, num_hidden)
        self.layer2 = nn.Tanh()  # 激活函數(shù) tanh
        self.layer3 = nn.Linear(num_hidden, num_output)
        
    def forward(self, x):
        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        return x
moduleNet = module_net(2, 4, 1) # 實(shí)例化生成神經(jīng)網(wǎng)絡(luò)
moduleNet # 打印網(wǎng)絡(luò)結(jié)構(gòu)
神經(jīng)網(wǎng)絡(luò)結(jié)構(gòu)
# 可以通過名字直接訪問每一層并訪問具體參數(shù)
layer01 = moduleNet.layer1
w0 = layer01.weight
para = moduleNet.parameters()
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容