【问题标题】:keras. Initializing a bidirecional LSTM. Passing word embeddings喀拉斯。初始化双向 LSTM。传递词嵌入
【发布时间】:2018-10-28 16:37:04
【问题描述】:

在我使用的实现中,lstm 的初始化方式如下:

l_lstm = Bidirectional(LSTM(64, return_sequences=True))(embedded_sequences)

我不太明白,这可能是因为缺乏 Python 经验:符号 l_lstm= Bidirectional(LSTM(...))(embedded_sequences)。 我不明白我将embedded_sequences 传递给什么?因为它不是LSTM() 的参数,但似乎也不是Bidirectional() 的参数,因为它是单独存在的。

这是双向的文档:

  def __init__(self, layer, merge_mode='concat', weights=None, **kwargs):
        if merge_mode not in ['sum', 'mul', 'ave', 'concat', None]:
            raise ValueError('Invalid merge mode. '
                             'Merge mode should be one of '
                             '{"sum", "mul", "ave", "concat", None}')
        self.forward_layer = copy.copy(layer)
        config = layer.get_config()
        config['go_backwards'] = not config['go_backwards']
        self.backward_layer = layer.__class__.from_config(config)
        self.forward_layer.name = 'forward_' + self.forward_layer.name
        self.backward_layer.name = 'backward_' + self.backward_layer.name
        self.merge_mode = merge_mode
        if weights:
            nw = len(weights)
            self.forward_layer.initial_weights = weights[:nw // 2]
            self.backward_layer.initial_weights = weights[nw // 2:]
        self.stateful = layer.stateful
        self.return_sequences = layer.return_sequences
        self.return_state = layer.return_state
        self.supports_masking = True
        self._trainable = True
        super(Bidirectional, self).__init__(layer, **kwargs)
        self.input_spec = layer.input_spec
        self._num_constants = None

【问题讨论】:

    标签: python keras lstm embedding


    【解决方案1】:

    让我们试着分解发生了什么:

    1. 您从 LSTM(...) 开始,它创建了一个 LSTM Layer。现在layers in Keras are callable 这意味着您可以像使用函数一样使用它们。例如lstm = LSTM(...) 然后lstm(some_input)调用给定输入张量的LSTM。
    2. Bidirectional(...) 包装任何 RNN 层并返回另一个层,当调用该层时,它会在两个方向上应用包装层。所以l_lstm = Bidirectional(LSTM(...)) 是一个层,当使用一些输入调用时,将在两个方向上应用LSTM注意:双向创建传递的 LSTM 层的副本,因此向后和向前是不同的 LSTM。
    3. 最后,当您调用Bidirectional(LSTM(...))(embedded_seqences) 时,双向层获取输入序列,将其双向传递给封装的 LSTM,收集它们的输出并将其连接起来。

    要了解有关层及其可调用性质的更多信息,您可以查看文档的functional API guide

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-03
      • 2018-01-22
      • 1970-01-01
      • 2021-06-26
      • 2017-12-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多