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()