×

PyTorch教程16.5之自然语言推理:使用注意力

消耗积分:0 | 格式:pdf | 大小:0.34 MB | 2023-06-05

石胜厚

分享资料个

我们在16.4 节介绍了自然语言推理任务和 SNLI 数据集鉴于许多基于复杂和深层架构的模型, Parikh等人。( 2016 )提出用注意力机制解决自然语言推理,并将其称为“可分解注意力模型”。这导致模型没有循环层或卷积层,在 SNLI 数据集上以更少的参数获得了当时最好的结果。在本节中,我们将描述和实现这种用于自然语言推理的基于注意力的方法(使用 MLP),如图 16.5.1所示。

//www.hzfubeitong.com/file/web2/M00/AA/48/pYYBAGR9PMOARtlZAAKKcqUaWlU524.svg

图 16.5.1本节将预训练的 GloVe 提供给基于注意力和 MLP 的架构以进行自然语言推理。

16.5.1。该模型

比保留前提和假设中标记的顺序更简单的是,我们可以将一个文本序列中的标记与另一个文本序列中的每个标记对齐,反之亦然,然后比较和聚合这些信息以预测前提和假设之间的逻辑关系。类似于机器翻译中源句和目标句之间的 token 对齐,前提和假设之间的 token 对齐可以通过注意力机制巧妙地完成。

//www.hzfubeitong.com/file/web2/M00/AA/48/pYYBAGR9PMaALy2sAASFcYMHqHw144.svg

图 16.5.2使用注意机制的自然语言推理。

图 16.5.2描述了使用注意机制的自然语言推理方法。在高层次上,它由三个联合训练的步骤组成:参与、比较和聚合。我们将在下面逐步说明它们。

import torch
from torch import nn
from torch.nn import functional as F
from d2l import torch as d2l
from mxnet import gluon, init, np, npx
from mxnet.gluon import nn
from d2l import mxnet as d2l

npx.set_np()

16.5.1.1。出席

第一步是将一个文本序列中的标记与另一个序列中的每个标记对齐。假设前提是“我确实需要睡觉”,假设是“我累了”。由于语义相似,我们可能希望将假设中的“i”与前提中的“i”对齐,并将假设中的“tired”与前提中的“sleep”对齐。同样,我们可能希望将前提中的“i”与假设中的“i”对齐,并将前提中的“需要”和“睡眠”与假设中的“疲倦”对齐。请注意,使用加权平均的这种对齐是软的,其中理想情况下较大的权重与要对齐的标记相关联。为了便于演示,图 16.5.2以硬方式显示了这种对齐方式

现在我们更详细地描述使用注意机制的软对齐。表示为 A=(a1,…,am)B=(b1,…,bn)前提和假设,其标记数为mn,分别在哪里 ai,bj∈Rd (i=1,…,m,j=1,…,n) 是一个d维词向量。对于软对齐,我们计算注意力权重 eij∈R作为

(16.5.1)eij=f(ai)⊤f(bj),

哪里的功能f是在以下函数中定义的 MLP mlp的输出维度fnum_hiddens由的参数指定 mlp

def mlp(num_inputs, num_hiddens, flatten):
  net = []
  net.append(nn.Dropout(0.2))
  net.append(nn.Linear(num_inputs, num_hiddens))
  net.append(nn.ReLU())
  if flatten:
    net.append(nn.Flatten(start_dim=1))
  net.append(nn.Dropout(0.2))
  net.append(nn.Linear(num_hiddens, num_hiddens))
  net.append(nn.ReLU())
  if flatten:
    net.append(nn.Flatten(start_dim=1))
  return nn.Sequential(*net)
def mlp(num_hiddens, flatten):
  net = nn.Sequential()
  net.add(nn.Dropout(0.2))
  net.add(nn.Dense(num_hiddens, activation='relu', flatten=flatten))
  net.add(nn.Dropout(0.2))
  net.add(nn.Dense(num_hiddens, activation='relu', flatten=flatten))
  return net

需要强调的是,在(16.5.1) f接受输入aibj分开而不是将它们中的一对一起作为输入。这种分解技巧只会导致m+n的应用(线性复杂度) f而不是mn应用程序(二次复杂度)。

对(16.5.1)中的注意力权重进行归一化,我们计算假设中所有标记向量的加权平均值,以获得与由索引的标记软对齐的假设表示i在前提下:

