模型构造

nn.Module

nn.Module是pytorch中提供的一个类,是所有神经网络模块的基类.我们自定义的模块要继承这个基类.

import torch
from torch import nn class MLP(nn.Module):
# 声明带有模型参数的层,这里声明了两个全连接层
def __init__(self, **kwargs):
# 调用MLP父类Module的构造函数来进行必要的初始化。这样在构造实例时还可以指定其他函数
# 参数,如“模型参数的访问、初始化和共享”一节将介绍的模型参数params
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) 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)
)

Module的子类

torch中还提供了一些其他的类,方便我们构造模型.这些类也都是继承自nn.Module.

  • Sequential
  • ModuleList
  • ModuleDict

这些类的定义都位于torch/nn/modules/container.py

Sequential

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

# Example of using Sequential
model = nn.Sequential(
nn.Conv2d(1,20,5),
nn.ReLU(),
nn.Conv2d(20,64,5),
nn.ReLU()
) # Example of using Sequential with OrderedDict
model = nn.Sequential(OrderedDict([
('conv1', nn.Conv2d(1,20,5)),
('relu1', nn.ReLU()),
('conv2', nn.Conv2d(20,64,5)),
('relu2', nn.ReLU())
]))

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

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

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

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

这里注意nn.ModuleList传入的是一个python list.

nn.ModuleList([nn.Linear(10, 10)])

不要写成了

nn.ModuleList(nn.Linear(10, 10))

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

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:

可以看到net2是没有parameters的.net1是有parameters的.因为net1用的是nn.ModuleList而不是python list.

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里的所有模块的参数会被自动添加到整个网络中。

总结一下

  • 可以通过继承Module类来构造模型。
  • SequentialModuleListModuleDict类都继承自Module类。
  • Sequential不同,ModuleListModuleDict并没有定义一个完整的网络,它们只是将不同的模块存放在一起,需要自己定义forward函数。

构造复杂模型

上面介绍的Sequential使用简单,但灵活性不足.通常我们还是自定义类,继承nn.Module,去完成更复杂的模型定义和控制.

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() X = torch.rand(2, 20)
net = FancyMLP()
print(net)
print(net(X))

输出

FancyMLP(
(linear): Linear(in_features=20, out_features=20, bias=True)
)
tensor(2.0396, grad_fn=<SumBackward0>)

这里在print(net)时的输出,是和__init__函数保持一致的,比如

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)
self.relu = nn.ReLU() 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() X = torch.rand(2, 20)
net = FancyMLP()
print(net)
print(net(X))

输出

FancyMLP(
(linear): Linear(in_features=20, out_features=20, bias=True)
(relu): ReLU()
)
tensor(7.5126, grad_fn=<SumBackward0>)

尽管在forward()里并没有用到self.relu.

自定义的模型依然可以和Sequential一起使用.因为再复杂,它也还是继承自nn.Module

net = nn.Sequential(nn.Linear(30, 20),FancyMLP())

从头学pytorch(九):模型构造的更多相关文章

  1. 从头学pytorch(十九):批量归一化batch normalization

    批量归一化 论文地址:https://arxiv.org/abs/1502.03167 批量归一化基本上是现在模型的标配了. 说实在的,到今天我也没搞明白batch normalize能够使得模型训练 ...

  2. 从头学pytorch(一):数据操作

    跟着Dive-into-DL-PyTorch.pdf从头开始学pytorch,夯实基础. Tensor创建 创建未初始化的tensor import torch x = torch.empty(5,3 ...

  3. 从头学pytorch(六):权重衰减

    深度学习中常常会存在过拟合现象,比如当训练数据过少时,训练得到的模型很可能在训练集上表现非常好,但是在测试集上表现不好. 应对过拟合,可以通过数据增强,增大训练集数量.我们这里先不介绍数据增强,先从模 ...

  4. 从头学pytorch(十二):模型保存和加载

    模型读取和存储 总结下来,就是几个函数 torch.load()/torch.save() 通过python的pickle完成序列化与反序列化.完成内存<-->磁盘转换. Module.s ...

  5. 从头学pytorch(三) 线性回归

    关于什么是线性回归,不多做介绍了.可以参考我以前的博客https://www.cnblogs.com/sdu20112013/p/10186516.html 实现线性回归 分为以下几个部分: 生成数据 ...

  6. 从头学pytorch(十五):AlexNet

    AlexNet AlexNet是2012年提出的一个模型,并且赢得了ImageNet图像识别挑战赛的冠军.首次证明了由计算机自动学习到的特征可以超越手工设计的特征,对计算机视觉的研究有着极其重要的意义 ...

  7. 从头学pytorch(十一):自定义层

    自定义layer https://www.cnblogs.com/sdu20112013/p/12132786.html一文里说了怎么写自定义的模型.本篇说怎么自定义层. 分两种: 不含模型参数的la ...

  8. 从头学pytorch(二十):残差网络resnet

    残差网络ResNet resnet是何凯明大神在2015年提出的.并且获得了当年的ImageNet比赛的冠军. 残差网络具有里程碑的意义,为以后的网络设计提出了一个新的思路. googlenet的思路 ...

  9. 从头学pytorch(四) softmax回归实现

    FashionMNIST数据集共70000个样本,60000个train,10000个test.共计10种类别. 通过如下方式下载. mnist_train = torchvision.dataset ...

随机推荐

  1. SDUT-2119_数据结构实验之链表四:有序链表的归并

    数据结构实验之链表四:有序链表的归并 Time Limit: 1000 ms Memory Limit: 65536 KiB Problem Description 分别输入两个有序的整数序列(分别包 ...

  2. Mysql——ERROR 1045 (28000): Access denied for user 'root'@'localhost'

    1.修改my.ini,最后一行添加  skip-grant-tables  ,保存关闭.(win10默认安装路径:C:\ProgramData\MySQL\MySQL Server 5.7) 2.重启 ...

  3. PyODPS DataFrame 处理笛卡尔积的几种方式

    PyODPS 提供了 DataFrame API 来用类似 pandas 的接口进行大规模数据分析以及预处理,本文主要介绍如何使用 PyODPS 执行笛卡尔积的操作. 笛卡尔积最常出现的场景是两两之间 ...

  4. @loj - 2674@ 「NOI2012」美食节

    目录 @description@ @solution@ @accepted code@ @details@ @description@ CZ 市为了欢迎全国各地的同学,特地举办了一场盛大的美食节. 作 ...

  5. Linux 运算符

    布尔运算符 下表列出了常用的布尔运算符,假定变量a为10 变量b为20: 运算符  说明 举例 ! 非运算 , 表达式为true 则返回false 否则返回true  [!false] 返回true. ...

  6. behavior planning——11 create a cost function speed penalty

    A  key part of getting transitions to happen when we want  them to is the design of reasonable cost ...

  7. Springboot2 Logback mybatis 打印sql执行语句

    把这个加入到logback.xml 中就可以打印mysql的日志了 <logger name="jdbc.sqltiming" level="debug" ...

  8. input submit标签的高度和宽度与input text的差异

    <input type="text"> 时设置input的高度和border,最后元素的高度和宽度包含了border的值. <input type="s ...

  9. poj 3181 Dollar Dayz(完全背包)

    Dollar Dayz Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 5419   Accepted: 2054 Descr ...

  10. 关于scipy包的安装

    先安装好scikit-learn和numpy,从网上下载scipy的whl文件,通过pip install+安装包地址的方法安装