Bert NER 实战
目录
- 0. 比赛介绍
- 1. Bert NER Finetune
- 数据准备
- 原始数据
- 数据转换
- 模型训练
0. 比赛介绍
本项目来自 Kaggle 的 NER 比赛:比赛链接
此 pipeline 及 code 参考自
- https://www.kaggle.com/tungmphung/coleridge-matching-bert-ner?select=kaggle_run_ner.py
- https://www.kaggle.com/tungmphung/pytorch-bert-for-named-entity-recognition
1. Bert NER Finetune
数据准备
首先需要将数据转换成 NER 的 json 格式。
原始数据
train.csv
0007f880-0a9b-492d-9a58-76eb0b0e0bd7.json
(某篇文章)
由于train.csv
中 Id 有重复,首先通过 group
将相同的并入一行:
train = train.groupby('Id').agg({'pub_title': 'first','dataset_title': '|'.join,'dataset_label': '|'.join,'cleaned_label': '|'.join
}).reset_index()print(f'No. grouped training rows: {len(train)}')
No. grouped training rows: 14316
数据转换
直接上代码:
cnt_pos, cnt_neg = 0, 0 # number of sentences that contain/not contain labels
ner_data = []pbar = tqdm(total=len(train))
for i, id, dataset_label in train[['Id', 'dataset_label']].itertuples():# paperpaper = papers[id]# labelslabels = dataset_label.split('|')labels = [clean_training_text(label) for label in labels]# sentencessentences = set([clean_training_text(sentence) for section in paper for sentence in section['text'].split('.') ])sentences = shorten_sentences(sentences) # make sentences shortsentences = [sentence for sentence in sentences if len(sentence) > 10] # only accept sentences with length > 10 chars# positive samplefor sentence in sentences:is_positive, tags = tag_sentence(sentence, labels)if is_positive:cnt_pos += 1ner_data.append(tags)elif any(word in sentence.lower() for word in ['data', 'study']): ner_data.append(tags)cnt_neg += 1# process barpbar.update(1)pbar.set_description(f"Training data size: {cnt_pos} positives + {cnt_neg} negatives")# shuffling
random.shuffle(ner_data)
代码上半部分主要是清洗数据,除去短句等等。重要的还是之后的tag_sentence
操作,本质就是字符串匹配。使用BIO
标记。具体实现如下:
def tag_sentence(sentence, labels): # requirement: both sentence and labels are already cleanedsentence_words = sentence.split()if labels is not None and any(re.findall(f'\\b{label}\\b', sentence)for label in labels): # positive samplenes = ['O'] * len(sentence_words)for label in labels:label_words = label.split()all_pos = find_sublist(sentence_words, label_words)for pos in all_pos:nes[pos] = 'B'for i in range(pos+1, pos+len(label_words)):nes[i] = 'I'return True, list(zip(sentence_words, nes))else: # negative samplenes = ['O'] * len(sentence_words)return False, list(zip(sentence_words, nes))
这样就得到了可训练的数据train_ner.json
:
部分样例
{"tokens": ["Ongoing", "projects", "managing", "flowthrough", "water", "data", "include", "SAMOS", "the", "U"], "tags": ["O", "O", "O", "O", "O", "O", "O", "O", "O", "O"]}
{"tokens": ["The", "numbers", "and", "percentages", "from", "which", "the", "figures", "are", "drawn", "are", "contained", "in", "a", "set", "The", "Survey", "of", "Earned", "Doctorates", "collects", "information", "on", "research", "doctorates", "only"], "tags": ["O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "B", "I", "I", "I", "O", "O", "O", "O", "O", "O"]}
模型训练
训练可以直接使用huggingface
github 中的 代码:run_ner.py
可以命令行直接运行
!python ../input/kaggle-ner-utils/kaggle_run_ner.py \
--model_name_or_path 'bert-base-cased' \
--train_file './train_ner.json' \
--validation_file './train_ner.json' \
--num_train_epochs 1 \
--per_device_train_batch_size 8 \
--per_device_eval_batch_size 8 \
--save_steps 15000 \
--output_dir './output' \
--report_to 'none' \
--seed 43 \
--do_train
Bert NER 实战相关推荐
- 我爱自然语言处理bert ner chinese
BERT相关论文.文章和代码资源汇总 4条回复 BERT最近太火,蹭个热点,整理一下相关的资源,包括Paper, 代码和文章解读. 1.Google官方: 1) BERT: Pre-training ...
- BERT模型实战之多文本分类(附源码)
BERT模型也出来很久了,之前看了论文学习过它的大致模型(可以参考前些日子写的笔记NLP大杀器BERT模型解读),但是一直有杂七杂八的事拖着没有具体去实现过真实效果如何.今天就趁机来动手写一写实战,顺 ...
- [深度学习] 自然语言处理 --- Bert开发实战 (Transformers)
本文主要介绍如果使用huggingface的transformers 2.0 进行NLP的模型训练 除了transformers,其它兼容tf2.0的bert项目还有: 我的博客里有介绍使用方法 [ ...
- NER实战(数据处理+模型分析(词典匹配,统计ML,DL)+评价标准+模型融合)
0.NER 简介 多特征:实体识别不是一个特别复杂的任务,不需要太深入的模型,那么就是加特征,特征越多效果越好,所以字特征.词特征.词性特征.句法特征.KG表征等等的就一个个加吧,甚至有些中文 NER ...
- BERT中文实战(文本相似度)
个人 github BERT本质上是一个两段式的NLP模型.第一个阶段叫做:Pre-training,跟WordEmbedding类似,利用现有无标记的语料训练一个语言模型.第二个阶段叫做:Fin ...
- 最详细NER实战讲解-bilstm+crf(4)提取词边界和词性特征
提取词性和词边界信息 word_bounds = ['M' for item in tag_list] # 和tag list长度一样的 全部都是M构成的 word_flags = [] for te ...
- 069_ublock
title 068 <pakku 哔哩哔哩弹幕过滤器>提升你的哔哩哔哩弹幕体验 弹幕复读终结者!瞬间合并B站的刷屏弹幕,还你清爽的弹幕体验. Bilibili名场面弹幕合并 <某科学 ...
- 五分钟搭建一个基于BERT的NER模型
BERT 简介 BERT是2018年google 提出来的预训练的语言模型,并且它打破很多NLP领域的任务记录,其提出在nlp的领域具有重要意义.预训练的(pre-train)的语言模型通过无监督的学 ...
- 中文NER任务简析与深度算法模型总结和实战展示
目录 一.中文NER定义 1.什么是NER 2.怎么来完成NER 3.NER标注体系 二.基于pytoch和TensorFlow的深度学习算法NER实战 1.算法概览 2.算法实战 A.BiLstm+ ...
最新文章
- Oracle-PL/SQL语法基础
- java 获取光标_如何在java中使用Windows API获取当前鼠标光标类型?
- Linux用户登录自动拷贝文件,linux下ssh远程登录/scp远程复制文件/rsync远程同步命令的自动登录...
- scala不可变和可变_Scala使期货变得轻松
- 114_Power Pivot 销售订单之销售额、成本、利润率相关
- Oracle BCT(Block Change Tracking)与增量备份
- [Android开源]EasyExecutor: 让线程任务的使用变得高效、安全、方便、灵活
- 用vmware workstation做双机集群的详细过程(三)
- 13家电脑品牌来源大揭底
- 地产行业信息化建设思考
- STM32_ADC模数转换的基本原理
- 将多个excel文件合并为:一个excel文件的多个sheet页【方法技巧】
- H.264之lookahead
- python乒乓球比赛规则介绍_乒乓球比赛规则简介
- 他两次都没能感动CCTV却感动了我们
- 两个通宵熬出来的互联网大厂最新面试题收集整理1000道(三-Memcached),欢迎点赞收藏!!!
- ChatGPT版微信个人号搭建流程
- 在uniapp中如何使用icon图标
- 『互联网架构』软件架构-深入理解Ribbon
- 8小时浓度均值即连续8个小时浓度的平均值