为什么要通过HuggingFace进行序列分类(DistilBertForSequenceClassification)的第一个隐藏状态

问题描述 投票:0回答:1

在通过HuggingFace进行的序列分类的最后几层中,他们采取了用于分类的变压器输出的序列长度的第一个隐藏状态。

hidden_state = distilbert_output[0]  # (bs, seq_len, dim) <-- transformer output
pooled_output = hidden_state[:, 0]  # (bs, dim)           <-- first hidden state
pooled_output = self.pre_classifier(pooled_output)  # (bs, dim)
pooled_output = nn.ReLU()(pooled_output)  # (bs, dim)
pooled_output = self.dropout(pooled_output)  # (bs, dim)
logits = self.classifier(pooled_output)  # (bs, dim)

相对于最后一个,平均甚至是使用Flatten层,采用第一个隐藏状态有什么好处?

time-series sequence tensorflow2.0 text-classification huggingface-transformers
1个回答
0
投票

是的,这与BERT的训练方式直接相关。具体来说,我鼓励您看一下original BERT paper,作者在其中介绍[CLS]标记的含义:

[CLS]是在每个输入示例[...]前面添加的特殊符号。

特别是,它用于分类目的,因此是对分类任务进行任何微调的第一和最简单的选择。您相关的代码片段在做什么,基本上只是在提取此[CLS]令牌。

[不幸的是,Huggingface的库的DistilBERT文档没有明确提及,但是您不得不检查BERT documentation,在其中他们还强调了[CLS]令牌的某些问题,与您的关注类似:

[沿着传销,BERT使用下一句预测(NSP)进行了训练目标,使用[CLS]令牌作为序列近似值。用户可以使用此令牌(使用特殊符号构建的序列中的第一个令牌令牌)以获得序列预测而不是令牌预测。但是,对序列求平均值可能会比使用[CLS]令牌。

© www.soinside.com 2019 - 2024. All rights reserved.