如何将 LSTM、GRU 或其他循环层添加到 PyTorch 中的序列中

the*_*ass 2 pytorch

我喜欢使用torch.nn.Sequential

self.conv_layer = torch.nn.Sequential(
    torch.nn.Conv1d(196, 196, kernel_size=15, stride=4),
    torch.nn.Dropout()
)
Run Code Online (Sandbox Code Playgroud)

但是,当我想添加一个循环层时,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)
)
Run Code Online (Sandbox Code Playgroud)

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

小智 6

我制作了一个名为 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]
Run Code Online (Sandbox Code Playgroud)

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

    net = nn.Sequential(
        nn.GRU(dim_in, dim_out, batch_first=True),
        SelectItem(1)
        )
Run Code Online (Sandbox Code Playgroud)