如何在PyTorch中将LSTM,GRU或其他循环图层添加到Sequential中

时间:2018-06-12 13:01:41

标签: pytorch

我喜欢在

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

但是当我想添加一个 recurrent 层,例如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图层。

2 个答案:

答案 0 :(得分:0)

AFAIK,你不能在顺序中使用RNN层(因为它不是连续的,它是经常性的)。

答案 1 :(得分:0)

我制作了一个名为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)
        )