2

我喜欢torch.nn.Sequential使用

self.conv_layer = torch.nn.Sequential(
    torch.nn.Conv1d(196, 196, kernel_size=15, stride=4),
    torch.nn.Dropout()
)

但是当我想添加一个循环层时,torch.nn.GRU它不起作用,因为 PyTorch 中循环层的输出是一个元组,您需要选择要进一步处理输出的哪一部分。

那么有什么办法可以得到

self.rec_layer = nn.Sequential(
    torch.nn.GRU(input_size=2, hidden_size=256),
    torch.nn.Linear(in_features=256, out_features=1)
)

去工作?对于这个例子,假设我想将torch.nn.GRU(input_size=2, hidden_size=20)(x)[1][-1](最后一层的最后一个隐藏状态)馈送到下Linear一层。

4

1 回答 1

4

我制作了一个名为 SelectItem 的模块来从元组或列表中挑选一个元素

class SelectItem(nn.Module):
    def __init__(self, item_index):
        super(SelectItem, self).__init__()
        self._name = 'selectitem'
        self.item_index = item_index

    def forward(self, inputs):
        return inputs[self.item_index]

SelectItem可用于Sequential挑选隐藏状态:

    net = nn.Sequential(
        nn.GRU(dim_in, dim_out, batch_first=True),
        SelectItem(1)
        )
于 2019-02-13T00:41:34.737 回答