Pytorch中nn.ModuleList 和 nn.Sequential的联系和区别

我的小程序:

待办计划:在不确定中前行
随笔日记:祭那些逝去的时光

首先,nn.ModuleList 和 nn.Sequential都是用来封装多个层。

区别在于:

nn.Sequential有forward()方法,如:

nn.Sequential allows you to build a neural net by specifying sequentially the building blocks (nn.Module's) of that net.

simple_cnn = nn.Sequential(
      nn.Conv2d(3, 32, kernel_size=7, stride=2),
      nn.ReLU(inplace=True),
      Flatten(), 
      nn.Linear(5408, 10),
     )
y = simple_cnn(x)#可直接调用nn.Sequential的faward()方法

实例化一个nn.Sequential的对象simple_cnn,可直接调用simple_cnn(x),调用的就是nn.Sequential的forward()方法,这样会把nn.Sequential里的所有层都forward(),一步到位。

而nn.ModuleList仅仅类似于pytho中的list类型,只是将一系列层装入列表,并没有forward()方法,如定义自己的一个网络:

nn.ModuleList is just like a Python list. It was designed to store any desired number of nn.Module's. It may be useful, for instance, if you want to design a neural network whose number of layers is passed as input:

class LinearNet(nn.Module):
 def __init__(self, input_size, num_layers, layers_size, output_size):
   super(LinearNet, self).__init__()
 
   self.linears = nn.ModuleList([nn.Linear(input_size, layers_size)])
   self.linears.extend([nn.Linear(layers_size, layers_size) for i in range(1, self.num_layers-1)])
   self.linears.append(nn.Linear(layers_size, output_size)

可以看到nn.ModuleList有python list中的extend,append等方法。因为nn.ModuleList没有forward()方法,所以装入nn.ModuleList的层需要自己循环调用forward(),当然,这样有了更多的灵活性,可以在每一层的输入输出中做一些自己的处理。如:

#self._blocks是一个nn.ModuleList
for idx, block in enumerate(self._blocks):
     drop_connect_rate = self._global_params.drop_connect_rate
     if drop_connect_rate:
         drop_connect_rate *= float(idx) / len(self._blocks)
     x = block(x, drop_connect_rate=drop_connect_rate)

nn.Sequential的优点是可以一步到位froward,方便高效,但缺少灵活性;nn.ModuleList的优点是灵活性高,但需要手动forward。各有自己适用的场景。

虽然nn.ModuleList就是一个list的功能,但不能用python中的list代替nn.ModuleList,因为pytorch不能识别放在python list中的模型变量。

In nn.Sequential, the nn.Module's stored inside are connected in a cascaded way. For instance, in the example that I gave, I define a neural network that receives as input an image with 3 channels and outputs 10 neurons. That network is composed by the following blocks, in the following order: Conv2D -> ReLU -> Linear layer. Moreover, an object of type nn.Sequential has a forward() method, so if I have an input image x I can directly call y = simple_cnn(x) to obtain the scores for x. When you define an nn.Sequential you must be careful to make sure that the output size of a block matches the input size of the following block. Basically, it behaves just like a nn.Module

On the other hand, nn.ModuleList does not have a forward() method, because it does not define any neural network, that is, there is no connection between each of the nn.Module's that it stores. You may use it to store nn.Module's, just like you use Python lists to store other types of objects (integers, strings, etc). The advantage of using nn.ModuleList's instead of using conventional Python lists to store nn.Module's is that Pytorch is “aware” of the existence of the nn.Module's inside an nn.ModuleList, which is not the case for Python lists. If you want to understand exactly what I mean, just try to redefine my class LinearNet using a Python list instead of a nn.ModuleList and train it. When defining the optimizer() for that net, you'll get an error saying that your model has no parameters, because PyTorch does not see the parameters of the layers stored in a Python list. If you use a nn.ModuleList instead, you'll get no error.

待办计划:在不确定中前行
随笔日记:祭那些逝去的时光

参考博文:https://www.jb51.net/article/167900.htm

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
对于计算机专业的学生而言,参加各类比赛能够带来多方面的益处,具体包括但不限于以下几点: 技能提升: 参与比赛促使学生深入学习和掌握计算机领域的专业知识与技能,如编程语言、算法设计、软件工程、网络安全等。 比赛通常涉及实际问题的解决,有助于将理论知识应用于实践,增强问题解决能力。 实践经验: 大多数比赛都要求参赛者设计并实现解决方案,这提供了宝贵的动手操作机会,有助于积累项目经验。 实践经验对于计算机专业的学生尤为重要,因为雇主往往更青睐有实际项目背景的候选人。 团队合作: 许多比赛鼓励团队协作,这有助于培养学生的团队精神、沟通技巧和领导能力。 团队合作还能促进学生之间的知识共享和思维碰撞,有助于形成更全面的解决方案。 职业发展: 获奖经历可以显著增强简历的吸引力,为求职或继续深造提供有力支持。 某些比赛可能直接与企业合作,提供实习、工作机会或奖学金,为学生的职业生涯打开更多门路。 网络拓展: 比赛是结识同行业人才的好机会,可以帮助学生建立行业联系,这对于未来的职业发展非常重要。 奖金与荣誉: 许多比赛提供奖金或奖品,这不仅能给予学生经济上的奖励,还能增强其成就感和自信心。 荣誉证书或奖状可以证明学生的成就,对个人品牌建设有积极作用。 创新与研究: 参加比赛可以激发学生的创新思维,推动科研项目的开展,有时甚至能促成学术论文的发表。 个人成长: 在准备和参加比赛的过程,学生将面临压力与挑战,这有助于培养良好的心理素质和抗压能力。 自我挑战和克服困难的经历对个人成长有着深远的影响。 综上所述,参加计算机领域的比赛对于学生来说是一个全面发展的平台,不仅可以提升专业技能,还能增强团队协作、沟通、解决问题的能力,并为未来的职业生涯奠定坚实的基础。
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 可以更好地实现目标。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值