PyTorch模型定义
Posted 沧夜2021
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PyTorch模型定义相关的知识,希望对你有一定的参考价值。
PyTorch模型定义
文章目录
1. 前言
好久没更新了,2022年也过去快一半了,更文量还是不如前几年。近期会尝试加快更新的进度。
本篇文章的更新内容是PyTorch模型的定义。
2. PyTorch模型定义的方式
2.1. Sequential
Sequential 类可以通过更加简单的方式定义模型。它可以接收一个子模块的有序字典(OrderedDict) 或者一系列子模块作为参数来逐一添加 Module 的实例,⽽模型的前向计算就是将这些实例按添加的顺序逐⼀计算
Sequential定义源码:
torch.nn.modules.container — PyTorch 1.11.0 documentation
class Sequential(Module):
r"""A sequential container.
Modules will be added to it in the order they are passed in the
constructor. Alternatively, an ``OrderedDict`` of modules can be
passed in. The ``forward()`` method of ``Sequential`` accepts any
input and forwards it to the first module it contains. It then
"chains" outputs to inputs sequentially for each subsequent module,
finally returning the output of the last module.
The value a ``Sequential`` provides over manually calling a sequence
of modules is that it allows treating the whole container as a
single module, such that performing a transformation on the
``Sequential`` applies to each of the modules it stores (which are
each a registered submodule of the ``Sequential``).
What's the difference between a ``Sequential`` and a
:class:`torch.nn.ModuleList`? A ``ModuleList`` is exactly what it
sounds like--a list for storing ``Module`` s! On the other hand,
the layers in a ``Sequential`` are connected in a cascading way.
Example::
# Using Sequential to create a small model. When `model` is run,
# input will first be passed to `Conv2d(1,20,5)`. The output of
# `Conv2d(1,20,5)` will be used as the input to the first
# `ReLU`; the output of the first `ReLU` will become the input
# for `Conv2d(20,64,5)`. Finally, the output of
# `Conv2d(20,64,5)` will be used as input to the second `ReLU`
model = nn.Sequential(
nn.Conv2d(1,20,5),
nn.ReLU(),
nn.Conv2d(20,64,5),
nn.ReLU()
)
# Using Sequential with OrderedDict. This is functionally the
# same as the above code
model = nn.Sequential(OrderedDict([
('conv1', nn.Conv2d(1,20,5)),
('relu1', nn.ReLU()),
('conv2', nn.Conv2d(20,64,5)),
('relu2', nn.ReLU())
]))
"""
_modules: Dict[str, Module] # type: ignore[assignment]
@overload
def __init__(self, *args: Module) -> None:
...
@overload
def __init__(self, arg: 'OrderedDict[str, Module]') -> None:
...
def __init__(self, *args):
super(Sequential, self).__init__()
if len(args) == 1 and isinstance(args[0], OrderedDict):
for key, module in args[0].items():
self.add_module(key, module)
else:
for idx, module in enumerate(args):
self.add_module(str(idx), module)
以上是节选的源码。
重点需要看的代码区域是:
def __init__(self, *args):
super(Sequential, self).__init__()
if len(args) == 1 and isinstance(args[0], OrderedDict):
for key, module in args[0].items():
self.add_module(key, module)
else:
for idx, module in enumerate(args):
self.add_module(str(idx), module)
由python基础知识可以知道,*args
代表输入的参数可以是列表
所以,这个构造函数中的if len(args) == 1 and isinstance(args[0], OrderedDict):
用来判断输入的参数是不是一个列表:
第一个判断条件是args
的长度是否为1
第二个判断条件是isinstance(args[0], OrderedDict)
,判断传入的是不是一个OrderedDict
再次:
如果不是以上的情况,那么传入的就是一些Module,接着继续处理。
使用Sequential来定义模型。只需要将模型的层按序排列起来即可,根据层名的不同,排列的时候有两种方式:
2.1.1 使用OrderedDict
对应源码if len(args) == 1 and isinstance(args[0], OrderedDict):
判断语句为真。
import collection
import torch.nn as nn
net2 = nn.Sequential(collections.OrderedDict([
('fc1', nn.Linear(784, 256)),
('relu1', nn.ReLU()),
('fc2', nn.Linear(256, 10))
]))
print(net2)
使用Sequential定义模型的好处在于简单、易读,同时使用Sequential定义的模型不需要再写forward,因为顺序已经定义好了。但使用Sequential也会使得模型定义丧失灵活性,比如需要在模型中间加入一个外部输入时就不适合用Sequential的方式实现。使用时需根据实际需求加以选择。
2.1.2 直接排列
对应源码if len(args) == 1 and isinstance(args[0], OrderedDict):
判断语句为假,进入else
语句部分
import torch.nn as nn
net = nn.Sequential(
nn.Linear(784, 256),
nn.ReLU(),
nn.Linear(256, 10),
)
print(net)
2.2. ModuleList
2.3. ModuleDict
参考资料
[5.1 PyTorch模型定义的方式 — 深入浅出PyTorch (datawhalechina.github.io)](https://datawhalechina.github.io/thorough-pytorch/第五章/5.1 PyTorch模型定义的方式.html#sequential)
以上是关于PyTorch模型定义的主要内容,如果未能解决你的问题,请参考以下文章