当前位置:   article > 正文

动手实践bert+BiLstm+crf_bert+bi-lstm+crf

bert+bi-lstm+crf

网上大部分都是使用ChinaPeoplesDailyNerCorpus语料做的,真正应用到自已的语料和需求中还是有一些坑,这里整理记录一下

首先明确语料需要处理成什么格式,贴图理解一下
在这里插入图片描述
这里面需要搞清楚几点,我们的语料最小粒度是字级别的,然后每句话结束会有一个空行(当年踩过的坑),后面的标记简单科普一下,专业人士直接跳过,大O表示非实体,B-ORD表示机构开头第一个字,I-ORD表示中间,有些预料可能会有结束标记,这里只使用了开头和中间,当然你可能还需要识别人名(B-PER, I-PER),地名(B-LOC, I-LOC),同理。

接下来就要考虑如何将一段话或者一篇文章处理成这种格式了
这里参考了一篇文章https://www.cnblogs.com/combfish/p/7830807.html其中的代码直接贴在下面了,不想看的可以直接跳过看后面分析

import re
 
# txt2ner_train_data turn label str into ner trainable data
# s :labeled str  eg.'我来到[@1999年#YEAR*]的[@上海#LOC*]的[@东华大学#SCHOOL*]'
# save_path: ner_trainable_txt name
def str2ner_train_data(s,save_path):
    ner_data = []
    result_1 = re.finditer(r'\[\@', s)
    result_2 = re.finditer(r'\*\]', s)
    begin = []
    end = []
    for each in result_1:
        begin.append(each.start())
    for each in result_2:
        end.append(each.end())
    assert len(begin) == len(end)
    i = 0
    j = 0
    while i < len(s):
        if i not in begin:
            ner_data.append([s[i], 0])
            i = i + 1
        else:
            ann = s[i + 2:end[j] - 2]
            entity, ner = ann.rsplit('#')
            if (len(entity) == 1):
                ner_data.append([entity, 'S-' + ner])
            else:
                if (len(entity) == 2):
                    ner_data.append([entity[0], 'B-' + ner])
                    ner_data.append([entity[1], 'E-' + ner])
                else:
                    ner_data.append([entity[0], 'B-' + ner])
                    for n in range(1, len(entity) - 1):
                        ner_data.append([entity[n], 'I-' + ner])
                    ner_data.append([entity[-1], 'E-' + ner])
 
            i = end[j]
            j = j + 1
 
    f = open(save_path, 'w', encoding='utf-8')
    for each in ner_data:
        f.write(each[0] + ' ' + str(each[1]))
        f.write('\n')
    f.close(
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/秋刀鱼在做梦/article/detail/912281
推荐阅读
相关标签
  

闽ICP备14008679号