Pytorch学习笔记(八):nn.ModuleList和nn.Sequential函数详解

相关文章

Pytorch学习笔记(一):torch.cat()模块的详解
Pytorch学习笔记(二):nn.Conv2d()函数详解
Pytorch学习笔记(三):nn.BatchNorm2d()函数详解
Pytorch学习笔记(四):nn.MaxPool2d()函数详解
Pytorch学习笔记(五):nn.AdaptiveAvgPool2d()函数详解
Pytorch学习笔记(六):view()和nn.Linear()函数详解
Pytorch学习笔记(七):F.softmax()和F.log_softmax函数详解
Pytorch学习笔记(八):nn.ModuleList和nn.Sequential函数详解

1.函数语法格式和作用

nn.ModuleList作用:
nn.ModuleList则没有顺序性要求,并且也没有实现forward()方法。为了构建网络模型。
nn.ModuleList函数语言格式:
这个直接看后面具体的代码即可
nn.Sequential作用:
nn.Sequential定义的网络中各层会按照定义的顺序进行级联,因此需要保证各层的输入和输出之间要衔接。而且里面的模块必须是按照顺序进行排列的,所以我们必须确保前一个模块的输出大小和下一个模块的输入大小是一致的,并且nn.Sequential实现了farward()方法,因此可以直接通过类似于x=self.combine(x)的方式实现forward。
nn.Sequential函数语言格式:
这个直接看后面具体的代码即可

2.参数解释

  • x指的是输入矩阵。

  • dim指的是归一化的方式,如果为0是对列做归一化,1是对行做归一化。

3.具体代码

  • nn.ModuleList
  • nn.ModuleList 并没有定义一个网络,它只是将不同的模块储存在一起,这些模块之间并没有什么先后顺序可言
  • 被调用多次的模块,是使用同一组 parameters 的,也就是它们的参数是共享的,无论之后怎么更新。例子如下,虽然在 forward 中我们用了 nn.Linear(10,10) 两次,但是它们只有一组参数。
class net3(nn.Module):
    def __init__(self):
        super(net3, self).__init__()
        self.linears = nn.ModuleList([nn.Linear(10,20), nn.Linear(20,30), nn.Linear(5,10)])
    def forward(self, x):
        x = self.linears[2](x)
        x = self.linears[0](x)
        x = self.linears[1](x) 
        return x

net = net3()
print(net)
# net3(
#   (linears): ModuleList(
#     (0): Linear(in_features=10, out_features=20, bias=True)
#     (1): Linear(in_features=20, out_features=30, bias=True)
#     (2): Linear(in_features=5, out_features=10, bias=True)
#   )
# )
input = torch.randn(32, 5)
print(net(input).shape)
# torch.Size([32, 30])
class net4(nn.Module):
    def __init__(self):
        super(net4, self).__init__()
        self.linears = nn.ModuleList([nn.Linear(5, 10), nn.Linear(10, 10)])
    def forward(self, x):
        x = self.linears[0](x)
        x = self.linears[1](x)
        x = self.linears[1](x)
        return x

net = net4()
print(net)
# net4(
#   (linears): ModuleList(
#     (0): Linear(in_features=5, out_features=10, bias=True)
#     (1): Linear(in_features=10, out_features=10, bias=True)
#   )
# )
for name, param in net.named_parameters():
    print(name, param.size())
# linears.0.weight torch.Size([10, 5])
# linears.0.bias torch.Size([10])
# linears.1.weight torch.Size([10, 10])
# linears.1.bias torch.Size([10])
  • nn.Sequential
  • 不同于 nn.ModuleList,它已经实现了内部的 forward 函数,而且里面的模块必须是按照顺序进行排列的,所以我们必须确保前一个模块的输出大小和下一个模块的输入大小是一致的,
class net5(nn.Module):
    def __init__(self):
        super(net5, self).__init__()
        self.block = nn.Sequential(nn.Conv2d(1,20,5),
                                    nn.ReLU(),
                                    nn.Conv2d(20,64,5),
                                    nn.ReLU())
    def forward(self, x):
        x = self.block(x)
        return x

net = net5()
print(net)
# net5(
#   (block): Sequential(
#     (0): Conv2d(1, 20, kernel_size=(5, 5), stride=(1, 1))
#     (1): ReLU()
#     (2): Conv2d(20, 64, kernel_size=(5, 5), stride=(1, 1))
#     (3): ReLU()
#   )
# )
pytorch 是一个高效的深度学习框架,其中nn.modulelistnn.sequential是常用的模块。这两种模块都可以用于创建深度学习网络,并且能够实现自动求导。nn.sequential 是一个有序的容器,其中每个模块按照传入的顺序依次进行计算。nn.modulelist 是一个无序的容器,其中每个模块都可以以列表的形式存储,且没有特定的计算顺序。 nn.sequential 模块的优点是简单易用,并且可以通过一行代码构建和训练网络。例如,要创建一个简单的两层全连接神经网络,可以如下代码实现: ``` model = nn.Sequential(nn.Linear(784, 64), nn.ReLU(), nn.Linear(64, 10), nn.Softmax(dim=1)) ``` 这会定义一个两个全连接层网络以及 ReLU 和softmax 激活函数,输入大小为 784(MNIST 图像大小) ,输出大小为 10(10 个数字)。 nn.modulelist 是一个更加灵活的容器,可以在其中添加任意的子模块。要使用 nn.modulelist,需要先创建一个空的 nn.modulelist,然后手动向其中添加子模块。例如,可以这样创建一个相同的两层全连接网络: ``` model = nn.ModuleList([ nn.Linear(784, 64), nn.ReLU(), nn.Linear(64, 10), nn.Softmax(dim=1) ]) ``` 需要注意的是,nn.modulelist 中的子模块顺序可能会影响计算结果,因为没有特定的训练顺序。因此,在使用 nn.modulelist 时应该尽量保证顺序的准确性。 综上所述,nn.sequentialnn.modulelist 都是常用的容器,用于组织神经网络中的子模块,它们在不同场景下具有各自的优势。在简单的前向计算中,nn.sequential 更加容易使用;在需要更好的灵活性时,nn.modulelist 可以更好地实现目标。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZZY_dl

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值