开宗明义:attention就是一个加权机制,但是权重需要经过训练得到。感觉有些情况就是代替了concat然后过模型的场景,优势是更小、参数更少。
本文介绍一些我自己整理的常见attention类型。
本文不关注别的博文里已经写烂了的attention机制的重要性和直觉解释(又不是写论文还要写introduction)。
multi-head attention也不在本文赘述。
待补。
K-key:输入,想从中找到权重高低的部分的那个东西
Q-query:拿来计算key各部权重的对象
KQ是拿来计算权重的,权重需要归一化(softmax)
V-value:是那个被用来乘权重的对象(也就是输入)


K是通过输入通过MLP后得到,Q是通过训练得到的context vector,V是输入。相当于对输入进行一个加权求和
HAN1:两层attention+GRU


(图中h是单词表征,
u
i
t
u_it
uit是单词表征经一层MLP后得到的隐表征,
u
w
u_w
uw是context vector,
α
\alpha
α是注意力权重,s是句子表征)

(这是第二层attention,差不多)
LeSICiN2里面聚合法条表征:

(论文中给出一项优化方法,是将context vector改为用其他嵌入经线性转换后得到的结果。但是没给出ablation study)
GNMT:

ConvS2S
定义见第4节
图场景:
(QKV都是输入,但仅在样本之间存在的关系/边上概率化attention)









[batch_size,query_num,hidden_dim]),context是输入(维度是[batch_size,sent_len,hidden_dim])
[batch_size,1,hidden_dim])直接就用来预测了(原代码里分别用了2个query,得到两个attention输出,concat起来做预测)class Code_Wise_Attention(nn.Module):
def __init__(self):
super(Code_Wise_Attention, self).__init__()
def forward(self,query,context):
S = torch.bmm(context, query.transpose(1, 2))
attention = torch.nn.functional.softmax(torch.max(S, 2)[0], dim=-1)
context_vec = torch.bmm(attention.unsqueeze(1), context)
return context_vec
这个attention机制,在NeurJudge原文中给出了两篇参考文献,还没看:Bidirectional attention flow for machine comprehension和Multi-Interactive Attention Network for Fine-grained Feature Learning in CTR Prediction

[batch_size,sent_len,hidden_dim]class Mask_Attention(nn.Module):
def __init__(self):
super(Mask_Attention, self).__init__()
def forward(self, query, context):
attention = torch.bmm(context, query.transpose(1, 2))
mask = attention.new(attention.size()).zero_()
mask[:,:,:] = -np.inf
attention_mask = torch.where(attention==0, mask, attention)
attention_mask = torch.nn.functional.softmax(attention_mask, dim=-1)
mask_zero = attention.new(attention.size()).zero_()
final_attention = torch.where(attention_mask!=attention_mask, mask_zero, attention_mask)
context_vec = torch.bmm(final_attention, query)
return context_vec
解决了dot-product attention随维度增长而剧增、导致softmax取值集中、梯度变小的问题(其实我没看懂这是为啥)







融合法律文本结构信息的刑事案件判决预测(下载自知网)
大致来说是输入两个矩阵(以下文本中是“法律文本”和“案情描述”),分别得到两个矩阵与对方交互后得到的结果,于是实现了各矩阵获得对方矩阵信息的效果

soft attention:传统attention,可被嵌入到模型中去进行训练并传播梯度
hard attention:不计算所有输出,依据概率对encoder的输出采样,在反向传播时需采用蒙特卡洛进行梯度估计
global attention:传统attention,对所有encoder输出进行计算
local attention:介于soft和hard之间,会预测一个位置并选取一个窗口进行计算
Hierarchical Attention Networks for Document Classification ↩︎
LeSICiN: A Heterogeneous Graph-based Approach for Automatic Legal Statute Identification from Indian Legal Documents
可参考我写的博文:Re6:读论文 LeSICiN: A Heterogeneous Graph-based Approach for Automatic Legal Statute Identification fro ↩︎
MAGNN: Metapath Aggregated Graph Neural Network for Heterogeneous Graph Embedding ↩︎
An Element-aware Multi-representation Model for Law Article Prediction ↩︎
Augmenting Legal Judgment Prediction with Contrastive Case Relations ↩︎