【问题标题】:`return_sequences = False` equivalent in pytorch LSTMpytorch LSTM 中的 `return_sequences = False` 等效项
【发布时间】:2020-09-23 23:56:04
【问题描述】:

在 tensorflow/keras 中,我们可以简单地为分类/全连接/激活(softmax/sigmoid)层之前的最后一个 LSTM 层设置return_sequences = False,以摆脱时间维度。

在 PyTorch 中,我找不到类似的东西。对于分类任务,我不需要序列到序列模型,而是像这样的多对一架构:

这是我的简单双 LSTM 模型。

import torch
from torch import nn

class BiLSTMClassifier(nn.Module):
    def __init__(self):
        super(BiLSTMClassifier, self).__init__()
        self.embedding = torch.nn.Embedding(num_embeddings = 65000, embedding_dim = 64)
        self.bilstm = torch.nn.LSTM(input_size = 64, hidden_size = 8, num_layers = 2,
                                    batch_first = True, dropout = 0.2, bidirectional = True)
        # as we have 5 classes
        self.linear = nn.Linear(8*2*512, 5) # last dimension
    def forward(self, x):
        x = self.embedding(x)
        print(x.shape)
        x, _ = self.bilstm(x)
        print(x.shape)
        x = self.linear(x.reshape(x.shape[0], -1))
        print(x.shape)

# create our model

bilstmclassifier = BiLSTMClassifier()

如果我观察每一层之后的形状,

xx = torch.tensor(X_encoded[0]).reshape(1,512)
print(xx.shape) 
# torch.Size([1, 512])
bilstmclassifier(xx)
#torch.Size([1, 512, 64])
#torch.Size([1, 512, 16])
#torch.Size([1, 5])

我该怎么做才能让最后一个 LSTM 返回形状为 (1, 16) 而不是 (1, 512, 16) 的张量?

【问题讨论】:

  • 只取那个维度的最后一个元素? x = x[:, -1, :] 其中x 是 LSTM 输出。
  • 谢谢,@xdurch0 似乎是一个简单的解决方案。和tensorflowreturn_sequences = False一样吗?
  • 我决定做一点挖掘并发布一个正确的答案。 tl;博士:是的。

标签: python-3.x tensorflow nlp pytorch lstm


【解决方案1】:

最简单的方法是对张量进行索引:

x = x[:, -1, :]

x 是 RNN 输出。当然,如果batch_firstFalse,则必须使用x[-1, :, :](或只是x[-1])来索引时间轴。事实证明,这与 Tensorflow/Keras 所做的相同。相关代码可见K.rnnhere

last_output = tuple(o[-1] for o in outputs)

注意此时的代码使用time_major数据格式,所以索引在第一个轴上。此外,outputs 是一个元组,因为它可以是多个层、状态/单元对等,但它通常是所有时间步的输出序列

然后在RNN 类中使用如下:

if self.return_sequences:
    output = K.maybe_convert_to_ragged(is_ragged_input, outputs, row_lengths)
else:
    output = last_output

所以总的来说,我们可以看到return_sequences=False 只使用了outputs[-1]

【讨论】:

  • 太棒了,我在想类似的东西,但没有研究实现。感谢您的挖掘。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-01-03
  • 2020-06-10
  • 2019-01-02
  • 2021-11-29
  • 1970-01-01
  • 2018-12-24
  • 1970-01-01
相关资源
最近更新 更多