之前我们一直使用nn.Sequential搭建层次神经网络,可以按序添加各种输入层、隐藏层等等。除了这种模型构造方式,还有一种基于Module类的模型构造方法,教程上说非常灵活。

继承Module类构造模型

补充:python中的kwargs

  • **用于将字典类型变量作为函数参数传入 ```python

    定义一个普通的带有3个参数的函数

    def fun(a, b, c): print a, b, c

可以用多种方式调用

fun(1, 2, 3) fun(1, b=2, c=3)

d = {‘b’:2, ‘c’:3}

这里**就拍上用场了

fun(1, **d)

  1. - **kwargs用于构造参数数量不确定的函数,kwargs实际上就是一个字典,可以通过下标来访问特定值。
  2. <a name="d3ZJp"></a>
  3. # 继承module类构造模型
  4. > `Module`类是`nn`模块里提供的一个模型构造类,是所有神经网络模块的基类,我们可以继承它来定义我们想要的模型。这里定义的`MLP`类重载了`Module`类的`__init__`函数和`forward`函数。它们分别用于创建模型参数和定义前向计算。前向计算也即正向传播。
  5. ```python
  6. import torch
  7. from torch import nn
  8. class MLP(nn.Module):
  9. # 声明带有模型参数的层,声明了两个全连接层
  10. def __init__(self, **kwargs):
  11. # 调用MLP父类Module的构造函数来进行必要的初始化
  12. super(MLP, self).__init__(**kwargs)
  13. self.hidden = nn.Linear(784, 256)
  14. self.act = nn.ReLU()
  15. self.output = nn.Linear(256, 10)
  16. # 前向运算,系统会自动调用
  17. def forward(self, x):
  18. a = self.act(self.hidden(x))
  19. return self.output(a)

使用Module类无需定义反向传播函数,系统会自动追踪梯度。下面的代码初始化net并传入输入数据X做一次前向计算。其中,net(X)会调用MLP继承自Module类的__call__函数,这个函数将调用MLP类定义的forward函数来完成前向计算。

  1. x = torch.rand(2, 784)
  2. net = MLP()
  3. print(net)
  4. # 相当于将张量x输入到模型中,并获得结果
  5. print(net(x))
  6. 结果:
  7. MLP(
  8. (hidden): Linear(in_features=784, out_features=256, bias=True)
  9. (act): ReLU()
  10. (output): Linear(in_features=256, out_features=10, bias=True)
  11. )
  12. tensor([[-0.0945, 0.0151, -0.0158, 0.1111, 0.0559, 0.1047, -0.0735, -0.1291,
  13. 0.1714, -0.0779],
  14. [-0.1420, -0.0436, 0.0446, 0.2947, 0.0069, 0.1551, -0.0126, -0.0570,
  15. 0.0593, 0.0713]], grad_fn=<AddmmBackward>)

其实,Sequential、ModuleListModuleDict都是继承自nn.Module基类。

Sequential类

Sequential接收一个子模块的有序字典(OrderedDict)或者一系列子模块作为参数来逐一添加Module的实例,而模型的前向计算就是将这些实例按添加的顺序逐一计算。
教程给出了一个模拟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

它的构造函数已经说明了它既可以接受字典形式的参数传入,也可以接受一些module对象的传入。至于前向传播,那就根据添加顺序依次作为输入层隐藏层输出层进行计算。

ModuleList类

ModuleList接受一个列表作为参数初始化,可以像列表一样进行append以及extend操作。它与Sequential的区别在于子模块列表是无序的。直接调用net(tensor)会报错。官网说可以让前向传播的定义更加灵活,但我好像暂时没想到什么可以用的地方。

  1. net = nn.ModuleList([nn.Linear(784, 256), nn.ReLU()])
  2. net.append(nn.Linear(256, 10))
  3. print(net[-1])
  4. print(net)
  5. # net(torch.zeros(1, 784)) # 会报NotImplementedError

添加到ModuleList中的模块,参数会自动添加到网络中。观察下方使用ModuleList构建的网络层以及不使用ModuleList构建的网络层,发现只有使用ModuleList构建的网络能够感知到list中的参数。使用python自带list则无此效果。

  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, ABC):
  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)
  17. 结果:
  18. net1:
  19. torch.Size([10, 10])
  20. torch.Size([10])
  21. net2:

ModuleDict类

构造函数接受一个字典作为输入,但层与层之间也无序列关系,需要自行定义forward函数。也相当于是一个弱智版Sequential类。用它构建模型有一个方便的地方,就是可以使用字符串下标快速添加网络层。与ModuleList相仿,添加到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

构造复杂模型

其中,rand_weight是不可训练参数,设置追踪梯度为False

  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()
  18. X = torch.rand(2, 20)
  19. net = FancyMLP()
  20. print(net)
  21. print(net(X))
  22. 结果:
  23. FancyMLP(
  24. (linear): Linear(in_features=20, out_features=20, bias=True)
  25. )
  26. tensor(-1.3540, grad_fn=<SumBackward0>)

网络可呈嵌套结构

  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)
  11. 结果:
  12. Sequential(
  13. (0): NestMLP(
  14. (net): Sequential(
  15. (0): Linear(in_features=40, out_features=30, bias=True)
  16. (1): ReLU()
  17. )
  18. )
  19. (1): Linear(in_features=30, out_features=20, bias=True)
  20. (2): FancyMLP(
  21. (linear): Linear(in_features=20, out_features=20, bias=True)
  22. )
  23. )
  24. tensor(0.0965, grad_fn=<SumBackward0>)