nlp系列(7)三元组识别(Bi-LSTM+CRF)pytorch

模型介绍

在实体识别中:使用了Bert模型,CRF模型

在关系识别中:使用了Bert模型的输出与实体掩码,进行一系列变化,得到关系

Bert模型介绍可以查看这篇文章:nlp系列(2)文本分类(Bert)pytorch_bert文本分类_牧子川的博客-CSDN博客

CRF模型介绍可以查看这篇文章:

nlp系列(6)文本实体识别(Bi-LSTM+CRF)pytorch_牧子川的博客-CSDN博客

模型结构

画了一个简易图

数据介绍

数据网址:​​​​​​https://github.com/buppt//raw/master/data/people-relation/train.txticon-default.png?t=N6B9https://github.com/buppt//raw/master/data/people-relation/train.txt

实体1  实体2  关系 文本

模型准备

将处理的数据通过bert模型计算得到两个实体的权重,然后送入到CRF模型计算两个实体损失,然后借鉴Bert模型的掩码,将bert的输出与实体掩码及其计算,得到关系的损失,将两个损失相加,得到模型的总损失。

    def compute_loss(self, input_ids, attention_mask, tag_ids, sub_mask, obj_mask, labels, real_lengths):
        hidden_output, pooled_output = self.get_features(input_ids, attention_mask)
        feats = self.hidden2tag(hidden_output)
        total_scores = self.get_total_scores(feats, real_lengths)
        gold_score = self.get_golden_scores(feats, tag_ids, real_lengths)
        ner_loss = torch.mean(total_scores - gold_score)
        relation_logits = self.get_relation_logit(pooled_output, hidden_output, sub_mask, obj_mask)
        relation_loss = self.criterion(relation_logits, labels)
        return ner_loss + relation_loss

模型预测

文本:
除演艺事业外,李冰冰热心公益,发起并亲自参与多项环保慈善活动,积极投身其中,身体力行担起了回馈社会的责任于02年出演《少年包青天》,进入大家视线
预测结果:
少年包青天 - 主演 - 李冰冰
=========================================
文本:
马志舟,1907年出生,陕西三原人,汉族,中国共产党,任红四团第一连连长,1933年逝世
预测结果:
马志舟 - 国籍 - 中国
马志舟 - 出生日期 - 1907年
马志舟 - 民族 - 汉族
马志舟 - 出生地 - 陕西三原 

源码获取

Bert+CRF 三元组识别icon-default.png?t=N6B9https://github.com/mzc421/Pytorch-NLP/tree/master/11-Bert%2BCRF%20%E4%B8%89%E5%85%83%E7%BB%84%E8%AF%86%E5%88%AB硬性的标准其实限制不了无限可能的我们,所以啊!少年们加油吧!

猜你喜欢

转载自blog.csdn.net/qq_48764574/article/details/132344244
今日推荐