python - Keras 中的 Bi-LSTM 注意力模型

标签 python tensorflow machine-learning keras deep-learning

我正在尝试使用词嵌入使用 Bi-LSTM 制作注意力模型。我遇到了How to add an attention mechanism in keras? , https://github.com/philipperemy/keras-attention-mechanism/blob/master/attention_lstm.pyhttps://github.com/keras-team/keras/issues/4962

但是,我对用于关系分类的基于注意力的双向长短期内存网络的实现感到困惑。所以,

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

希望这有帮助!

关于python - Keras 中的 Bi-LSTM 注意力模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52867069/

相关文章:

KDTree 中的 python 点索引

python - 列表理解困惑

python - TensorFlow:从 RNN 获取所有状态

tensorflow 自定义循环不会在第一个纪元结束并且进度条运行到无限

scala - 将 groupByKey() 替换为 reduceByKey()

Python:我可以在变量中存储变量名吗?

Python for 循环实现

tensorflow - 如何在TensorFlow中计算CNN的准确性

algorithm - 用于估计分数的分类算法

c# - ML-Agents 代理未重置?