【问题标题】:Either too little or too many arguments for a nn.Sequentialnn.Sequential 的参数太少或太多
【发布时间】:2020-04-05 00:44:24
【问题描述】:

我是 PyTorch 的新手,所以请原谅我的愚蠢问题。

我在 Encoder 对象的 init 中定义了一个 nn.Sequential,如下所示:

self.list_of_blocks = [EncoderBlock(n_features, n_heads, n_hidden, dropout) for _ in range(n_blocks)]
self.blocks = nn.Sequential(*self.list_of_blocks)

EncoderBlock 的前端是这样的

def forward(self, x, mask):

在我的编码器的 forward() 中,我尝试这样做:

z0 = self.blocks(z0, mask)

我希望 nn.Sequential 将这两个参数传递给各个块。

但是,我明白了

TypeError: forward() takes 2 positional arguments but 3 were given

当我尝试时:

z0 = self.blocks(z0)

我明白了(可以理解):

TypeError: forward() takes 2 positional arguments but only 1 was given

当我不使用 nn.Sequential 并且只执行一个又一个 EncoderBlock 时,它可以工作:

for i in range(self.n_blocks):
     z0 = self.list_of_blocks[i](z0, mask)

问题:我做错了什么,在这种情况下如何正确使用 nn.Sequential?

【问题讨论】:

    标签: deep-learning neural-network pytorch sequential attention-model


    【解决方案1】:

    顺序一般不适用于多个输入和输出。

    这是一个经常讨论的话题,请参阅 PyTorch forum 和 GitHub 问题 #1908#9979

    您可以定义自己的顺序版本。假设所有编码器块的掩码都相同(例如,就像在 Transformer 网络中一样),您可以这样做:

    class MaskedSequential(nn.Sequential):
        def forward(self, x, mask):
            for module in self._modules.values():
                x = module(x, mask)
            return inputs
    

    或者如果您的EncoderBlocks 返回元组,您可以使用GitHub issues 之一中建议的更通用的解决方案:

    class MySequential(nn.Sequential):
        def forward(self, *inputs):
            for module in self._modules.values():
                if type(inputs) == tuple:
                    inputs = module(*inputs)
                else:
                    inputs = module(inputs)
            return inputs
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-17
      • 1970-01-01
      • 2020-08-04
      • 1970-01-01
      • 2021-05-14
      • 2019-07-29
      • 1970-01-01
      • 2018-07-09
      相关资源
      最近更新 更多