(16.5.2)βi=∑j=1nexp⁡(e

声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表德赢Vwin官网 网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉

评论(0)
发评论

下载排行榜

全部0条评论

快来发表一下你的评论吧 !

'+ '

'+ '

'+ ''+ '
'+ ''+ ''+ '
'+ ''+ '' ); $.get('/article/vipdownload/aid/'+webid,function(data){ if(data.code ==5){ $(pop_this).attr('href',"//www.hzfubeitong.com/m/login/index.html"); return false } if(data.code == 2){ //跳转到VIP升级页面 window.location.href="https://m.elecfans.com/vip/index?aid=" + webid return false } //是会员 if (data.code > 0) { $('body').append(htmlSetNormalDownload); var getWidth=$("#poplayer").width(); $("#poplayer").css("margin-left","-"+getWidth/2+"px"); $('#tips').html(data.msg) $('.download_confirm').click(function(){ $('#dialog').remove(); }) } else { var down_url = $('#vipdownload').attr('data-url'); isBindAnalysisForm(pop_this, down_url, 1) } }); }); //是否开通VIP $.get('/article/vipdownload/aid/'+webid,function(data){ if(data.code == 2 || data.code ==5){ //跳转到VIP升级页面 $('#vipdownload>span').text("开通VIP 免费下载") return false }else{ // 待续费 if(data.code == 3) { vipExpiredInfo.ifVipExpired = true vipExpiredInfo.vipExpiredDate = data.data.endoftime } $('#vipdownload .icon-vip-tips').remove() $('#vipdownload>span').text("VIP免积分下载") } }); }).on("click",".download_cancel",function(){ $('#dialog').remove(); }) var setWeixinShare={};//定义默认的微信分享信息,页面如果要自定义分享,直接更改此变量即可 if(window.navigator.userAgent.toLowerCase().match(/MicroMessenger/i) == 'micromessenger'){ var d={ title:'PyTorch教程16.5之自然语言推理:使用注意力',//标题 desc:$('[name=description]').attr("content"), //描述 imgUrl:'https://'+location.host+'/static/images/ele-logo.png',// 分享图标,默认是logo link:'',//链接 type:'',// 分享类型,music、video或link,不填默认为link dataUrl:'',//如果type是music或video,则要提供数据链接,默认为空 success:'', // 用户确认分享后执行的回调函数 cancel:''// 用户取消分享后执行的回调函数 } setWeixinShare=$.extend(d,setWeixinShare); $.ajax({ url:"//www.hzfubeitong.com/app/wechat/index.php?s=Home/ShareConfig/index", data:"share_url="+encodeURIComponent(location.href)+"&format=jsonp&domain=m", type:'get', dataType:'jsonp', success:function(res){ if(res.status!="successed"){ return false; } $.getScript('https://res.wx.qq.com/open/js/jweixin-1.0.0.js',function(result,status){ if(status!="success"){ return false; } var getWxCfg=res.data; wx.config({ //debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。 appId:getWxCfg.appId, // 必填,公众号的唯一标识 timestamp:getWxCfg.timestamp, // 必填,生成签名的时间戳 nonceStr:getWxCfg.nonceStr, // 必填,生成签名的随机串 signature:getWxCfg.signature,// 必填,签名,见附录1 jsApiList:['onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ','onMenuShareWeibo','onMenuShareQZone'] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2 }); wx.ready(function(){ //获取“分享到朋友圈”按钮点击状态及自定义分享内容接口 wx.onMenuShareTimeline({ title: setWeixinShare.title, // 分享标题 link: setWeixinShare.link, // 分享链接 imgUrl: setWeixinShare.imgUrl, // 分享图标 success: function () { setWeixinShare.success; // 用户确认分享后执行的回调函数 }, cancel: function () { setWeixinShare.cancel; // 用户取消分享后执行的回调函数 } }); //获取“分享给朋友”按钮点击状态及自定义分享内容接口 wx.onMenuShareAppMessage({ title: setWeixinShare.title, // 分享标题 desc: setWeixinShare.desc, // 分享描述 link: setWeixinShare.link, // 分享链接 imgUrl: setWeixinShare.imgUrl, // 分享图标 type: setWeixinShare.type, // 分享类型,music、video或link,不填默认为link dataUrl: setWeixinShare.dataUrl, // 如果type是music或video,则要提供数据链接,默认为空 success: function () { setWeixinShare.success; // 用户确认分享后执行的回调函数 }, cancel: function () { setWeixinShare.cancel; // 用户取消分享后执行的回调函数 } }); //获取“分享到QQ”按钮点击状态及自定义分享内容接口 wx.onMenuShareQQ({ title: setWeixinShare.title, // 分享标题 desc: setWeixinShare.desc, // 分享描述 link: setWeixinShare.link, // 分享链接 imgUrl: setWeixinShare.imgUrl, // 分享图标 success: function () { setWeixinShare.success; // 用户确认分享后执行的回调函数 }, cancel: function () { setWeixinShare.cancel; // 用户取消分享后执行的回调函数 } }); //获取“分享到腾讯微博”按钮点击状态及自定义分享内容接口 wx.onMenuShareWeibo({ title: setWeixinShare.title, // 分享标题 desc: setWeixinShare.desc, // 分享描述 link: setWeixinShare.link, // 分享链接 imgUrl: setWeixinShare.imgUrl, // 分享图标 success: function () { setWeixinShare.success; // 用户确认分享后执行的回调函数 }, cancel: function () { setWeixinShare.cancel; // 用户取消分享后执行的回调函数 } }); //获取“分享到QQ空间”按钮点击状态及自定义分享内容接口 wx.onMenuShareQZone({ title: setWeixinShare.title, // 分享标题 desc: setWeixinShare.desc, // 分享描述 link: setWeixinShare.link, // 分享链接 imgUrl: setWeixinShare.imgUrl, // 分享图标 success: function () { setWeixinShare.success; // 用户确认分享后执行的回调函数 }, cancel: function () { setWeixinShare.cancel; // 用户取消分享后执行的回调函数 } }); }); }); } }); } function openX_ad(posterid, htmlid, width, height) { if ($(htmlid).length > 0) { var randomnumber = Math.random(); var now_url = encodeURIComponent(window.location.href); var ga = document.createElement('iframe'); ga.src = 'https://www1.elecfans.com/www/delivery/myafr.php?target=_blank&cb=' + randomnumber + '&zoneid=' + posterid+'&prefer='+now_url; ga.width = width; ga.height = height; ga.frameBorder = 0; ga.scrolling = 'no'; var s = $(htmlid).append(ga); } } openX_ad(828, '#berry-300', 300, 250);