NLP-文本分类:Bert文本分类(fine-tuning)【一分类(MSELoss)、多分类(CrossEntropyLoss)、多标签分类(BCEWithLogitsLoss)】

在这里插入图片描述

二、Bert源码(BertForSequenceClassification)

源码位置:\transformers\models\bert\modeling_bert.py


@add_start_docstrings(
    """
    Bert Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
    output) e.g. for GLUE tasks.
    """,
    BERT_START_DOCSTRING,
)
class BertForSequenceClassification(BertPreTrainedModel):
    def __init__(self, config):
        super().__init__(config)
        self.num_labels = config.num_labels
        self.config = config

        self.bert = BertModel(config)
        classifier_dropout = (
            config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
        )
        self.dropout = nn.Dropout(classifier_dropout)
        self.classifier = nn.Linear(config.hidden_size, config.num_labels)

        # Initialize weights and apply final processing
        self.post_init()

    @add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
    @add_code_sample_docstrings(
        processor_class=_TOKENIZER_FOR_DOC,
        checkpoint=_CHECKPOINT_FOR_DOC,
        output_type=SequenceClassifierOutput,
        config_class=_CONFIG_FOR_DOC,
    )
    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,
    ):
        r"""
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
        """
        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:
            if self.config.problem_type is None:
                if self.num_labels == 1:
                    self.config.problem_type = "regression"
                elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
                    self.config.problem_type = "single_label_classification"
                else:
                    self.config.problem_type = "multi_label_classification"

            if self.config.problem_type == "regression":
                loss_fct = MSELoss()
                if self.num_labels == 1:
                    loss = loss_fct(logits.squeeze(), labels.squeeze())
                else:
                    loss = loss_fct(logits, labels)
            elif self.config.problem_type == "single_label_classification":
                loss_fct = CrossEntropyLoss()
                loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
            elif self.config.problem_type == "multi_label_classification":
                loss_fct = BCEWithLogitsLoss()
                loss = loss_fct(logits, 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,
        )

We will adapt BertForSequenceClassification class to cater for multi-label classification.

class BertForMultiLabelSequenceClassification(PreTrainedBertModel):
    """BERT model for classification.
    This module is composed of the BERT model with a linear layer on top of
    the pooled output.
    """
    def __init__(self, config, num_labels=2):
        super(BertForMultiLabelSequenceClassification, self).__init__(config)
        self.num_labels = num_labels
        self.bert = BertModel(config)
        self.dropout = torch.nn.Dropout(config.hidden_dropout_prob)
        self.classifier = torch.nn.Linear(config.hidden_size, num_labels)
        self.apply(self.init_bert_weights)

    def forward(self, input_ids, token_type_ids=None, attention_mask=None, labels=None):
        _, pooled_output = self.bert(input_ids, token_type_ids, attention_mask, output_all_encoded_layers=False)
        pooled_output = self.dropout(pooled_output)
        logits = self.classifier(pooled_output)

        if labels is not None:
            loss_fct = BCEWithLogitsLoss()
            loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1, self.num_labels))
            return loss
        else:
            return logits
        
    def freeze_bert_encoder(self):
        for param in self.bert.parameters():
            param.requires_grad = False
    
    def unfreeze_bert_encoder(self):
        for param in self.bert.parameters():
            param.requires_grad = True

The primary change here is the usage of Binary cross-entropy with logits (BCEWithLogitsLoss) loss function instead of vanilla cross-entropy loss (CrossEntropyLoss) that is used for multiclass classification. Binary cross-entropy loss allows our model to assign independent probabilities to the labels.

The model summary is shows the layers of the model alongwith their dimensions.

BertForMultiLabelSequenceClassification(
  (bert): BertModel(
    (embeddings): BertEmbeddings(
      (word_embeddings): Embedding(28996, 768)
      (position_embeddings): Embedding(512, 768)
      (token_type_embeddings): Embedding(2, 768)
      (LayerNorm): FusedLayerNorm(torch.Size([768]), eps=1e-12, elementwise_affine=True)
      (dropout): Dropout(p=0.1)
    )
    (encoder): BertEncoder(
      (layer): ModuleList(
#       12 BertLayers
        (11): BertLayer(
          (attention): BertAttention(
            (self): BertSelfAttention(
              (query): Linear(in_features=768, out_features=768, bias=True)
              (key): Linear(in_features=768, out_features=768, bias=True)
              (value): Linear(in_features=768, out_features=768, bias=True)
              (dropout): Dropout(p=0.1)
            )
            (output): BertSelfOutput(
              (dense): Linear(in_features=768, out_features=768, bias=True)
              (LayerNorm): FusedLayerNorm(torch.Size([768]), eps=1e-12, elementwise_affine=True)
              (dropout): Dropout(p=0.1)
            )
          )
          (intermediate): BertIntermediate(
            (dense): Linear(in_features=768, out_features=3072, bias=True)
          )
          (output): BertOutput(
            (dense): Linear(in_features=3072, out_features=768, bias=True)
            (LayerNorm): FusedLayerNorm(torch.Size([768]), eps=1e-12, elementwise_affine=True)
            (dropout): Dropout(p=0.1)
          )
        )
      )
    )
    (pooler): BertPooler(
      (dense): Linear(in_features=768, out_features=768, bias=True)
      (activation): Tanh()
    )
  )
  (dropout): Dropout(p=0.1)
  (classifier): Linear(in_features=768, out_features=6, bias=True)
)
  • BertEmbeddings: Input embedding layer
  • BertEncoder: The 12 BERT attention layers
  • Classifier: Our multi-label classifier with out_features=6, each corresponding to our 6 labels

