为什么在 pyTorch 中列出模型组件没有用?

Why listing model components in pyTorch is not useful?

我正在尝试创建具有 N 层的前馈神经网络 所以想法是假设如果我想要 2 个输入 3 个隐藏和 2 个输出比我将 [2,3,2] 传递给神经网络 class 并且神经网络模型将被创建所以如果我想要 [100,1000, 1000,2] 在这种情况下,100 是输入,两个隐藏层每个包含 1000 个神经元和 2 个输出,所以我想要完全连接的神经网络,我只想传递包含每层神经元数量的列表。 为此,我编写了以下代码

class FeedforwardNeuralNetModel(nn.Module):
    def __init__(self, layers):
        super(FeedforwardNeuralNetModel, self).__init__()
        self.fc=[]
        self.sigmoid=[]
        self.activationValue = []
        self.layers = layers
        for i in range(len(layers)-1):
            self.fc.append(nn.Linear(layers[i],layers[i+1]))
            self.sigmoid.append(nn.Sigmoid())

    def forward(self, x):
        out=x
        for i in range(len(self.fc)):
            out=self.fc[i](out)
            out = self.sigmoid[i](out)
        return out    

当我尝试使用它时,我发现它有点空模型

model=FeedforwardNeuralNetModel([3,5,10,2])

print(model)

>>FeedforwardNeuralNetModel()

当我使用以下代码时

class FeedforwardNeuralNetModel(nn.Module):
    def __init__(self, input_dim, hidden_dim, output_dim):
        super(FeedforwardNeuralNetModel, self).__init__()
        # Linear function
        self.fc1 = nn.Linear(input_dim, hidden_dim) 
        # Non-linearity
        self.tanh = nn.Tanh()
        # Linear function (readout)
        self.fc2 = nn.Linear(hidden_dim, output_dim)  

    def forward(self, x):
        # Linear function
        out = self.fc1(x)
        # Non-linearity
        out = self.tanh(out)
        # Linear function (readout)
        out = self.fc2(out)
        return out

当我尝试打印此模型时,我发现了以下结果

print(model)

>>FeedforwardNeuralNetModel(
(fc1): Linear(in_features=3, out_features=5, bias=True)
(sigmoid): Sigmoid()
(fc2): Linear(in_features=5, out_features=10, bias=True)
)

在我的代码中,我只是创建列表,这有什么区别 我只是想了解为什么在火炬中列出模型组件没有用?

如果你这样做 print(FeedForwardNetModel([1,2,3]) 它会给出以下错误

AttributeError: 'FeedforwardNeuralNetModel' object has no attribute '_modules'

这基本上意味着该对象无法识别您声明的模块。


为什么会这样?

目前,模块在 self.fc 中声明,即 list,因此 torch 无法知道它是否是模型,除非它执行 deep search,这是糟糕且低效的.


我们如何让 torch 知道 self.fc 是一个模块列表?

通过使用 nn.ModuleList(参见下面修改后的代码)。 ModuleList 和 ModuleDict 分别是 python 列表和字典,但它们告诉火炬 list/dict 包含一个 nn 模块。

#modified init function
def __init__(self, layers): 
    super().__init__()
    self.fc=nn.ModuleList()
    self.sigmoid=[]
    self.activationValue = []
    self.layers = layers
    for i in range(len(layers)-1):
        self.fc.append(nn.Linear(layers[i],layers[i+1]))
        self.sigmoid.append(nn.Sigmoid())