从源码解析 Bert 的 BertPooler 模块

31 篇文章 3 订阅
23 篇文章 11 订阅

前文链接:

  1. 从源码层面,深入理解 Bert 框架
  2. 从源码解析 Bert 的 Embedding 模块
  3. 从源码解析 Bert 的 BertEncoder 模块

以上文章解析了Bert的BertEmbedding、BertEncoder模块,接下来分析bert的第三个重要模块 BertPooler;
BertPooler模块本质上就是一个全连接层网络,或者说一个分类器;BertPooler模块接在bert的堆叠encoder层后,主要用于解决序列级的NLP任务

BertPooler模块源码

class BertPooler(nn.Module):
    def __init__(self, config):
        super(BertPooler, self).__init__()
        self.dense = nn.Linear(config.hidden_size, config.hidden_size)
        self.activation = nn.Tanh()

    def forward(self, hidden_states):
        # We "pool" the model by simply taking the hidden state corresponding
        # to the first token.
        first_token_tensor = hidden_states[:, 0]
        pooled_output = self.dense(first_token_tensor)
        pooled_output = self.activation(pooled_output)
        return pooled_output

1. __ init __(self, config)函数

__ init __(self, config)函数根据配置文件里的信息确定了全连接层网络的隐含层节点个数,并且定义了网络的激活函数为 Tanh() 函数

2. forward(self, hidden_states)函数

forward()函数的目的就是将BertEncoder模块得到数据放入__init__()函数定义好好的分类器中,并将分类器的结果返回

这里着重解释一下这行代码

first_token_tensor = hidden_states[:, 0]

这句代码的作用是:使BertPooler模块的全连接层只接收BertEncoder模块中第一个token([CLS])对应的输出,因为BertPooler模块用于解决序列级任务,而序列级任务只会用到[CLS]位置对应的输出

  • 6
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

energy_百分百

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值