Attention的矩阵表示及理解

本文详细介绍了注意力机制在深度学习,特别是Seq2Seq模型中的应用。通过对比Luong和Vaswani的注意力机制,重点解释了Scaled Dot-Product Attention的工作原理,包括Attention Score的计算、Attention Distribution的softmax转换以及Attention Output的生成过程。文中还提供了矩阵运算的表示,帮助读者理解各个步骤,并给出了PyTorch实现的关键代码片段。

Attention两篇文章链接:其中一个是Luong,提的dot product attention, 另一个是Vaswali的scaled dot product attention , 也就是大名鼎鼎的attention is all you need。

说到attention不再过多赘述,论文中的公式推导感觉比较简单,结合自己的理解写一下矩阵层面的表示。数学好的可以跳过。

在attention is all you need这篇文章中,他是这么写的:
A t t e n t i o n ( Q , K , V ) = s o f t m a x ( Q K T d k ) V Attention(Q, K, V) = softmax(\frac{QK^T}{\sqrt{d_k}})V Attention(Q,K,V)=softmax(dk QKT)V,而Luong那篇文章中,公式比较多且分散。
但无论如何,大致总结是(看下图),先算attention score(Q,K相乘),再用softmax算distribution,再把distribution和hidden state相乘获得attention output(最上面那个MatMul),再把output和另一个hidden相加(concat)。在这里插入图片描述

这里以seq2seq模型中的attention为例。

首先我们有encoder hidden state的一个序列: H = [ h 1 , h 2 , . . . h N ] H =[h_1, h_2, ...h_N] H=[h1,h2,...hN]
然后有 t t t 时刻的decoder state s t s^t st, 所有时刻的decoder state就是 S = [ s 1 , s 2 , . . . , s t ] S=[s^1, s^2, ..., s^t] S=[s1,s2,...,st]
每次用所有的encoder hidden state去和当前时刻的decoder state相乘(dot product)

对于 t t t时刻而言的attention score就是用 e t = [ h 1 T s t , h 2 T s t , . . . , h N T s t ] e^t = [h_1^Ts^t, h_2^Ts^t, ..., h_N^Ts^t] et=[h1Tst,h2Tst,...,hNTst]
但实际在计算中,我们是把整个decoder hidden state和encoder hidden state乘起来,而不是像循环一样对每个时刻都依次计算
E = [ h 1 T s 1 h 2 T s 1 , . . . , h N T s 1 ⋮ ⋮ ⋱ ⋮ h 1 T s t − 1 h 2 T s t − 1 , . . . , h N T s t − 1 h 1 T s t h 2 T s t , . . . , h N T s t ] = [ s 1 s 2 ⋮ s t ] ⋅ [ h 1 T h 2 T ⋯ h N T ]   ( 1 ) E = \left[ \begin{matrix} h_1^Ts^1 & h_2^Ts^1, &..., &h_N^Ts^1 \\ \vdots & \vdots &\ddots &\vdots\\ h_1^Ts^{t-1} & h_2^Ts^{t-1}, &..., &h_N^Ts^{t-1}\\ h_1^Ts^t & h_2^Ts^t, &..., &h_N^Ts^t \end{matrix} \right] = \left[ \begin{matrix}s^1\\ s^2\\ \vdots\\ s^t \end{matrix} \right] \cdot \left[ \begin{matrix} h_1^T & h_2^T & \cdots & & h_N^T \end{matrix} \right] \ (1) E=h1Ts1h1Tst1h1Tsth

### 实现注意力机制中的偏移矩阵 在实现带有偏移的注意力机制时,通常是在计算注意力分数之前引入一个可学习的偏移量。这有助于模型更好地捕捉输入序列之间的相对位置关系[^1]。 对于基于Luong的注意力机制来说,可以通过修改注意力得分函数来加入偏移项: ```python import tensorflow as tf class OffsetAttention(tf.keras.layers.Layer): def __init__(self, units): super(OffsetAttention, self).__init__() self.W1 = tf.keras.layers.Dense(units) self.W2 = tf.keras.layers.Dense(units) self.V = tf.keras.layers.Dense(1) self.offset = tf.Variable(initial_value=tf.zeros([units]), trainable=True) def call(self, query, values): hidden_with_time_axis = tf.expand_dims(query, 1) score = self.V( tf.nn.tanh( self.W1(hidden_with_time_axis) + self.W2(values) + self.offset)) attention_weights = tf.nn.softmax(score, axis=1) context_vector = attention_weights * values context_vector = tf.reduce_sum(context_vector, axis=1) return context_vector, attention_weights ``` 上述代码定义了一个`OffsetAttention`类,该类继承自TensorFlow Keras层。通过初始化方法设置了三个全连接层以及一个可训练变量作为偏移向量。调用此层时会返回上下文向量和注意权重。 在这个例子中,偏移被加到了原始特征表示上,从而允许网络学习如何调整不同时间步之间的重要性分配。这种做法可以增强模型对某些特定模式的理解能力,尤其是在处理具有复杂结构的数据集时效果显著。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值