模型构造方法
- 继承Module类
- 使用继承自Module的类:Sequential、ModuleList、ModuleDict
- 继承Module类,这种方式比较灵活
1 | import torch |
- 使用Sequential,方便的搭建顺序网络,不需要手动实现forward
1 | # 自己继承Module来实现一个Sequential类 |
- 使用Module
Sequential与ModuleLst的区别在于Seq是有序的,因此相邻模块的输入输出大小确定,它在内部可以帮我们实现forward,而ModuleList的模块之间没有联系和顺序,需要自己实现forward。也就是说它们不一定都在不同的层,可能出现在同一层。并且加入到ModuleList中的参数会自动添加到网络中,一般的python list则不会。
1 | class MyModule(nn.Module): |
- ModuleDict
它的特性与ModuleList很像,无序、自动添加参数、需要手动实现forward。
1 | net = nn.ModuleDict({ |
复杂模型
复杂模型一般继承前面的Module类来自己写。
1 | class FancyMLP(nn.Module): |
嵌套调用
这些类都是继承自Module类的子类,因此可以嵌套调用它们。
1 | class NestMLP(nn.Module): |
- 输出
1 | Sequential( |
参数的访问、初始化和共享
访问
1 | import torch |
初始化
1 | for name, param in net.named_parameters(): |
共享
除了前面通过Module类创建的网络,在forward多次调用同一个层的参数是共享的外,还有一个方法是传入Sequential的模块是Module的实例 时,参数也是共享的
1 | linear = nn.Linear(1, 1, bias=False) ## 注意这是一个Module的实例 |
自定义层
- 定义一个简单层,不含参数,仅计算输入数据减去均值后的值
1 | import torch |
- 对于含模型参数的层,除了前面用Parameter一个一个添加外,还可以使用ParameterList和ParameterDict
1 | # ParameterList |
1 | # ParameterDict |
1 | net = nn.Sequential( # 自定义层也可用于构造网络 |
读写与保存
- 读写Tensor
可以直接使用save函数和load函数分别存储和读取Tensor。save使用Python的pickle实用程序将对象进行序列化,然后将序列化的对象保存到disk,使用save可以保存各种对象,包括模型、张量和字典等。而load使用pickle unpickle工具将pickle的对象文件反序列化为内存。
1 | import torch |
- 模型的保存与加载
PyTorch中,Module的可学习参数(即权重和偏差),模块模型包含在参数中(通过model.parameters()访问)。state_dict是一个从参数名称隐射到参数Tesnor的字典对象。
1 | class MLP(nn.Module): |
模型保存和加载一般有两种:
- 仅保存和加载模型参数(state_dict) 。(推荐)
- 保存和加载整个模型。
1 | # 方法一 |
以方法一为例:
1 | X = torch.randn(2, 3) |
GPU
- 查看GPU信息
1 | import torch |
- 数据转化为GPU数据
1 | x = torch.tensor([1, 2, 3]) |
- 模型转移到GPU
1 | net = nn.Linear(3, 1) |