Attention的学习

Attention的学习,第1张

Attention的学习

简介:

​ 其实attention机制是对于当前状态的生成,对前面的状态的一个关注程度。


通过当前的隐藏状态,去和之前的hidden进行比对,也相当于计算相似度。


(其实代码实现的话,就是一个两个矩阵拼接进行一个Linear,最中终Encoder中会得出hidden个score,每个score对应每个hidden的值,再进行一个点积也相当于加权求和,得出batch个attention的向量,然后通过attention、decoder_input,hidden_state进行拼接再经过一个Linear得出预测值)

参考:https://wmathor.com/index.php/archives/1451/

这个博主b站视频:https://www.bilibili.com/video/BV1op4y1U7ag/

1.Encoder部分
  • encoder部分和传统的seq2seq其实是一样的

  • 经过encoder 会获得两个东西

    1. encoder_output : 是encoder中循环神经网络的最后一层全部的hidden_state
    2. hidden : 是encoder中循环神经网络每层的最后一个hidden

2.Attention部分

Attention分为两部分 :

  1. 计算权重 得出 score

  2. 加权求和 得出 Attention_vector

  • 计算权重:

    公式:
    W e i g h t : a i = a l i g n ( h i , s 0 ) Weight : a_i = align(h_i,s_0) Weight:ai=align(hi,s0)

    具体编码的时候(伪代码):

    energy=tanh(linear(torch.cat(hi,s0),hidden_num))
    a_i = linear(energy,1)
    

    这里会得到seq_len个a ,就是分数,我会经过一个softmax
    s o f t m a x ( a 1 − s e q l e n ) softmax(a_{1-seq_len}) softmax(a1seqlen)

  • 加权求和:

    公式:
    A t t e n t i o n − v e c t o r : c 0 = a 1 h 1 + . . . + a m h m Attention-vector:c_0 = a_1h_1+...+a_mh_m Attentionvector:c0=a1h1+...+amhm

3.Decoder部分

​ 经过前两步 *** 作,我现在拥有的是 s , c , encoder_input

步骤:

  1. 把 c .decoder_input 进行cat拼接,得到input

  2. ,把input,s 传入Decoder的神经网络中,得出output

  3. 最后进行预测,就是一个Linear,这个Linear是output和c进行的一个拼接然后再去作Linear


    )

下面给出伪代码:

input = torch.cat(c , encoder_input)
encoder_output = rnn(input,s)
pre = Linear(encoder_output)

coder_input)
encoder_output = rnn(input,s)
pre = Linear(encoder_output)


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/563909.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-03
下一篇 2022-04-03

发表评论

登录后才能评论

评论列表(0条)

保存