【问题标题】:How can I do return_sequences for a stacked LSTM model with PyTorch?如何使用 PyTorch 为堆叠的 LSTM 模型执行 return_sequences?
【发布时间】:2020-06-10 20:44:21
【问题描述】:

我有一个 Tensorflow / Keras 模型:


        self.model.add(Bidirectional(LSTM(lstm1_size, input_shape=(
            seq_length, feature_dim), return_sequences=True)))
        self.model.add(BatchNormalization())
        self.model.add(Dropout(0.2))

        self.model.add(Bidirectional(
            LSTM(lstm2_size, return_sequences=True)))
        self.model.add(BatchNormalization())
        self.model.add(Dropout(0.2))

        # BOTTLENECK HERE

        self.model.add(Bidirectional(
            LSTM(lstm3_size, return_sequences=True)))
        self.model.add(BatchNormalization())
        self.model.add(Dropout(0.2))

        self.model.add(Bidirectional(
            LSTM(lstm4_size, return_sequences=True)))
        self.model.add(BatchNormalization())
        self.model.add(Dropout(0.2))

        self.model.add(Bidirectional(
            LSTM(lstm5_size, return_sequences=True)))
        self.model.add(BatchNormalization())
        self.model.add(Dropout(0.2))

        self.model.add(Dense(feature_dim, activation='linear'))

如何使用return_sequences 创建堆叠的 PyTorch 模型?我对return_sequences 的理解是它返回 LSTM 每一层的“输出”,然后将其输入下一层。

我将如何使用 PyToch 完成此任务?

【问题讨论】:

  • 您不确定什么?在目前的状态下,这个问题是含糊的,并没有显示出您方面的任何实施努力。如果您正在寻找一个明确的转换指南,我会使用ONNX 格式,这是我觉得很舒服的唯一链接指向它不是一个有偏见的资源。话又说回来,恐怕 ONNX 并不适合重现训练,因为它主要用于共享模型架构。
  • 更新了更具体的问题

标签: python tensorflow keras pytorch


【解决方案1】:

PyTorch 总是返回序列。

https://pytorch.org/docs/stable/nn.html#lstm

示例:

import torch as t

batch_size = 2
time_steps = 10
features = 2
data = t.empty(batch_size, time_steps, features).normal_()

lstm = t.nn.LSTM(input_size=2, hidden_size=3, bidirectional=True, batch_first=True)

output, (h_n, c_n) = lstm(data)
[output.shape, h_n.shape, c_n.shape]

[torch.Size([2, 10, 6]), torch.Size([2, 2, 3]), torch.Size([2, 2, 3])]

class Net(t.nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.lstm_1 = t.nn.LSTM(input_size=2, hidden_size=3, bidirectional=True, batch_first=True)
        self.lstm_2 = t.nn.LSTM(input_size=2*3, hidden_size=4, bidirectional=True, batch_first=True)

    def forward(self, input):
        output, (h_n, c_n) = self.lstm_1(input)
        output, (h_n, c_n) = self.lstm_2(output)
        return output

net = Net()

net(data).shape

torch.Size([2, 10, 8])

【讨论】:

  • 是的。如果你想要最后一个元素,你应该使用output[:,-1,:]batch_first=True,以及output[-1,:,:]batch_first=False
猜你喜欢
  • 2020-09-23
  • 2019-07-11
  • 1970-01-01
  • 2021-03-14
  • 1970-01-01
  • 2021-07-26
  • 1970-01-01
  • 2021-01-06
  • 2020-02-09
相关资源
最近更新 更多