初识nn.Sequential()

发布于:2022-07-27 ⋅ 阅读:(374) ⋅ 点赞:(0)

问题

李沐动手学深度学习-Softmax的简洁实现中遇到nn.Sequential不理解

 先百度:

nn.Sequential()_一颗磐石的博客-CSDN博客_nn.sequential

后通过help(nn.Sequential)

Help on class Sequential in module torch.nn.modules.container:

class Sequential(torch.nn.modules.module.Module)
 |  Sequential(*args)
 |  
 |  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.
 |  


个人理解为:Sequential是一个连续容器,会按照传入的参数顺序的进行存放,并且第一个模型的输出会作为第二个模型的输出,依次类推,最后输出的是最后一个模型的输出。


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

   第一个例子:说明参数通过 Conv2d后产生输出,作为RELU的输入,第一个RELU的输出作为第二个Conv2d的输入,之后输出再给第二个RELU,最后输出为第二个RELU的输出

   第二个例子的实现效果与第一个相同,但不理解OrderedDict,遇到再解决

有错误请指正!!!

有错误请指正!!!

有错误请指正!!!


网站公告

今日签到

点亮在社区的每一天
去签到