4.1 模型构造

让我们回顾一下在3.10节(多层感知机的简洁实现)中含单隐藏层的多层感知机的实现方法。我们首先构造Sequential实例,然后依次添加两个全连接层。其中第一层的输出大小为256,即隐藏层单元个数是256;第二层的输出大小为10,即输出层单元个数是10。我们在上一章的其他节中也使用了Sequential类构造模型。这里我们介绍另外一种基于Module类的模型构造方法:它让模型构造更加灵活。

注:其实前面我们陆陆续续已经使用了这些方法了,本节系统介绍一下。

4.1.1 继承Module类来构造模型

Module类是nn模块里提供的一个模型构造类,是所有神经网络模块的基类,我们可以继承它来定义我们想要的模型。下面继承Module类构造本节开头提到的多层感知机。这里定义的MLP类重载了Module类的__init__函数和forward函数。它们分别用于创建模型参数和定义前向计算。前向计算也即正向传播。

  1. import torch
  2. from torch import nn
  3. class MLP(nn.Module):
  4. # 声明带有模型参数的层,这里声明了两个全连接层
  5. def __init__(self, **kwargs):
  6. # 调用MLP父类Module的构造函数来进行必要的初始化。这样在构造实例时还可以指定其他函数
  7. # 参数,如“模型参数的访问、初始化和共享”一节将介绍的模型参数params
  8. super(MLP, self).__init__(**kwargs)
  9. self.hidden = nn.Linear(784, 256) # 隐藏层
  10. self.act = nn.ReLU()
  11. self.output = nn.Linear(256, 10) # 输出层
  12. # 定义模型的前向计算,即如何根据输入x计算返回所需要的模型输出
  13. def forward(self, x):
  14. a = self.act(self.hidden(x))
  15. return self.output(a)

以上的MLP类中无须定义反向传播函数。系统将通过自动求梯度而自动生成反向传播所需的backward函数。

我们可以实例化MLP类得到模型变量net。下面的代码初始化net并传入输入数据X做一次前向计算。其中,net(X)会调用MLP继承自Module类的__call__函数,这个函数将调用MLP类定义的forward函数来完成前向计算。

  1. X = torch.rand(2, 784)
  2. net = MLP()
  3. print(net)
  4. net(X)

输出:

  1. MLP(
  2. (hidden): Linear(in_features=784, out_features=256, bias=True)
  3. (act): ReLU()
  4. (output): Linear(in_features=256, out_features=10, bias=True)
  5. )
  6. tensor([[-0.1798, -0.2253, 0.0206, -0.1067, -0.0889, 0.1818, -0.1474, 0.1845,
  7. -0.1870, 0.1970],
  8. [-0.1843, -0.1562, -0.0090, 0.0351, -0.1538, 0.0992, -0.0883, 0.0911,
  9. -0.2293, 0.2360]], grad_fn=<ThAddmmBackward>)

注意,这里并没有将Module类命名为Layer(层)或者Model(模型)之类的名字,这是因为该类是一个可供自由组建的部件。它的子类既可以是一个层(如PyTorch提供的Linear类),又可以是一个模型(如这里定义的MLP类),或者是模型的一个部分。我们下面通过两个例子来展示它的灵活性。

4.1.2 Module的子类

我们刚刚提到,Module类是一个通用的部件。事实上,PyTorch还实现了继承自Module的可以方便构建模型的类: 如SequentialModuleListModuleDict等等。

4.1.2.1 Sequential类

当模型的前向计算为简单串联各个层的计算时,Sequential类可以通过更加简单的方式定义模型。这正是Sequential类的目的:它可以接收一个子模块的有序字典(OrderedDict)或者一系列子模块作为参数来逐一添加Module的实例,而模型的前向计算就是将这些实例按添加的顺序逐一计算。

下面我们实现一个与Sequential类有相同功能的MySequential类。这或许可以帮助读者更加清晰地理解Sequential类的工作机制。

  1. class MySequential(nn.Module):
  2. from collections import OrderedDict
  3. def __init__(self, *args):
  4. super(MySequential, self).__init__()
  5. if len(args) == 1 and isinstance(args[0], OrderedDict): # 如果传入的是一个OrderedDict
  6. for key, module in args[0].items():
  7. self.add_module(key, module) # add_module方法会将module添加进self._modules(一个OrderedDict)
  8. else: # 传入的是一些Module
  9. for idx, module in enumerate(args):
  10. self.add_module(str(idx), module)
  11. def forward(self, input):
  12. # self._modules返回一个 OrderedDict,保证会按照成员添加时的顺序遍历成员
  13. for module in self._modules.values():
  14. input = module(input)
  15. return input

