python - keras中注意力层是如何实现的?

标签 python keras deep-learning tf.keras attention-model

我正在学习注意力模型及其在 keras 中的实现。在搜索时我遇到了这两种方法 firstsecond使用它我们可以在 keras 中创建一个注意力层

# First method

class Attention(tf.keras.Model):
    def __init__(self, units):
        super(Attention, self).__init__()
        self.W1 = tf.keras.layers.Dense(units)
        self.W2 = tf.keras.layers.Dense(units)
        self.V = tf.keras.layers.Dense(1)

    def call(self, features, hidden):
        hidden_with_time_axis = tf.expand_dims(hidden, 1)
        score = tf.nn.tanh(self.W1(features) + self.W2(hidden_with_time_axis))
        attention_weights = tf.nn.softmax(self.V(score), axis=1)
        context_vector = attention_weights * features
        context_vector = tf.reduce_sum(context_vector, axis=1)

        return context_vector, attention_weights

# Second method

activations = LSTM(units, return_sequences=True)(embedded)

# compute importance for each step
attention = Dense(1, activation='tanh')(activations)
attention = Flatten()(attention)
attention = Activation('softmax')(attention)
attention = RepeatVector(units)(attention)
attention = Permute([2, 1])(attention)

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

math behind attention model

enter image description here

如果我们看第一种方法,它在某种程度上是注意力数学的直接实现,而在互联网上点击次数更多的第二种方法则不是。

我真正的疑问是第二种方法中的这些行

attention = RepeatVector(units)(attention)
attention = Permute([2, 1])(attention)
sent_representation = merge([activations, attention], mode='mul')
  • 哪个是引起关注的正确实现方式?
  • 第二种方法中 RepeatVectorPermute 层背后的直觉是什么?
  • 第一个方法中W1W2是权重;为什么这里将密集层视为权重?
  • 为什么V值被视为单个单元密集层?
  • V(score) 是做什么的?

最佳答案

Which is the right implementation for attention?

我推荐以下内容:

https://github.com/tensorflow/models/blob/master/official/transformer/model/attention_layer.py#L24

上面的多头注意力层实现了一个巧妙的技巧:它 reshape 了矩阵,使其不再被塑造为(batch_size,time_steps,features),而是被塑造为(batch_size,heads,time_steps,features/heads)并且然后它对“特征/头” block 执行计算。

What is the intution behind RepeatVector and Permute layer in second method?

您的代码不完整...您的代码中缺少矩阵乘法(您没有显示正在使用的注意层)。这可能会修改结果的形状,并且此代码正在尝试以某种方式恢复正确的形状。这可能不是最好的方法。

In the first method W1,W2 are weights; why is a dense layer is consider as weights here?

密集层是一组权重...您的问题有点模糊。

Why is the V value is considered as a single unit dense layer?

这是一个非常奇怪的选择,与我对论文的阅读和我所看到的实现不符。

关于python - keras中注意力层是如何实现的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56987142/

相关文章:

python - WGAN-GP 列车损失较大

tensorflow - 在Keras/Tensorflow中实现自定义WARP丢失功能,出现错误: LookupError: No gradient defined for operation

python - 是否有轻量级的 Python 模块来加载预装的 ML 模块并执行预测?

keras - 如何知道keras中的特定层索引

c++ - 使用 Visual C++ Express 10 链接到 boost::python

python - 使用 numpy.max/numpy.min 作为时间戳值

python - 如何将 keras 模型转换为 Protocol Buffer (.pb) 文件?

machine-learning - 训练和验证精度高,测试精度差

python - 带有 tkinter xgboost 的 cxfreeze 小部件未显示但没有错误

python - 在python中通过json递归