首页 > 解决方案 > Keras 中的 Bi-LSTM 注意力模型

问题描述

我正在尝试使用词嵌入使用 Bi-LSTM 制作注意力模型。我遇到了如何在 keras 中添加注意力机制?, https://github.com/philipperemy/keras-attention-mechanism/blob/master/attention_lstm.pyhttps://github.com/keras-team/keras/issues/4962

但是,我对Attention-Based Bidirectional Long Short-Term Memory Networks for Relation Classification. 所以,

_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)

标签: pythontensorflowmachine-learningkerasdeep-learning

解决方案


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 层对加权隐藏状态向量求和,以获得最终将使用的向量。

希望这有帮助!


推荐阅读