【问题标题】:How is attention layer implemented in keras?keras 中注意力层是如何实现的?
【发布时间】:2019-07-11 10:27:58
【问题描述】:

我正在学习注意力模型及其在 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

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

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

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

【问题讨论】:

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


【解决方案1】:

哪个是引起注意的正确实现?

我会推荐以下内容:

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

上面的多头注意力层实现了一个绝妙的技巧:它重塑了矩阵,使其形状不是(batch_size,time_steps,features),而是(batch_size,heads,time_steps,features/heads)和然后它对“特征/头”块执行计算。

第二种方法中RepeatVector和Permute层背后的直觉是什么?

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

在第一种方法中,W1,W2 是权重;为什么在这里将密集层视为权重?

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

为什么V值被认为是单个单元密集层?

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

【讨论】:

  • 嘿,谢谢你的回答。 Your code is incomplete... there is a matrix multiplication missing .... 我从这里获取代码 stackoverflow.com/q/42918446/996366 。你能告诉我普通注意力和多头注意力有什么区别吗?
  • 多头注意力意味着从一个time_step到全局(所有时间步)状态执行了多个“查询”。还学习了“查询”。每个人都倾向于关注句子的不同特征。当然,这都是纯粹的猜测……但您可以将注意力集中在句子的多个特征(例如主语、动词、目标)上,以便了解如何从一种语言翻译成另一种语言。
猜你喜欢
  • 1970-01-01
  • 2016-09-11
  • 1970-01-01
  • 1970-01-01
  • 2021-02-08
  • 2019-05-22
  • 2018-04-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多