jupyter快速实现单标签及多标签多分类的文本分类BERT模型

jupyter实现pytorch版BERT(单标签分类版)

nlp-notebooks/Text classification with BERT in PyTorch.ipynb

通过改写上述代码,实现多标签分类

参考解决方案 ,我选择的解决方案是继承BertForSequenceClassification并改写,即将上述代码的ln [9] 改为以下内容:

python 复制代码
from transformers.modeling_bert import BertForSequenceClassification
from transformers.modeling_outputs import SequenceClassifierOutput

class BertForMultilabelSequenceClassification(BertForSequenceClassification):
   def __init__(self, config):
     super().__init__(config)

   def forward(self,
       input_ids=None,
       attention_mask=None,
       token_type_ids=None,
       position_ids=None,
       head_mask=None,
       inputs_embeds=None,
       labels=None,
       output_attentions=None,
       output_hidden_states=None,
       return_dict=None):
       return_dict = return_dict if return_dict is not None else self.config.use_return_dict

       outputs = self.bert(input_ids,
           attention_mask=attention_mask,
           token_type_ids=token_type_ids,
           position_ids=position_ids,
           head_mask=head_mask,
           inputs_embeds=inputs_embeds,
           output_attentions=output_attentions,
           output_hidden_states=output_hidden_states,
           return_dict=return_dict)

       pooled_output = outputs[1]
       pooled_output = self.dropout(pooled_output)
       logits = self.classifier(pooled_output)

       loss = None
       if labels is not None:
           loss_fct = torch.nn.BCEWithLogitsLoss()
           loss = loss_fct(logits.view(-1, self.num_labels), 
                           labels.float().view(-1, self.num_labels))

       if not return_dict:
           output = (logits,) + outputs[2:]
           return ((loss,) + output) if loss is not None else output

       return SequenceClassifierOutput(loss=loss,
           logits=logits,
           hidden_states=outputs.hidden_states,
           attentions=outputs.attentions)
           
model = BertForMultilabelSequenceClassification.from_pretrained(BERT_MODEL, num_labels = len(label2idx))
model.to(device)
相关推荐
Rabbit_QL9 天前
【BPE实战】从零实现 BPE 分词器:训练、编码与解码
python·算法·nlp
这张生成的图像能检测吗9 天前
(论文速读)XLNet:语言理解的广义自回归预训练
人工智能·计算机视觉·nlp·注意力机制
肾透侧视攻城狮9 天前
《NLP核心能力构建:从传统统计到上下文感知的文本表示演进之路》
人工智能·nlp·fasttext·word2vec/glove·elmo/n-gram/词袋·doc2vec/lda·句向量与文档向量
陈天伟教授9 天前
人工智能应用- 预测化学反应:08. 基于 BERT 的化学反应分类
人工智能·深度学习·bert
码农三叔9 天前
(3-2-01)视觉感知:目标检测与分类
人工智能·目标检测·分类·机器人·人机交互·人形机器人
开发者小天9 天前
python中使用jupyter notebook 绘制正态分布直方图 密度图 小提琴图 模仿企鹅喙长分布图
开发语言·python·jupyter
DeepModel10 天前
【分类算法】ID3算法超详细讲解
分类·分类算法
向哆哆10 天前
粉尘环境分类检测千张图数据集(适用YOLO系列)(已标注+划分/可直接训练)
yolo·分类·数据挖掘
换个名字就很好10 天前
cursor安装和编程
nlp