我们用MySequential类来实现前面描述的MLP类,并使用随机初始化的模型做一次前向计算。

  1. net = MySequential(
  2. nn.Linear(784, 256),
  3. nn.ReLU(),
  4. nn.Linear(256, 10),
  5. )
  6. print(net)
  7. net(X)

输出:

  1. MySequential(
  2. (0): Linear(in_features=784, out_features=256, bias=True)
  3. (1): ReLU()
  4. (2): Linear(in_features=256, out_features=10, bias=True)
  5. )
  6. tensor([[-0.0100, -0.2516, 0.0392, -0.1684, -0.0937, 0.2191, -0.1448, 0.0930,
  7. 0.1228, -0.2540],
  8. [-0.1086, -0.1858, 0.0203, -0.2051, -0.1404, 0.2738, -0.0607, 0.0622,
  9. 0.0817, -0.2574]], grad_fn=<ThAddmmBackward>)

可以观察到这里MySequential类的使用跟3.10节(多层感知机的简洁实现)中Sequential类的使用没什么区别。

4.1.2.2 ModuleList类

ModuleList接收一个子模块的列表作为输入,然后也可以类似List那样进行append和extend操作:

  1. net = nn.ModuleList([nn.Linear(784, 256), nn.ReLU()])
  2. net.append(nn.Linear(256, 10)) # # 类似List的append操作
  3. print(net[-1]) # 类似List的索引访问
  4. print(net)
  5. # net(torch.zeros(1, 784)) # 会报NotImplementedError

输出:

  1. Linear(in_features=256, out_features=10, bias=True)
  2. ModuleList(
  3. (0): Linear(in_features=784, out_features=256, bias=True)
  4. (1): ReLU()
  5. (2): Linear(in_features=256, out_features=10, bias=True)
  6. )

既然SequentialModuleList都可以进行列表化构造网络,那二者区别是什么呢。ModuleList仅仅是一个储存各种模块的列表,这些模块之间没有联系也没有顺序(所以不用保证相邻层的输入输出维度匹配),而且没有实现forward功能需要自己实现,所以上面执行net(torch.zeros(1, 784))会报NotImplementedError;而Sequential内的模块需要按照顺序排列,要保证相邻层的输入输出大小相匹配,内部forward功能已经实现。

