4.1 模型构造

  1. import torch
  2. from torch import nn
  3. print(torch.__version__)
  1. 1.1.0

4.1.1 继承 Module 类来构造模型

Moduletorch.nn 模块提供的一个模型构造类,是所有神经网络模块的基类

  1. class MLP(nn.Module):
  2. # 声明带有模型参数的层,这里声明了两个全连接层
  3. def __init__(self, **kwargs):
  4. # 调用MLP父类Block的构造函数来进行必要的初始化。这样在构造实例时还可以指定其他函数参数
  5. super(MLP, self).__init__(**kwargs)
  6. self.hidden = nn.Linear(784, 256) # 隐藏层
  7. self.act = nn.ReLU()
  8. self.output = nn.Linear(256, 10) # 输出层
  9. # 定义模型的前向计算,即如何根据输入x计算返回所需要的模型输出
  10. def forward(self, x):
  11. a = self.act(self.hidden(x))
  12. return self.output(a)
  1. X = torch.rand(2, 784)
  2. net = MLP()
  3. print(net)
  4. net(X)
  5. """
  6. MLP(
  7. (hidden): Linear(in_features=784, out_features=256, bias=True)
  8. (act): ReLU()
  9. (output): Linear(in_features=256, out_features=10, bias=True)
  10. )
  11. tensor([[ 0.0234, -0.2646, -0.1168, -0.2127, 0.0884, -0.0456, 0.0811, 0.0297,
  12. 0.2032, 0.1364],
  13. [ 0.1479, -0.1545, -0.0265, -0.2119, -0.0543, -0.0086, 0.0902, -0.1017,
  14. 0.1504, 0.1144]], grad_fn=<AddmmBackward>)
  15. """

4.1.2 Module 的子类

4.1.2.1 Sequential

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. # key 是这个模块的名称
  8. # module 是模块的实现方法
  9. self.add_module(key, module) # add_module方法会将module添加进self._modules(一个OrderedDict)
  10. else: # 传入的是一些Module
  11. for idx, module in enumerate(args):
  12. self.add_module(str(idx), module)
  13. def forward(self, input):
  14. # self._modules返回一个 OrderedDict,保证会按照成员添加时的顺序遍历成
  15. for module in self._modules.values():
  16. input = module(input)
  17. return input
  1. net = MySequential(
  2. nn.Linear(784, 256),
  3. nn.ReLU(),
  4. nn.Linear(256, 10),
  5. )
  6. print(net)
  7. net(X)
  8. # 输出
  9. """
  10. MySequential(
  11. (0): Linear(in_features=784, out_features=256, bias=True)
  12. (1): ReLU()
  13. (2): Linear(in_features=256, out_features=10, bias=True)
  14. )
  15. tensor([[ 0.1273, 0.1642, -0.1060, 0.1401, 0.0609, -0.0199, -0.0140, -0.0588,
  16. 0.1765, -0.1296],
  17. [ 0.0267, 0.1670, -0.0626, 0.0744, 0.0574, 0.0413, 0.1313, -0.1479,
  18. 0.0932, -0.0615]], grad_fn=<AddmmBackward>)
  19. """
  1. from collections import OrderedDict
  2. net = MySequential(
  3. OrderedDict([("Linear_1", nn.Linear(784, 256)),
  4. ("relu_1", nn.ReLU()),
  5. ("Linear_2", nn.Linear(256, 10))])
  6. )
  7. print(net)
  8. """
  9. MySequential(
  10. (Linear_1): Linear(in_features=784, out_features=256, bias=True)
  11. (relu_1): ReLU()
  12. (Linear_2): Linear(in_features=256, out_features=10, bias=True)
  13. )
  14. """

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
  6. """
  7. Linear(in_features=256, out_features=10, bias=True)
  8. ModuleList(
  9. (0): Linear(in_features=784, out_features=256, bias=True)
  10. (1): ReLU()
  11. (2): Linear(in_features=256, out_features=10, bias=True)
  12. )
  13. """
  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
  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)
  17. """
  18. net1:
  19. torch.Size([10, 10])
  20. torch.Size([10])
  21. net2:
  22. """

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
  10. """
  11. Linear(in_features=784, out_features=256, bias=True)
  12. Linear(in_features=256, out_features=10, bias=True)
  13. ModuleDict(
  14. (act): ReLU()
  15. (linear): Linear(in_features=784, out_features=256, bias=True)
  16. (output): Linear(in_features=256, out_features=10, bias=True)
  17. )
  18. """

4.1.3 构造复杂的模型

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

  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()
  1. X = torch.rand(2, 20)
  2. net = FancyMLP()
  3. print(net)
  4. net(X)
  5. """
  6. FancyMLP(
  7. (linear): Linear(in_features=20, out_features=20, bias=True)
  8. )
  9. tensor(0.8907, grad_fn=<SumBackward0>)
  10. """
  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.4605, grad_fn=<SumBackward0>)
  25. """