paddlepaddle中在BiLstm后添加Attention

paddlepaddle中实现bilstm比较简单, 但如何实现bilstm+attention目前没搜到,参考这篇博文(https://aistudio.baidu.com/aistudio/projectdetail/122459),我自己写了一个,不知道对不对,反正能跑通。以下除Attention层外的代码来自于百度Ai Stuio中新出的EasyDL专业版(https://ai.baidu.com/easydl/pro)中的代码。

      # embedding layer
        emb = fluid.layers.embedding(
            input=unpad_data,
            size=[dict_dim, emb_dim],
            param_attr=fluid.ParamAttr(learning_rate=emb_lr))
            
        # bilstm layer
        fc0 = fluid.layers.fc(input=emb, size=hid_dim * 4)
        rfc0 = fluid.layers.fc(input=emb, size=hid_dim * 4)
        lstm_h, c = fluid.layers.dynamic_lstm(
            input=fc0, size=hid_dim * 4, is_reverse=False)
        rlstm_h, c = fluid.layers.dynamic_lstm(
            input=rfc0, size=hid_dim * 4, is_reverse=True)
        
        # concat layer
        lstm_h_concat = fluid.layers.concat(input=[lstm_h, rlstm_h], axis=1)
        lstm_h_tanh = fluid.layers.tanh(lstm_h_concat)
        
        #attenion layer
        hidlayer_state = fluid.layers.fc(input=lstm_h_tanh, size=hid_dim*8, bias_attr=False)
        attention_weights = fluid.layers.fc(input=hidlayer_state, size=1, bias_attr=False)
        attention_weights = fluid.layers.sequence_softmax(input=attention_weights)
        weigths_reshape = fluid.layers.reshape(x=attention_weights, shape=[-1])
        scaled = fluid.layers.elementwise_mul(x=lstm_h_concat, y=weigths_reshape, axis=0)
        lstm_sum = fluid.layers.sequence_pool(input=scaled, pool_type='sum')
        
        # full connect layer
        fc1 = fluid.layers.fc(input=lstm_sum, size=hid_dim2, act='tanh')
        # softmax layer
        predictions = fluid.layers.fc(input=fc1, size=num_labels, act='softmax')

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值