之前我们一直使用nn.Sequential搭建层次神经网络,可以按序添加各种输入层、隐藏层等等。除了这种模型构造方式,还有一种基于Module类的模型构造方法,教程上说非常灵活。
继承Module类构造模型
补充:python中的,kwargs
可以用多种方式调用
fun(1, 2, 3) fun(1, b=2, c=3)
d = {‘b’:2, ‘c’:3}
这里**就拍上用场了
fun(1, **d)
- **kwargs用于构造参数数量不确定的函数,kwargs实际上就是一个字典,可以通过下标来访问特定值。<a name="d3ZJp"></a># 继承module类构造模型> `Module`类是`nn`模块里提供的一个模型构造类,是所有神经网络模块的基类,我们可以继承它来定义我们想要的模型。这里定义的`MLP`类重载了`Module`类的`__init__`函数和`forward`函数。它们分别用于创建模型参数和定义前向计算。前向计算也即正向传播。```pythonimport torchfrom torch import nnclass 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)# 前向运算,系统会自动调用def forward(self, x):a = self.act(self.hidden(x))return self.output(a)
使用Module类无需定义反向传播函数,系统会自动追踪梯度。下面的代码初始化
net并传入输入数据X做一次前向计算。其中,net(X)会调用MLP继承自Module类的__call__函数,这个函数将调用MLP类定义的forward函数来完成前向计算。
x = torch.rand(2, 784)net = MLP()print(net)# 相当于将张量x输入到模型中,并获得结果print(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.0945, 0.0151, -0.0158, 0.1111, 0.0559, 0.1047, -0.0735, -0.1291,0.1714, -0.0779],[-0.1420, -0.0436, 0.0446, 0.2947, 0.0069, 0.1551, -0.0126, -0.0570,0.0593, 0.0713]], grad_fn=<AddmmBackward>)
其实,Sequential、ModuleList和ModuleDict都是继承自nn.Module基类。
Sequential类
Sequential接收一个子模块的有序字典(OrderedDict)或者一系列子模块作为参数来逐一添加Module的实例,而模型的前向计算就是将这些实例按添加的顺序逐一计算。
教程给出了一个模拟Sequential工作机制的类,以便理解。
class MySequential(nn.Module):from collections import OrderedDictdef __init__(self, *args):super(MySequential, self).__init__()if len(args) == 1 and isinstance(args[0], OrderedDict): # 如果传入的是一个OrderedDictfor key, module in args[0].items():self.add_module(key, module) # add_module方法会将module添加进self._modules(一个OrderedDict)else: # 传入的是一些Modulefor 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
它的构造函数已经说明了它既可以接受字典形式的参数传入,也可以接受一些module对象的传入。至于前向传播,那就根据添加顺序依次作为输入层隐藏层输出层进行计算。
ModuleList类
ModuleList接受一个列表作为参数初始化,可以像列表一样进行append以及extend操作。它与Sequential的区别在于子模块列表是无序的。直接调用net(tensor)会报错。官网说可以让前向传播的定义更加灵活,但我好像暂时没想到什么可以用的地方。
net = nn.ModuleList([nn.Linear(784, 256), nn.ReLU()])net.append(nn.Linear(256, 10))print(net[-1])print(net)# net(torch.zeros(1, 784)) # 会报NotImplementedError
添加到ModuleList中的模块,参数会自动添加到网络中。观察下方使用ModuleList构建的网络层以及不使用ModuleList构建的网络层,发现只有使用ModuleList构建的网络能够感知到list中的参数。使用python自带list则无此效果。
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, ABC):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类
构造函数接受一个字典作为输入,但层与层之间也无序列关系,需要自行定义forward函数。也相当于是一个弱智版Sequential类。用它构建模型有一个方便的地方,就是可以使用字符串下标快速添加网络层。与ModuleList相仿,添加到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
构造复杂模型
其中,rand_weight是不可训练参数,设置追踪梯度为False
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 /= 2if x.norm().item() < 0.8:x *= 10return x.sum()X = torch.rand(2, 20)net = FancyMLP()print(net)print(net(X))结果:FancyMLP((linear): Linear(in_features=20, out_features=20, bias=True))tensor(-1.3540, grad_fn=<SumBackward0>)
网络可呈嵌套结构
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(0.0965, grad_fn=<SumBackward0>)