Evaluation Metrics

We adapted the accuracy metric function to include a threshold, which is set to 0.5 as default.

在这里插入代码片



参考资料:
Multi-label Text Classification using BERT – The Mighty Transformer
https://github.com/huggingface/transformers
Bert文本分类(fine-tuning)
干货 | BERT fine-tune 终极实践教程
Bert文本分类实践(一):实现一个简单的分类模型
【NLP】Bert文本分类
二分类问题:基于BERT的文本分类实践!附完整代码
NLP(二十)利用BERT实现文本二分类
二分类、多分类与多标签问题的区别及对应损失函数的选择

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
BERT是目前自然语言处理领域最先进的模型之一,拥有强大的语言理解能力和处理文本任务的能力。其中BERT分类文本分类的应用广泛,可以用于情感分析、垃圾邮件过滤、新闻分类等。 在实现BERT分类文本分类时,需要完成以下步骤: 1.数据预处理:将原始文本数据进行清洗、分词、标注等操作,将其转换为计算机能够处理的数字形式。 2.模型构建:使用BERT预训练模型作为基础,将其Fine-tuning到目标任务上,生成一个新的分类模型。 3.模型训练:使用标注好的训练集对模型进行训练,通过反向传播算法不断调整模型参数,提高模型的分类精度。 4.模型评估:使用验证集和测试集对模型进行验证和评估,选择最优模型。 下面附上一份BERT分类文本分类的Python源码,供参考: ``` import torch import torch.nn as nn from transformers import BertModel, BertTokenizer class BertClassifier(nn.Module): def __init__(self, num_classes): super(BertClassifier, self).__init__() self.bert = BertModel.from_pretrained('bert-base-chinese') self.dropout = nn.Dropout(0.1) self.fc = nn.Linear(self.bert.config.hidden_size, num_classes) def forward(self, input_ids, attention_mask): outputs = self.bert(input_ids=input_ids, attention_mask=attention_mask) pooled_output = outputs[1] # 获取[CLS]对应的向量作为分类 logits = self.fc(self.dropout(pooled_output)) return logits tokenizer = BertTokenizer.from_pretrained('bert-base-chinese') model = BertClassifier(num_classes=2) optimizer = torch.optim.AdamW(model.parameters(), lr=1e-5) loss_fn = nn.CrossEntropyLoss() def train(model, optimizer, loss_fn, train_dataset, val_dataset, epochs=5): for epoch in range(epochs): model.train() for step, batch in enumerate(train_dataset): input_ids = batch['input_ids'].to(device) attention_mask = batch['attention_mask'].to(device) labels = batch['label'].to(device) optimizer.zero_grad() logits = model(input_ids, attention_mask) loss = loss_fn(logits, labels) loss.backward() optimizer.step() if step % 100 == 0: print(f"Epoch:{epoch}, Step:{step}, Loss:{loss}") model.eval() correct = 0 total = 0 with torch.no_grad(): for batch in val_dataset: input_ids = batch['input_ids'].to(device) attention_mask = batch['attention_mask'].to(device) labels = batch['label'].to(device) logits = model(input_ids, attention_mask) pred = torch.argmax(logits, dim=-1) correct += (pred == labels).sum().item() total += labels.size(0) acc = correct / total print(f"Epoch:{epoch}, Val Acc:{acc}") device = torch.device("cuda" if torch.cuda.is_available() else "cpu") num_classes = 2 # 根据具体任务设定 train_dataset = # 根据具体情况构建训练集dataset val_dataset = # 根据具体情况构建验证集dataset train(model=model, optimizer=optimizer, loss_fn=loss_fn, train_dataset=train_dataset, val_dataset=val_dataset, epochs=5) ``` 在该源码中,我们基于BERT预训练模型和PyTorch框架构建了一个多分类模型。该模型可以通过Fine-tuning到不同的分类任务上,实现高精度的多分类文本分类

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值