当前位置:   article > 正文

从源码解析 Bert 的 BertPooler 模块_bert pooler

bert pooler

前文链接:

  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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

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]位置对应的输出

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/一键难忘520/article/detail/772222
推荐阅读
相关标签
  

闽ICP备14008679号