最近在定义一个多任务网络的时候对nn.ModuleList和nn.Sequential的用法产生了疑惑,这里让我们一起来探究一下二者的用法和区别。
nn.ModuleList和nn.Sequencial的作用
先来探究一下nn.ModuleList的作用,定义一个简单的只含有全连接的网络来看一下。当不使用ModuleList只用list来定义网络中的层的时候:
import torch
import torch.nn as nn
class testNet(nn.Module):
def __init__(self):
super(testNet, self).__init__()
self.combine = []
self.combine.append(nn.Linear(100,50))
self.combine.append(nn.Linear(50,25))
net = testNet()
print(net)
可以看到结果并没有显示添加的全连接层信息。如果改成采用ModuleList:
import torch
import torch.nn as nn
class testNet(nn.Module):
def __init__(self):
super(testNet, self).__init__()
self.combine = nn.ModuleList()
sel