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 张量。计算遵循以下步骤:
query 和 key 分别重塑为形状 [batch_size, Tq, 1, dim] 和 [batch_size, 1, Tv, dim]。[batch_size, Tq, Tv] 的分数,方法是进行非线性求和:scores = tf.reduce_sum(tf.tanh(query + key), axis=-1)[batch_size, Tq, Tv] 的分布:distribution = tf.nn.softmax(scores)。distribution 创建 value 的线性组合,形状为 [batch_size, Tq, dim]:return tf.matmul(distribution, value)。参数
True,将创建一个变量来缩放注意力分数。0.0。调用参数
Tensor,形状为 [batch_size, Tq, dim]。Tensor,形状为 [batch_size, Tv, dim]。Tensor,形状为 [batch_size, Tv, dim]。如果未提供,将使用 value 作为 key 和 value,这是最常见的情况。Tensor,形状为 [batch_size, Tq]。如果提供,则输出在 mask==False 的位置将为零。Tensor,形状为 [batch_size, Tv]。如果提供,将应用掩码,使得 mask==False 的位置的值不会对结果做出贡献。True,则将注意力分数(经过掩码和 softmax 后)作为额外的输出参数返回。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]`.
query、value 和 key 的含义取决于应用。例如,在文本相似性的情况下,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.
# ...