【问题标题】:Why listing model components in pyTorch is not useful?为什么在 pyTorch 中列出模型组件没有用?
【发布时间】:2019-06-06 04:38:06
【问题描述】:

我正在尝试创建具有 N 层的前馈神经网络 所以想法是假设如果我想要 2 个输入、3 个隐藏和 2 个输出,那么我只需将 [2,3,2] 传递给神经网络类,并且将创建神经网络模型,所以如果我想要 [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)
)

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

【问题讨论】:

    标签: python neural-network pytorch feed-forward


    【解决方案1】:

    如果你这样做 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 列表和字典,但它们告诉 torch 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())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-24
      • 1970-01-01
      • 2020-06-09
      • 2013-02-09
      • 2018-01-03
      • 2021-03-18
      • 1970-01-01
      • 2020-10-24
      相关资源
      最近更新 更多