ModuleList的出现只是让网络定义前向传播时更加灵活,见下面官网的例子。

  1. class MyModule(nn.Module):
  2. def __init__(self):
  3. super(MyModule, self).__init__()
  4. self.linears = nn.ModuleList([nn.Linear(10, 10) for i in range(10)])
  5. def forward(self, x):
  6. # ModuleList can act as an iterable, or be indexed using ints
  7. for i, l in enumerate(self.linears):
  8. x = self.linears[i // 2](x) + l(x)
  9. return x

另外,ModuleList不同于一般的Python的list,加入到ModuleList里面的所有模块的参数会被自动添加到整个网络中,下面看一个例子对比一下。

  1. class Module_ModuleList(nn.Module):
  2. def __init__(self):
  3. super(Module_ModuleList, self).__init__()
  4. self.linears = nn.ModuleList([nn.Linear(10, 10)])
  5. class Module_List(nn.Module):
  6. def __init__(self):
  7. super(Module_List, self).__init__()
  8. self.linears = [nn.Linear(10, 10)]
  9. net1 = Module_ModuleList()
  10. net2 = Module_List()
  11. print("net1:")
  12. for p in net1.parameters():
  13. print(p.size())
  14. print("net2:")
  15. for p in net2.parameters():
  16. print(p)

输出:

  1. net1:
  2. torch.Size([10, 10])
  3. torch.Size([10])
  4. net2:

4.1.2.3 ModuleDict类

ModuleDict接收一个子模块的字典作为输入, 然后也可以类似字典那样进行添加访问操作:

  1. net = nn.ModuleDict({
  2. 'linear': nn.Linear(784, 256),
  3. 'act': nn.ReLU(),
  4. })
  5. net['output'] = nn.Linear(256, 10) # 添加
  6. print(net['linear']) # 访问
  7. print(net.output)
  8. print(net)
  9. # net(torch.zeros(1, 784)) # 会报NotImplementedError

输出:

  1. Linear(in_features=784, out_features=256, bias=True)
  2. Linear(in_features=256, out_features=10, bias=True)
  3. ModuleDict(
  4. (act): ReLU()
  5. (linear): Linear(in_features=784, out_features=256, bias=True)
  6. (output): Linear(in_features=256, out_features=10, bias=True)
  7. )

ModuleList一样,ModuleDict实例仅仅是存放了一些模块的字典,并没有定义forward函数需要自己定义。同样,ModuleDict也与Python的Dict有所不同,ModuleDict里的所有模块的参数会被自动添加到整个网络中。

4.1.3 构造复杂的模型

虽然上面介绍的这些类可以使模型构造更加简单,且不需要定义forward函数,但直接继承Module类可以极大地拓展模型构造的灵活性。下面我们构造一个稍微复杂点的网络FancyMLP。在这个网络中,我们通过get_constant函数创建训练中不被迭代的参数,即常数参数。在前向计算中,除了使用创建的常数参数外,我们还使用Tensor的函数和Python的控制流,并多次调用相同的层。

  1. class FancyMLP(nn.Module):
  2. def __init__(self, **kwargs):
  3. super(FancyMLP, self).__init__(**kwargs)
  4. self.rand_weight = torch.rand((20, 20), requires_grad=False) # 不可训练参数(常数参数)
  5. self.linear = nn.Linear(20, 20)
  6. def forward(self, x):
  7. x = self.linear(x)
  8. # 使用创建的常数参数,以及nn.functional中的relu函数和mm函数
  9. x = nn.functional.relu(torch.mm(x, self.rand_weight.data) + 1)
  10. # 复用全连接层。等价于两个全连接层共享参数
  11. x = self.linear(x)
  12. # 控制流,这里我们需要调用item函数来返回标量进行比较
  13. while x.norm().item() > 1:
  14. x /= 2
  15. if x.norm().item() < 0.8:
  16. x *= 10
  17. return x.sum()

在这个FancyMLP模型中,我们使用了常数权重rand_weight(注意它不是可训练模型参数)、做了矩阵乘法操作(torch.mm)并重复使用了相同的Linear层。下面我们来测试该模型的前向计算。

  1. X = torch.rand(2, 20)
  2. net = FancyMLP()
  3. print(net)
  4. net(X)

输出:

  1. FancyMLP(
  2. (linear): Linear(in_features=20, out_features=20, bias=True)
  3. )
  4. tensor(0.8432, grad_fn=<SumBackward0>)

因为FancyMLPSequential类都是Module类的子类,所以我们可以嵌套调用它们。

  1. class NestMLP(nn.Module):
  2. def __init__(self, **kwargs):
  3. super(NestMLP, self).__init__(**kwargs)
  4. self.net = nn.Sequential(nn.Linear(40, 30), nn.ReLU())
  5. def forward(self, x):
  6. return self.net(x)
  7. net = nn.Sequential(NestMLP(), nn.Linear(30, 20), FancyMLP())
  8. X = torch.rand(2, 40)
  9. print(net)
  10. net(X)

输出:

  1. Sequential(
  2. (0): NestMLP(
  3. (net): Sequential(
  4. (0): Linear(in_features=40, out_features=30, bias=True)
  5. (1): ReLU()
  6. )
  7. )
  8. (1): Linear(in_features=30, out_features=20, bias=True)
  9. (2): FancyMLP(
  10. (linear): Linear(in_features=20, out_features=20, bias=True)
  11. )
  12. )
  13. tensor(14.4908, grad_fn=<SumBackward0>)

小结

  • 可以通过继承Module类来构造模型。
  • SequentialModuleListModuleDict类都继承自Module类。
  • Sequential不同,ModuleListModuleDict并没有定义一个完整的网络,它们只是将不同的模块存放在一起,需要自己定义forward函数。
  • 虽然Sequential等类可以使模型构造更加简单,但直接继承Module类可以极大地拓展模型构造的灵活性。

注:本节与原书此节有一些不同,原书传送门