简体   繁体   English

我可以在 `nn.Sequential` 中解压 `nn.ModuleList` 吗?

[英]Can I unpack an `nn.ModuleList` inside `nn.Sequential`?

I am parametrizing the number of hidden layers of a simple ANN using nn.ModuleList .我正在使用nn.ModuleList对简单 ANN 的隐藏层数进行参数化。 I am wondering if passing this list into a nn.Sequential module as follows would lead to any adverse effects with the execution graph.我想知道如下将此列表传递到nn.Sequential模块是否会对执行图产生任何不利影响。

nn.Sequential is not necessary, however it seems cleaner to me to have the entire architecture explicit in the constructor. nn.Sequential不是必需的,但是在构造函数中明确整个架构对我来说似乎更清晰。

class ANN(nn.Module):

    def __init__(
        self,
        in_feats=3,
        in_hidden=5,
        n_hidden_layers=3,

    ):
        super(ANN, self).__init__()

        # ====== dynamically register hidden layers ======
        self.hidden_linears = nn.ModuleList()
        for i in range(n_hidden_layers):
            self.hidden_linears.append(nn.Linear(in_hidden, in_hidden))
            self.hidden_linears.append(nn.ReLU())
        
        # ====== sequence of layers ======
        self.layers = nn.Sequential(
            nn.Linear(in_feats, in_hidden),
            nn.ReLU(),
            *self.hidden_linears,
            nn.Linear(in_hidden, 1),
            nn.Sigmoid(),
        )

    def forward(self, X):
        return self.layers(X)

Also open to suggestions of neater ways to put this together.也愿意接受更简洁的方法将它们组合在一起的建议。

You could use nn.Sequential.modules() to get every single part of the Sequential and then pack them into a list.您可以使用nn.Sequential.modules()获取 Sequential 的每个部分,然后将它们打包到一个列表中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM