nn.Sequential和nn.Module是PyTorch中用于構建模型的兩個模塊。
參考:https://github.com/L1aoXingyu/code-of-learn-deep-learning-with-pytorch/blob/master/chapter3_NN/nn-sequential-module.ipynb
nn.Sequential 構建序列化模塊
# 通過nn.Sequential 搭建含一個隱藏層的深度神經網絡
import torch.nn as nn
seqNet = nn.Sequential(
nn.Linear(2, 4) # 線性層 wx + b
nn.Tanh() # 激活函數 tanh
nn.Linear(4, 1)
)
seqNet # 打印網絡結構
神經網絡結構
# 可以通過索引訪問每一層及參數
w0 = seqNet[0].weight
# 通過 parameters 可得到模型的參數
param = seqNet.parameters()
nn.Module 更靈活的模型定義方式
Module 定義的模板如下:
class 網絡名字(nn.Module):
def __init__(self, 一些定義的參數): # 定義需要用的網絡層
super(網絡名字, 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. 其靈活性體現在forward中。
構建相同的神經網絡模型,代碼如下:
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() # 激活函數 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) # 實例化生成神經網絡
moduleNet # 打印網絡結構
神經網絡結構
# 可以通過名字直接訪問每一層并訪問具體參數
layer01 = moduleNet.layer1
w0 = layer01.weight
para = moduleNet.parameters()