Products
GG网络技术分享 2025-08-15 17:20 6
许多头是近年来天然语言处理领域的一项关键进展。它通过将输入序列分解为优良几个子序列,并在不同的子序列间,从而搞优良模型对麻烦关系的捕捉能力。
许多头的核心是计算优良几个注意力权沉矩阵,个个矩阵对应不同的子序列。通过将这些个矩阵拼接,能得到一个综合的注意力权沉矩阵,进而对输入序列进行加权求和,得到到头来输出。
def scaled_dot_product_attention:
matmul_qk = tf.matmul
dk = tf.cast, tf.float32)
scaled_attention_logits = matmul_qk / tf.math.sqrt
if mask is not None:
scaled_attention_logits +=
attention_weights = tf.nn.softmax
output = tf.matmul
return output, attention_weights
class MultiHeadAttention:
def __init__:
super.__init__
self.num_heads = num_heads
self.d_model = d_model
assert d_model % self.num_heads == 0
self.depth = d_model // self.num_heads
self.wq = tf.keras.layers.Dense
self.wk = tf.keras.layers.Dense
self.wv = tf.keras.layers.Dense
self.dense = tf.keras.layers.Dense
def split_heads:
x = tf.reshape)
return tf.transpose
def call:
batch_size = tf.shape
q = self.wq
k = self.wk
v = self.wv
q = self.split_heads
k = self.split_heads
v = self.split_heads
scaled_attention, attention_weights = scaled_dot_product_attention
scaled_attention = tf.transpose
concat_attention = tf.reshape)
output = self.dense
return output, attention_weights
利用计算得到的优良几个头的注意力矩阵 A_i 合并成一个注意力矩阵 W,然后通过线性变换得到许多头的到头来权沉 R,用 R 权沉对输入特征矩阵进行加权平均并输出。
许多头在天然语言处理中有广泛的应用,如在翻译中用于计算源语言和目标语言之间的注意力矩阵,使得模型在翻译时更关注有关的单词。一边, 在生成对话时也能利用许多头来计算上下文和下一个句子之间的关联度,以便生成更加连贯有逻辑的对话。
许多头作为一种基础的,具有很有力的灵活性和可塑性,能应用于各种领域,是深厚度学中应用最广泛的机制之一。
Demand feedback