【定义】
CRF++是著名的条件随机场的开源工具,也是目前综合性能最佳的CRF工具,采用C++语言编写而成。其最重要的功能是采用了特征模板。这样就可以自动生成一系列的特征函数,而不用我们自己生成特征函数,我们要做的就是寻找特征,比如词性等。
【安装】
在Windows中CRF++不需要安装,下载解压CRF++0.58文件即可以使用
【语料】
需要注意字与标签之间的分隔符为制表符\t

played VBD O
on IN O
Monday NNP O
( ( O
home NN O
team NN O
in IN O
CAPS NNP O

【特征模板】
模板是使用CRF++的关键,它能帮助我们自动生成一系列的特征函数,而不用我们自己生成特征函数,而特征函数正是CRF算法的核心概念之一。

【训练】



【预测】

【实例】
该语料库一共42000行,每三行为一组,其中,第一行为英语句子,第二行为句子中每个单词的词性,第三行为NER系统的标注,共分4个标注类别:PER(人名),LOC(位置),ORG(组织)以及MISC,其中B表示开始,I表示中间,O表示单字词,不计入NER,sO表示特殊单字词。首先我们将该语料分为训练集和测试集,比例为9:1。

# -*- coding: utf-8 -*-# NER预料train.txt所在的路径
dir = "/Users/Shared/CRF_4_NER/CRF_TEST"with open("%s/train.txt" % dir, "r") as f:sents = [line.strip() for line in f.readlines()]# 训练集与测试集的比例为9:1
RATIO = 0.9
train_num = int((len(sents)//3)*RATIO)# 将文件分为训练集与测试集
with open("%s/NER_train.data" % dir, "w") as g:for i in range(train_num):words = sents[3*i].split('\t')postags = sents[3*i+1].split('\t')tags = sents[3*i+2].split('\t')for word, postag, tag in zip(words, postags, tags):g.write(word+' '+postag+' '+tag+'\n')g.write('\n')with open("%s/NER_test.data" % dir, "w") as h:for i in range(train_num+1, len(sents)//3):words = sents[3*i].split('\t')postags = sents[3*i+1].split('\t')tags = sents[3*i+2].split('\t')for word, postag, tag in zip(words, postags, tags):h.write(word+' '+postag+' '+tag+'\n')h.write('\n')print('OK!')

模板文件template内容如下

# Unigram
U00:%x[-2,0]
U01:%x[-1,0]
U02:%x[0,0]
U03:%x[1,0]
U04:%x[2,0]
U05:%x[-1,0]/%x[0,0]
U06:%x[0,0]/%x[1,0]U10:%x[-2,1]
U11:%x[-1,1]
U12:%x[0,1]
U13:%x[1,1]
U14:%x[2,1]
U15:%x[-2,1]/%x[-1,1]
U16:%x[-1,1]/%x[0,1]
U17:%x[0,1]/%x[1,1]
U18:%x[1,1]/%x[2,1]U20:%x[-2,1]/%x[-1,1]/%x[0,1]
U21:%x[-1,1]/%x[0,1]/%x[1,1]
U22:%x[0,1]/%x[1,1]/%x[2,1]# Bigram
B

训练该数据

crf_learn -c 3.0 template NER_train.data model -t

在测试集上对该模型的预测表现做评估

crf_test -m model NER_test.data > result.txt

使用Python脚本统计预测的准确率

# -*- coding: utf-8 -*-dir = "/Users/Shared/CRF_4_NER/CRF_TEST"with open("%s/result.txt" % dir, "r") as f:sents = [line.strip() for line in f.readlines() if line.strip()]total = len(sents)
print(total)count = 0
for sent in sents:words = sent.split()# print(words)if words[-1] == words[-2]:count += 1print("Accuracy: %.4f" %(count/total))

看看模型在新数据上的识别效果

# -*- coding: utf-8 -*-import os
import nltkdir = "/Users/Shared/CRF_4_NER/CRF_TEST"sentence = "Venezuelan opposition leader and self-proclaimed interim president Juan Guaidó said Thursday he will return to his country by Monday, and that a dialogue with President Nicolas Maduro won't be possible without discussing elections."
#sentence = "Real Madrid's season on the brink after 3-0 Barcelona defeat"
# sentence = "British artist David Hockney is known as a voracious smoker, but the habit got him into a scrape in Amsterdam on Wednesday."
# sentence = "India is waiting for the release of an pilot who has been in Pakistani custody since he was shot down over Kashmir on Wednesday, a goodwill gesture which could defuse the gravest crisis in the disputed border region in years."
# sentence = "Instead, President Donald Trump's second meeting with North Korean despot Kim Jong Un ended in a most uncharacteristic fashion for a showman commander in chief: fizzle."
# sentence = "And in a press conference at the Civic Leadership Academy in Queens, de Blasio said the program is already working."
#sentence = "The United States is a founding member of the United Nations, World Bank, International Monetary Fund."default_wt = nltk.word_tokenize # 分词
words = default_wt(sentence)
print(words)
postags = nltk.pos_tag(words)
print(postags)with open("%s/NER_predict.data" % dir, 'w', encoding='utf-8') as f:for item in postags:f.write(item[0]+' '+item[1]+' O\n')print("write successfully!")os.chdir(dir)
os.system("crf_test -m model NER_predict.data > predict.txt")
print("get predict file!")# 读取预测文件redict.txt
with open("%s/predict.txt" % dir, 'r', encoding='utf-8') as f:sents = [line.strip() for line in f.readlines() if line.strip()]word = []
predict = []for sent in sents:words = sent.split()word.append(words[0])predict.append(words[-1])# print(word)
# print(predict)# 去掉NER标注为O的元素
ner_reg_list = []
for word, tag in zip(word, predict):if tag != 'O':ner_reg_list.append((word, tag))# 输出模型的NER识别结果
print("NER识别结果:")
if ner_reg_list:for i, item in enumerate(ner_reg_list):if item[1].startswith('B'):end = i+1while end <= len(ner_reg_list)-1 and ner_reg_list[end][1].startswith('I'):end += 1ner_type = item[1].split('-')[1]ner_type_dict = {'PER': 'PERSON: ','LOC': 'LOCATION: ','ORG': 'ORGANIZATION: ','MISC': 'MISC: '}print(ner_type_dict[ner_type], ' '.join([item[0] for item in ner_reg_list[i:end]]))

使用CRF++实现命名实体识别相关推荐

  1. 知识图谱 基于CRF的命名实体识别模型

    基于CRF的命名实体识别模型 条件随机场 CRF ​ 条件随机场 CRF 是在已知一组输入随机变量条件的情况下,输出另一组随机变量的条件概率分布模型:其前提是假设输出随机变量构成马尔可夫随机场:条件随 ...

  2. Python3.7+Tensorflow2.0(TF2)实现Bilstm+mask-self-attention+CRF实现命名实体识别

    一.他说的是对的 前几天看到一篇关于大连理工大学的研三学长的去世新闻,仔细看了他的遗书,很是泪目.他说同样的条件,做出的实验结果是不同的. 在训练我这个模型的时候,深深体会到了这个感受,有时候收敛,有 ...

  3. 【项目实战课】基于BiLSTM+CRF的命名实体识别实战

    欢迎大家来到我们的项目实战课,本期内容是<基于BiLSTM+CRF的命名实体识别实战>.所谓项目课,就是以简单的原理回顾+详细的项目实战的模式,针对具体的某一个主题,进行代码级的实战讲解. ...

  4. 用CRF做命名实体识别——NER系列(三)

    在上一篇文章<用隐马尔可夫模型(HMM)做命名实体识别--NER系列(二)>中,我们使用HMM模型来做命名实体识别,将问题转化为统计概率问题,进行求解.显然,它的效果是非常有限的. 在深度 ...

  5. NLP入门(八)使用CRF++实现命名实体识别(NER)

    CRF与NER简介   CRF,英文全称为conditional random field, 中文名为条件随机场,是给定一组输入随机变量条件下另一组输出随机变量的条件概率分布模型,其特点是假设输出随机 ...

  6. CRF用于命名实体识别(快速上手实现)

    写在前面 最近在看命名实体识别相关的模型,实验室正好有中医典籍文本的命名实体标注数据集,拿来练练构建一个简单的CRF模型,顺便记录下来,代码可以作为一个参考,手中有标注数据集就可以使用这段代码来训练自 ...

  7. 逐行讲解CRF实现命名实体识别(NER)

    文章标题 本文概述 NER介绍 代码详解 任务 导入库 加载数据集 构造特征字典 数据处理 模型训练 模型验证 模型参数 备注 随机搜索RandomizedSearchCV 本文概述 使用sklear ...

  8. PyTorch 高级实战教程:基于 BI-LSTM CRF 实现命名实体识别和中文分词

    20210607 https://blog.csdn.net/u011828281/article/details/81171066 前言:译者实测 PyTorch 代码非常简洁易懂,只需要将中文分词 ...

  9. Pytorch: 命名实体识别: BertForTokenClassification/pytorch-crf

    文章目录 基本介绍 BertForTokenClassification pytorch-crf 实验项目 参考 基本介绍 命名实体识别:命名实体识别任务是NLP中的一个基础任务.主要是从一句话中识别 ...

最新文章

  1. html三列布局中间固定,常见的三列布局(左右固定宽度,中间自适应)
  2. php根据手机号码获取省份
  3. tab使用 TabActivity TabHost Tabspec常用方法
  4. 使用Stackblitz一分钟之内创建一个Angular应用
  5. 获取要素集中字段的唯一值
  6. python视频处理代码_python如何实现视频转代码视频
  7. Precedence Problems of C Operators
  8. javascript的内置对象
  9. 了解 svg 图像和元素创建
  10. mybatis添加方法可以传map吗_Mybatis创建方式二
  11. 【Android TV 开发】安卓电视调试 ( 开启网络远程调试 )
  12. matlab函数零点求法,Matlab之函数零点 | 学步园
  13. 执行脚本错误:-bash: ./start.sh: /bin/bash^M: bad interpreter: No such file or directory
  14. vba 添加outlook 签名_调用Outlook发送邮件-附带签名
  15. sed 第n行后加入_sed详解
  16. CheckListBox的实现方式分析
  17. *.lwp文件如何打开
  18. 三星手机电池循环清零代码_晶弘冰箱故障信息代码及维修程序。
  19. 【絮叨.1】同时在写四门语言是怎样一种体验?
  20. 人间四月天,有一本好书要送给你

热门文章

  1. 【信号与系统】系统线性时不变、因果稳定性的判定
  2. 从经济学角度解释:为什么画家总是死后成名?
  3. python操作word、ppt、pdf
  4. response+++php,GitHub - FelixHo/SCAP: 基于Bootstrap 3.0(Response)+ThinkPHP3.2的活动分享平台...
  5. 诺贝丽斯宣布成功完成收购爱励铝业
  6. GITLAB email不发送腾讯企业邮箱解决方案
  7. layui 集成手写签名
  8. spring-狂神学习笔记-联系我获取md文档
  9. 安卓应用加固壳判断java厂商_Android APK加固(加壳)工具
  10. 计算机用户名大小写,windows计算机名大小写