本次我们介绍一下Pytorch的基本类Module,Module 类是 nn 模块⾥提供的⼀个模型构造类,是所有神经⽹络模块的基类,我们可以继承它来定义我们想要的模型。下⾯继承 Module 类构造本节开头提到的多层感知机。这里定义的 MLP 类重载了 Module 类的 \_\_init\_\_ 函数和 forward 函数。它们分别⽤于创建模型参数和定义前向计算。
1、继承 MODULE 类来构造模型
class MLP(nn.Module):
# 声明带有模型参数的层,这里声明了两个全连接层
def __init__(self, **kwargs):
# 调用MLP父类Block的构造函数来进行必要的初始化。这样在构造实例时还可以指定其他函数
# 参数,如“模型参数的访问、初始化和共享”一节将介绍的模型参数params
super(MLP, self).__init__(**kwargs)
self.hidden = nn.Linear(784, 256) # 隐藏层
self.act = nn.ReLU()
self.output = nn.Linear(256, 10) # 输出层
# 定义模型的前向计算,即如何根据输入x计算返回所需要的模型输出
def forward(self, x):
a = self.act(self.hidden(x))
return self.output(a)
以上的 MLP 类中⽆须定义反向传播函数。系统将通过⾃动求梯度⽽而自动⽣成反向传播所需的 backward 函数。
我们可以实例化 MLP 类得到模型变量 net 。下⾯的代码初化 net 并传入输⼊数据 X 做⼀次前向计 算。其中, net(X) 会调用 MLP 继承自 Module 类的 \_\_call\_\_ 函数,这个函数将调用 MLP 类定义的forward 函数来完成前向计算。
X = torch.rand(2, 784)
net = MLP()
print(net)
net(X)
MLP(
(hidden): Linear(in_features=784, out_features=256, bias=True)
(act): ReLU()
(output): Linear(in_features=256, out_features=10, bias=True)
)
Out[3]:
tensor([[-0.0245, 0.1291, 0.1377, 0.0896, 0.1298, 0.1089, -0.1557, 0.1295,
0.0683, 0.1965],
[ 0.0227, -0.0887, 0.2675, 0.1480, 0.1317, -0.0312, -0.0694, 0.1058,
0.0101, 0.2468]], grad_fn=)
注意,这里并没有将 Module 类命名为 Layer (层)或者 Model (模型)之类的名字,这是因为该类是⼀个可供⾃由组建的部件。它的⼦类既可以是一个层(如PyTorch提供的 Linear 类),⼜可以是⼀ 个模型(如这里定义的 MLP 类),或者是模型的⼀个部分。我们下⾯通过两个例子来展示它的灵活性。
2、Module的子类
Module 类是⼀个通用的部件。事实上,PyTorch还实现了继承自 Module 的可以⽅便构建模型的类: 如 Sequential 、 ModuleList 和 ModuleDict 等等
2.1、Sequential 类
当模型的前向计算为简单串联各个层的计算时, Sequential 类可以通过更加简单的⽅式定义模型。这正是 Sequential 类的目的:它可以接收⼀个⼦模块的有序字典(OrderedDict)或者一系列子模块作为参数来逐⼀添加 Module 的实例,而模型的前向计算就是将这些实例按添加的顺序逐⼀计算。
下面我们实现⼀个与 Sequential 类有相同功能的 MySequential 类。这或许可以帮助读者更加清晰地理解 Sequential 类的⼯作机制
class MySequential(nn.Module):
from collections import OrderedDict
def __init__(self, *args):
super(MySequential, self).__init__()
if len(args) == 1 and isinstance(args[0], OrderedDict): # 如果传入的是一个OrderedDict
for key, module in args[0].items():
self.add_module(key, module) # add_module方法会将module添加进self._modules(一个OrderedDict)
else: # 传入的是一些Module
for idx, module in enumerate(args):
self.add_module(str(idx), module)
def forward(self, input):
# self._modules返回一个 OrderedDict,保证会按照成员添加时的顺序遍历成
for module in self._modules.values():
input = module(input)
return input
我们用 MySequential 类来实现前面描述的 MLP 类,并使用随机初始化的模型做⼀次前向计算。
net = MySequential(
nn.Linear(784, 256),
nn.ReLU(),
nn.Linear(256, 10),
)
print(net)
net(X)
MySequential(
(0): Linear(in_features=784, out_features=256, bias=True)
(1): ReLU()
(2): Linear(in_features=256, out_features=10, bias=True)
)
tensor([[-0.0472, 0.1257, -0.0043, -0.1107, 0.1425, -0.1411, -0.0128, -0.0843,
0.0725, -0.2771],
[ 0.0216, 0.0896, 0.1535, -0.1177, 0.2459, -0.1088, -0.0873, -0.0100,
0.0152, -0.3757]], grad_fn=)
2.2、ModuleList 类
ModuleList 接收⼀个⼦模块的列表作为输入,然后也可以类似List那样进⾏append和extend操作:
net = nn.ModuleList([nn.Linear(784, 256), nn.ReLU()])
net.append(nn.Linear(256, 10)) # # 类似List的append操作
print(net[-1]) # 类似List的索引访问
print(net)
Linear(in_features=256, out_features=10, bias=True)
ModuleList(
(0): Linear(in_features=784, out_features=256, bias=True)
(1): ReLU()
(2): Linear(in_features=256, out_features=10, bias=True)
)
2.3、ModuleDict 类
ModuleDict 接收⼀个⼦模块的字典作为输入, 然后也可以类似字典那样进行添加访问操作:
net = nn.ModuleDict({
'linear': nn.Linear(784, 256),
'act': nn.ReLU(),
})
net['output'] = nn.Linear(256, 10) # 添加
print(net['linear']) # 访问
print(net.output)
print(net)
Linear(in_features=784, out_features=256, bias=True)
Linear(in_features=256, out_features=10, bias=True)
ModuleDict(
(act): ReLU()
(linear): Linear(in_features=784, out_features=256, bias=True)
(output): Linear(in_features=256, out_features=10, bias=True)
)
3、构造复杂的模型
下面我们构造一个稍微复杂点的网络 FancyMLP 。在这个网络中,我们通过 get\_constant 函数创建训练中不被迭代的参数,即常数参数。在前向计算中,除了使⽤创建的常数参数外,我们还使用 Tensor 的函数和Python的控制流,并多次调⽤相同的层。
class FancyMLP(nn.Module):
def __init__(self, **kwargs):
super(FancyMLP, self).__init__(**kwargs)
self.rand_weight = torch.rand((20, 20), requires_grad=False) # 不可训练参数(常数参数)
self.linear = nn.Linear(20, 20)
def forward(self, x):
x = self.linear(x)
# 使用创建的常数参数,以及nn.functional中的relu函数和mm函数
x = nn.functional.relu(torch.mm(x, self.rand_weight.data) + 1)
# 复用全连接层。等价于两个全连接层共享参数
x = self.linear(x)
# 控制流,这里我们需要调用item函数来返回标量进行比较
while x.norm().item() > 1:
x /= 2
if x.norm().item() < 0.8:
x *= 10
return x.sum()
在这个 FancyMLP 模型中,我们使⽤了常数权重rand\_weight (注意它不是可训练模型参数)、做了矩阵乘法操作( torch.mm )并重复使⽤了相同的 Linear 层。下⾯我们来测试该模型的前向计算
X = torch.rand(2, 20)
net = FancyMLP()
print(net)
net(X)
FancyMLP(
(linear): Linear(in_features=20, out_features=20, bias=True)
)
tensor(-0.7305, grad_fn=)
因为 FancyMLP 和 Sequential 类都是 Module 类的子类,所以我们可以嵌套调⽤它们
class NestMLP(nn.Module):
def __init__(self, **kwargs):
super(NestMLP, self).__init__(**kwargs)
self.net = nn.Sequential(nn.Linear(40, 30), nn.ReLU())
def forward(self, x):
return self.net(x)
net = nn.Sequential(NestMLP(), nn.Linear(30, 20), FancyMLP())
X = torch.rand(2, 40)
print(net)
net(X)
Sequential(
(0): NestMLP(
(net): Sequential(
(0): Linear(in_features=40, out_features=30, bias=True)
(1): ReLU()
)
)
(1): Linear(in_features=30, out_features=20, bias=True)
(2): FancyMLP(
(linear): Linear(in_features=20, out_features=20, bias=True)
)
)
tensor(-4.1390, grad_fn=)
总结:
1、可以通过继承 Module 类来构造模型。
2、Sequential 、 ModuleList 、 ModuleDict 类都继承自 Module 类。
3、虽然 Sequential 等类可以使模型构造更加简单,但直接继承 Module 类可以极⼤地拓展模型构造的灵活性。