LSTM 自动编码器输出层

LSTM Autoencoder Output Layer

我正在尝试让 LSTM 自动编码器重新创建其输入。到目前为止我有:

class getSequence(nn.Module):
    def forward(self, x):
        out, _ = x
        return out


class getLast(nn.Module):
    def forward(self, x):
        out, states = x
        states = states[len(states) - 1]
        return states

class AEncoder(nn.Module):
    def __init__(self, input_size, first_layer, second_layer, n_layers):
        super(AEncoder, self).__init__()
        self.n_layers = n_layers
        self.encode = nn.Sequential(nn.LSTM(input_size, first_layer, batch_first=True),
                                    getSequence(),
                                    nn.ReLU(True),
                                    nn.LSTM(first_layer, second_layer),
                                    getLast())
        self.decode = nn.Sequential(nn.LSTM(second_layer, first_layer),
                                    getSequence(),
                                    nn.ReLU(True),
                                    nn.LSTM(first_layer, input_size),
                                    getSequence())

    def forward(self, x):
        x = x.float()
        x = self.encode(x)
        x = x.repeat(32, 1, 1) # repeating last hidden state of self.encode
        x = self.decode(x)
        return x

在研究过程中,我看到一些人在 self.decode 的末尾添加了一个时间分布的密集层。我很困惑,如果最后一层是特定于自动编码器用于的其他任务,如果是这样,如果我只是想重新创建输入,我可以忽略那个层吗?

时间分布密集层顾名思义只是一个普通的密集层,适用于输入的每个时间片,您可以将其视为[=21的特殊形式=]RNN 单元,即没有循环隐藏状态。

因此,您可以使用任何时间分布的层作为处理时间分布输入的自动编码器的输出层,例如具有 LSTM CellGRU Cell, Simple RNN Cell or time-distributed dense layer;如research paper that propose the LSTM-Autoencoder,它在编码器和解码器中仅使用一个 LSTM 层重建向量序列(图像块或特征)的基本模型,模型结构为:

以下是在解码器中使用时间分布密集层的示例:

class Decoder(nn.Module):

  def __init__(self, seq_len, input_dim=64, n_features=1):
    super(Decoder, self).__init__()

    self.seq_len, self.input_dim = seq_len, input_dim
    self.hidden_dim, self.n_features = 2 * input_dim, n_features

    self.rnn = nn.LSTM(
      input_size=input_dim,
      hidden_size=self.hidden_dim,
      num_layers=1,
      batch_first=True)

    self.output_layer = nn.Linear(self.hidden_dim, n_features)

  def forward(self, x):
    x = x.repeat(self.seq_len, self.n_features)
    x = x.reshape((self.n_features, self.seq_len, self.input_dim))
    x, (hidden_n, cell_n) = self.rnn(x)
    x = x.reshape((self.seq_len, self.hidden_dim))
    return self.output_layer(x)