【最新试验】用预训练模型Roberta做序列标注_自然语言处理_使用RobertaForTokenClassification做命名实体识别pytorch版

有了bert,roberta还会远吗,目前pytorch transformer上已经放出了bertForTokenClassification

然而,在工业界前进的我们,不能忍受如此慢速的更新

于是我们自己写好了robertaForTokenClassicification类,准备使用了!

以下是代码

 


class RobertaForTokenClassification(BertPreTrainedModel):
    r"""
        **labels**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``:
            Labels for computing the token classification loss.
            Indices should be in ``[0, ..., config.num_labels - 1]``.

    Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs:
        **loss**: (`optional`, returned when ``labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``:
            Classification loss.
        **scores**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length, config.num_labels)``
            Classification scores (before SoftMax).
        **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)
            list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)
            of shape ``(batch_size, sequence_length, hidden_size)``:
            Hidden-states of the model at the output of each layer plus the initial embedding outputs.
        **attentions**: (`optional`, returned when ``config.output_attentions=True``)
            list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:
            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.

    Examples::

        tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
        model = BertForTokenClassification.from_pretrained('bert-base-uncased')
        input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0)  # Batch size 1
        labels = torch.tensor([1] * input_ids.size(1)).unsqueeze(0)  # Batch size 1
        outputs = model(input_ids, labels=labels)
        loss, scores = outputs[:2]

    """
    def __init__(self, config):
        super(RobertaForTokenClassification, self).__init__(config)
        self.num_labels = config.num_labels
        print('we have labels = ',self.num_labels)
        self.roberta = RobertaModel(config)
        self.dropout = nn.Dropout(config.hidden_dropout_prob)
        self.classifier = nn.Linear(config.hidden_size, self.num_labels)

        self.apply(self.init_weights)

    def forward(self, input_ids, token_type_ids=None, attention_mask=None, labels=None,
                position_ids=None, head_mask=None):
        outputs = self.roberta(input_ids, position_ids=position_ids, token_type_ids=token_type_ids,
                            attention_mask=attention_mask, head_mask=head_mask)
        sequence_output = outputs[0]
        sequence_output = self.dropout(sequence_output)
        logits = self.classifier(sequence_output)

        outputs = (logits,) + outputs[2:]  # add hidden states and attention if they are here
        if labels is not None:
            loss_fct = CrossEntropyLoss()
            # Only keep active parts of the loss
            if attention_mask is not None:
                #(bs,seq length)
                active_loss = attention_mask.view(-1) == 1
                # active loss (400 = bs * seq) True False
                active_logits = logits.view(-1, self.num_labels)[active_loss]
                # active logits shape(213,num_labels)
                active_labels = labels.view(-1)[active_loss]
                # active_labels shape(213)
                loss = loss_fct(active_logits, active_labels)
            else:
                loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
            outputs = (loss,) + outputs

        return outputs  # (loss), scores, (hidden_states), (attentions)
#

跟bert的思路几乎完全一样,感兴趣的小伙伴自行阅读我之前写的博文就行。

 

然后我们很容易的想到后置网络可以接crf,那么针对上面的代码小小改动以下我们就得到了RobertaCrf

 

from torchcrf import CRF
class RobertaCrf(BertPreTrainedModel):

    def __init__(self, config):
        super(RobertaCrf, self).__init__(config)
        self.num_labels = config.num_labels
        print('roberta crf have labels = ',self.num_labels)
        self.roberta = RobertaModel(config)
        self.dropout = nn.Dropout(config.hidden_dropout_prob)
        self.classifier = nn.Linear(config.hidden_size, self.num_labels)
        self.crf_model = CRF(self.num_labels).to('cuda')
        self.apply(self.init_weights)

    def forward(self, input_ids, token_type_ids=None, attention_mask=None, labels=None,
                position_ids=None, head_mask=None):
        outputs = self.roberta(input_ids, position_ids=position_ids, token_type_ids=token_type_ids,
                            attention_mask=attention_mask, head_mask=head_mask)
        sequence_output = outputs[0]
        sequence_output = self.dropout(sequence_output)
        tag_logits = self.classifier(sequence_output)
        logits = self.crf_model.decode(tag_logits.transpose(0, 1))
        outputs = (logits,) + outputs[2:]  # add hidden states and attention if they are here
        active_loss = attention_mask.view(-1)== 1
        reshape_active_loss = active_loss.reshape_as(attention_mask)
        if labels is not None:
            loss = -self.crf_model(tag_logits.transpose(0, 1), labels.transpose(0, 1),reshape_active_loss.transpose(0, 1), reduction='sum')
            outputs = (loss,) + outputs
        # else:
        #     logits = self.crf_model.decode(sequence_output.transpose(0, 1))
        return outputs  # (loss), scores, (hidden_states), (attentions)

 

你可能感兴趣的:(ner,命名实体识别,roberta,roberta,crf)