Keras 中的 Bi-LSTM 注意力模型

2023-12-27

我正在尝试使用词嵌入使用 Bi-LSTM 制作注意力模型。我碰到如何在keras中添加注意力机制? https://stackoverflow.com/questions/42918446/how-to-add-an-attention-mechanism-in-keras, https://github.com/philipperemy/keras-attention-mechanism/blob/master/attention_lstm.py https://github.com/philipperemy/keras-attention-mechanism/blob/master/attention_lstm.py and https://github.com/keras-team/keras/issues/4962 https://github.com/keras-team/keras/issues/4962.

但是,我对实施感到困惑Attention-Based Bidirectional Long Short-Term Memory Networks for Relation Classification. So,

_input = Input(shape=[max_length], dtype='int32')

# get the embedding layer
embedded = Embedding(
        input_dim=30000,
        output_dim=300,
        input_length=100,
        trainable=False,
        mask_zero=False
    )(_input)

activations = Bidirectional(LSTM(20, return_sequences=True))(embedded)

# compute importance for each step
attention = Dense(1, activation='tanh')(activations)

我在这里很困惑哪个方程与论文中的方程是什么。

attention = Flatten()(attention)
attention = Activation('softmax')(attention)

RepeatVector 会做什么?

attention = RepeatVector(20)(attention)
attention = Permute([2, 1])(attention)


sent_representation = merge([activations, attention], mode='mul')

现在,我再次不确定为什么这条线在这里。

sent_representation = Lambda(lambda xin: K.sum(xin, axis=-2), output_shape=(units,))(sent_representation)

由于我有两个类,我将最终的 softmax 为:

probabilities = Dense(2, activation='softmax')(sent_representation)

attention = Flatten()(attention)  

将注意力权重张量转换为向量(如果序列大小为 max_length,则大小为 max_length)。

attention = Activation('softmax')(attention)

允许所有注意力权重在 0 到 1 之间,所有权重之和等于 1。

attention = RepeatVector(20)(attention)
attention = Permute([2, 1])(attention)


sent_representation = merge([activations, attention], mode='mul')

RepeatVector 重复注意力权重向量(大小为 max_len)与隐藏状态的大小 (20),以便按元素将激活和隐藏状态相乘。张量变量的大小激活是 max_len*20。

sent_representation = Lambda(lambda xin: K.sum(xin, axis=-2), output_shape=(units,))(sent_representation)

该 Lambda 层将加权隐藏状态向量相加,以获得最终使用的向量。

希望这有帮助!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Keras 中的 Bi-LSTM 注意力模型 的相关文章

随机推荐