Keras 2 API 文档 / 层 API / 注意力层 / AdditiveAttention 层

AdditiveAttention 层

[源代码]

AdditiveAttention

tf_keras.layers.AdditiveAttention(use_scale=True, **kwargs)

加性注意力层,又称 Bahdanau 风格的注意力。

输入是形状为 [batch_size, Tq, dim]query 张量,形状为 [batch_size, Tv, dim]value 张量,以及形状为 [batch_size, Tv, dim]key 张量。计算遵循以下步骤:

  1. querykey 分别重塑为形状 [batch_size, Tq, 1, dim][batch_size, 1, Tv, dim]
  2. 计算形状为 [batch_size, Tq, Tv] 的分数,方法是进行非线性求和:scores = tf.reduce_sum(tf.tanh(query + key), axis=-1)
  3. 使用分数计算形状为 [batch_size, Tq, Tv] 的分布:distribution = tf.nn.softmax(scores)
  4. 使用 distribution 创建 value 的线性组合,形状为 [batch_size, Tq, dim]return tf.matmul(distribution, value)

参数

  • use_scale:如果为 True,将创建一个变量来缩放注意力分数。
  • dropout:0 到 1 之间的浮点数。用于注意力分数的单元丢弃比例。默认为 0.0

调用参数

  • inputs:以下张量的列表
    • query:查询 Tensor,形状为 [batch_size, Tq, dim]
    • value:值 Tensor,形状为 [batch_size, Tv, dim]
    • key:可选的键 Tensor,形状为 [batch_size, Tv, dim]。如果未提供,将使用 value 作为 keyvalue,这是最常见的情况。
  • mask:以下张量的列表
    • query_mask:布尔掩码 Tensor,形状为 [batch_size, Tq]。如果提供,则输出在 mask==False 的位置将为零。
    • value_mask:布尔掩码 Tensor,形状为 [batch_size, Tv]。如果提供,将应用掩码,使得 mask==False 的位置的值不会对结果做出贡献。
  • training:Python 布尔值,指示该层是应以训练模式(添加 dropout)还是推理模式(无 dropout)运行。
  • return_attention_scores:布尔值,如果为 True,则将注意力分数(经过掩码和 softmax 后)作为额外的输出参数返回。
  • use_causal_mask:布尔值。设置为 True 用于 decoder self-attention。添加一个掩码,使得位置 i 不能 attending 到位置 j > i。这可以防止信息从未来流向过去。默认为 False

输出

Attention outputs of shape `[batch_size, Tq, dim]`.
[Optional] Attention scores after masking and softmax with shape
    `[batch_size, Tq, Tv]`.

queryvaluekey 的含义取决于应用。例如,在文本相似性的情况下,query 是第一个文本片段的序列嵌入,而 value 是第二个文本片段的序列嵌入。key 通常与 value 是相同的张量。

以下是在 CNN+Attention 网络中使用 AdditiveAttention 的代码示例。

# Variable-length int sequences.
query_input = tf.keras.Input(shape=(None,), dtype='int32')
value_input = tf.keras.Input(shape=(None,), dtype='int32')

# Embedding lookup.
token_embedding = tf.keras.layers.Embedding(max_tokens, dimension)
# Query embeddings of shape [batch_size, Tq, dimension].
query_embeddings = token_embedding(query_input)
# Value embeddings of shape [batch_size, Tv, dimension].
value_embeddings = token_embedding(value_input)

# CNN layer.
cnn_layer = tf.keras.layers.Conv1D(
    filters=100,
    kernel_size=4,
    # Use 'same' padding so outputs have the same shape as inputs.
    padding='same')
# Query encoding of shape [batch_size, Tq, filters].
query_seq_encoding = cnn_layer(query_embeddings)
# Value encoding of shape [batch_size, Tv, filters].
value_seq_encoding = cnn_layer(value_embeddings)

# Query-value attention of shape [batch_size, Tq, filters].
query_value_attention_seq = tf.keras.layers.AdditiveAttention()(
    [query_seq_encoding, value_seq_encoding])

# Reduce over the sequence axis to produce encodings of shape
# [batch_size, filters].
query_encoding = tf.keras.layers.GlobalAveragePooling1D()(
    query_seq_encoding)
query_value_attention = tf.keras.layers.GlobalAveragePooling1D()(
    query_value_attention_seq)

# Concatenate query and document encodings to produce a DNN input layer.
input_layer = tf.keras.layers.Concatenate()(
    [query_encoding, query_value_attention])

# Add DNN layers, and create Model.
# ...