继承Module​类来构造模型

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

import torch
from torch import nn

class MLP(nn.Module):
    # 声明带有模型参数的层,这里声明了两个全连接层
    def __init__(self, **kwargs):
        # 调用MLP父类Module的构造函数来进行必要的初始化。这样在构造实例时还可以指定其他函数
        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)
)
tensor([[-0.1798, -0.2253,  0.0206, -0.1067, -0.0889,  0.1818, -0.1474,  0.1845,
         -0.1870,  0.1970],
        [-0.1843, -0.1562, -0.0090,  0.0351, -0.1538,  0.0992, -0.0883,  0.0911,
         -0.2293,  0.2360]], grad_fn=<ThAddmmBackward>)

Module​的子类

​Module​类是一个通用的部件,PyTorch还实现了继承自Module​的可以方便构建模型的类: 如Sequential​、ModuleList​和ModuleDict​等等。

Sequential​类

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

下面实现一个与Sequential​类有相同功能的MySequential​类。

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.0100, -0.2516,  0.0392, -0.1684, -0.0937,  0.2191, -0.1448,  0.0930,
          0.1228, -0.2540],
        [-0.1086, -0.1858,  0.0203, -0.2051, -0.1404,  0.2738, -0.0607,  0.0622,
          0.0817, -0.2574]], grad_fn=<ThAddmmBackward>)

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)
# net(torch.zeros(1, 784)) # 会报NotImplementedError

输出:

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

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

另外,ModuleList​不同于一般的Python的list​,加入到ModuleList​里面的所有模块的参数会被自动添加到整个网络(父模块)中,注册后,这些子模块的参数(权重和偏置)会被父模块的 .parameters()​ 方法收集,从而被优化器识别并更新。下面看一个例子对比一下。

class Module_ModuleList(nn.Module):
    def __init__(self):
        super(Module_ModuleList, self).__init__()
        self.linears = nn.ModuleList([nn.Linear(10, 10)])
  
class Module_List(nn.Module):
    def __init__(self):
        super(Module_List, self).__init__()
        self.linears = [nn.Linear(10, 10)]

net1 = Module_ModuleList()
net2 = Module_List()

print("net1:")
for p in net1.parameters():
    print(p.size())

print("net2:")
for p in net2.parameters():
    print(p)

输出:

net1:
torch.Size([10, 10])
torch.Size([10])
net2:  # 输出:空列表(参数未被注册)

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)
# net(torch.zeros(1, 784)) # 会报NotImplementedError

输出:

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

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

4.1.3 构造复杂的模型

虽然上面介绍的这些类可以使模型构造更加简单,且不需要定义forward​函数,但直接继承Module​类可以极大地拓展模型构造的灵活性。下面构造一个稍微复杂点的网络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.8432, grad_fn=<SumBackward0>)

因为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(14.4908, grad_fn=<SumBackward0>)

循之际,如星夜般的幻想。