7.3.1 自定义模型
在神经网络框架中,由多个层组成的组件称之为 模块(Module)。
在PyTorch中模型就是一个Module,各网络层、模块也是Module。Module是所有神经网络的基类。
在定义一个Module时,我们需要继承torch.nn.Module并主要实现两个方法:
- __init__:定义网络各层的结构,并初始化参数。
- forward:根据输入进行前向传播,并返回输出。计算其输出关于输入的梯度,可通过其反向传播函数进行访问(通常自动发生)。forward方法是每次调用的具体实现。
接下来使用PyTorch实现下图的神经网络:
![图片[1]-7.3 搭建神经网络-大赛人网](https://www.dsrw.com/wp-content/uploads/2026/11/image-309.png)
第1个隐藏层:使用Xavier正态分布初始化权重,激活函数使用Tanh。
第2个隐藏层:使用He正态分布初始化权重,激活函数使用ReLU。
输出层:按默认方式初始化,激活函数使用Softmax。
import torch
import torch.nn as nn
class Model(nn.Module):
# 初始化
def __init__(self):
super(Model, self).__init__() # 调用父类初始化
self.linear1 = nn.Linear(3, 4) # 第1个隐藏层,3个输入,4个输出
nn.init.xavier_normal_(self.linear1.weight) # 初始化权重参数
self.linear2 = nn.Linear(4, 4) # 第2个隐藏层,4个输入,4个输出
nn.init.kaiming_normal_(self.linear2.weight) # 初始化权重参数
self.out = nn.Linear(4, 2) # 输出层,4个输入,2个输出,默认使用He均匀分布初始化
# 前向传播
def forward(self, x):
x = self.linear1(x) # 经过第1个隐藏层
x = torch.tanh(x) # 激活函数
x = self.linear2(x) # 经过第2个隐藏层
x = torch.relu(x) # 激活函数
x = self.out(x) # 经过输出层
x = torch.softmax(x, dim=1) # 激活函数
return x
model = Model()
output = model(torch.randn(10, 3))
print("输出:\n", output)
print()
# 使用named_parameters()查看各层参数
print("模型参数:")
for name, param in model.named_parameters():
print(name, param)
print()
# 使用state_dict()查看各层参数
print("模型参数:\n", model.state_dict())
7.3.2 查看模型结构和参数数量
可使用torchsummary.summary来查看模型结构与参数数量。需要先安装torchsummary库:pip install torchsummary。
from torchsummary import summary
# input_size:特征数,batch_size:样本数
summary(model, input_size=(3,), batch_size=10, device="cpu")
![图片[2]-7.3 搭建神经网络-大赛人网](https://www.dsrw.com/wp-content/uploads/2026/11/image-310.png)
![图片[3]-7.3 搭建神经网络-大赛人网](https://www.dsrw.com/wp-content/uploads/2026/11/image-311.png)
7.3.3 使用Sequential构建模型
可以通过torch.nn.Sequential来构建模型,将各层按顺序传入。
# 构建模型
model = nn.Sequential(
nn.Linear(3, 4),
nn.Tanh(),
nn.Linear(4, 4),
nn.ReLU(),
nn.Linear(4, 2),
nn.Softmax(dim=1),
)
# 初始化参数
def init_weights(m):
# 对Linear层进行初始化
if type(m) == nn.Linear:
nn.init.xavier_uniform_(m.weight)
m.bias.data.fill_(0.01)
model.apply(init_weights) # apply会遍历所有子模块并依次调用函数
output = model(torch.randn(10, 3))
print("输出:\n", output)
Sequential类使模型构造变得简单,不必自定义类就可以组合新的架构。然而并不是所有的架构都是简单的顺序架构,当需要更强的灵活性时还是需要自定义模型。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END















请登录后查看评论内容