torch.nn.Sequential()

官网解释

一个顺序容器。每个模块将被按顺序添加到其中。Sequential 的 forward() 方法接受任何输入并将其转发到它的第一个模块。之后第一个模块输出的值将被第二个模块接收作为输入,以此类推直到最后一个模块的输出。

与手动调用一系列模块相比,Sequential 提供的价值在于它允许将整个容器视为单个模块,这样对 Sequential 执行转换就会应用于它存储的每个模块(每个模块都是 Sequential 的已注册子模块)。

Sequential 和 torch.nn.ModuleList 有什么区别? ModuleList 正是它听起来的样子——一个用于存储 Module 的列表!另一方面,Sequential 中的层以级联方式连接。

基本使用

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

append

model.append(nn.Module)

如何选择nn.Sequential和nn.Module

nn.Module是 PyTorch 中所有神经网络模块的基类。nn.Sequential 是其子类

创建新的神经网络时,通常会创建一个继承于nn.Module新类,并定义两个办法:__ init __() 和 forward() ,forward()前向传播函数表明你是如何使用 init() 函数中定义的神经网络的层

模块的示例:

class model(nn.Module):
    def __init__(self):
        super().__init__()
        
        self.fc1 = nn.Linear(10, 4)
        self.fc2 = nn.Linear(4, 2)

    def forward(self, x)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        return x

如果定义的模型是按顺序调用的,那么使用nn.Sequential是更好的选择。那么可以将上面的例子稍微改一下:

class model(nn.Sequential):
    def __init__(self):
        super().__init__(
           nn.Linear(10, 4),
           nn.ReLU(),
           nn.Linear(4, 2),
           nn.ReLU())

这个就和我们使用的nn.Sequential很像了,所以用nn.Sequential可以将其表示为:

model = Sequential(
   nn.Linear(10, 4),
   nn.ReLU(),
   nn.Linear(4, 2),
   nn.Linear())

nn.Sequential是快速实现顺序模块,这样你就不需要编写前向定义,因为这些层是在输出上顺序调用的.

在一些复杂的模块,可以使用nn.Sequential构成我们的子模块,然后使用nn.Module将其组合起来。

posted @ 2022-08-12 22:34  Zongxi_giegie  阅读(572)  评论(0)    收藏  举报