天池中药说明书实体识别挑战冠军方案;中文命名实体识别;NER; BERT-CRF & BERT-SPAN & BERT-MRC;Pytorch

Overview

Chinese-DeepNER-Pytorch

天池中药说明书实体识别挑战冠军方案开源

贡献者:

zxx飞翔的鱼: https://github.com/z814081807

我是蛋糕王:https://github.com/WuHuRestaurant

数青峰:https://github.com/zchaizju

后续官方开放数据集后DeepNER项目会进行优化升级,包含完整的数据处理、训练、验证、测试、部署流程,提供详细的代码注释、模型介绍、实验结果,提供更普适的基于预训练的中文命名实体识别方案,开箱即用,欢迎Star!

(代码框架基于pytorch and transformers, 框架复用性、解耦性、易读性较高,很容易修改迁移至其他NLP任务中)

环境

python3.7
pytorch==1.6.0 +
transformers==2.10.0
pytorch-crf==0.7.2

项目目录说明

DeepNER
│
├── data                                    # 数据文件夹
│   ├── mid_data                            # 存放一些中间数据
│   │   ├── crf_ent2id.json                 # crf 模型的 schema
│   │   └── span_ent2id.json                # span 模型的 schema
│   │   └── mrc_ent2id.json                 # mrc 模型的 schema
│
│   ├── raw_data                            # 转换后的数据
│   │   ├── dev.json                        # 转换后的验证集
│   │   ├── test.json                       # 转换后的初赛测试集
│   │   ├── pseudo.json                     # 转换后的半监督数据
│   │   ├── stack.json                      # 转换后的全体数据
│   └── └── train.json                      # 转换后的训练集
│
├── out                                     # 存放训练好的模型
│   ├── ...           
│   └── ...                                      
│
├── src
│   ├── preprocess                  
│   │   ├── convert_raw_data.py             # 处理转换原始数据
│   │   └── processor.py                    # 转换数据为 Bert 模型的输入
│   ├── utils                      
│   │   ├── attack_train_utils.py           # 对抗训练 FGM / PGD
│   │   ├── dataset_utils.py                # torch Dataset
│   │   ├── evaluator.py                    # 模型评估
│   │   ├── functions_utils.py              # 跨文件调用的一些 functions
│   │   ├── model_utils.py                  # Span & CRF & MRC model (pytorch)
│   │   ├── options.py                      # 命令行参数|   └── trainer.py                      # 训练器
|
├── competition_predict.py                  # 复赛数据推理并提交
├── README.md                               # ...
├── convert_test_data.py                    # 将复赛 test 转化成 json 格式
├── run.sh                                  # 运行脚本
└── main.py                                 # main 函数 (主要用于训练/评估)

使用说明

预训练使用说明

数据转换

注:已提供转换好的数据 无需运行

python src/preprocessing/convert_raw_data.py

训练阶段

bash run.sh

注:脚本中指定的 BERT_DIR 指BERT所在文件夹,需要把 BERT 下载到指定文件夹中

BERT-CRF模型训练
task_type='crf'
mode='train' or 'stack'  train:单模训练与验证 ; stack:5折训练与验证

swa_start: swa 模型权重平均开始的 epoch
attack_train'pgd' / 'fgm' / '' 对抗训练 fgm 训练速度慢一倍, pgd 慢两倍,pgd 本次数据集效果明显
BERT-SPAN模型训练
task_type='span'
mode:同上
attack_train: 同上
loss_type: 'ce':交叉熵; 'ls_ce'label_smooth; 'focal': focal loss
BERT-MRC模型训练
task_type='mrc'
mode:同上
attack_train: 同上
loss_type: 同上

预测复赛 test 文件 (上述模型训练完成后)

注:暂无数据运行,等待官方数据开源后可运行

# convert_test_data
python convert_test_data.py
# predict
python competition_predict.py

赛题背景

任务描述

人工智能加速了中医药领域的传承创新发展,其中中医药文本的信息抽取部分是构建中医药知识图谱的核心部分,为上层应用如临床辅助诊疗系统的构建(CDSS)等奠定了基础。本次NER挑战需要抽取中药药品说明书中的关键信息,包括药品、药物成分、疾病、症状、证候等13类实体,构建中医药药品知识库。

数据探索分析

本次竞赛训练数据有三个特点:

  • 中药药品说明书以长文本居多

- 医疗场景下的标注样本不足

- 标签分布不平衡

核心思路

数据预处理

首先对说明书文本进行预清洗与长文本切分。预清洗部分对无效字符进行过滤。针对长文本问题,采用两级文本切分的策略。切分后的句子可能过短,将短文本归并,使得归并后的文本长度不超过设置的最大长度。此外,利用全部标注数据构造实体知识库,作为领域先验词典。

Baseline: BERT-CRF

  • Baseline 细节
    • 预训练模型:选用 UER-large-24 layer[1],UER在RoBerta-wwm 框架下采用大规模优质中文语料继续训练,CLUE 任务中单模第一
    • 差分学习率:BERT层学习率2e-5;其他层学习率2e-3
    • 参数初始化:模型其他模块与BERT采用相同的初始化方式
    • 滑动参数平均:加权平均最后几个epoch模型的权重,得到更加平滑和表现更优的模型
  • Baseline bad-case分析

优化1:对抗训练

  • 动机:采用对抗训练缓解模型鲁棒性差的问题,提升模型泛化能力
  • 对抗训练是一种引入噪声的训练方式,可以对参数进行正则化,提升模型鲁棒性和泛化能力
    • Fast Gradient Method (FGM):对embedding层在梯度方向添加扰动
    • Projected Gradient Descent (PGD) [2]:迭代扰动,每次扰动被投影到规定范围内

优化2:混合精度训练(FP16)

  • 动机:对抗训练降低了计算效率,使用混合精度训练优化训练耗时
  • 混合精度训练
    • 在内存中用FP16做存储和乘法来加速
    • 用FP32做累加避免舍入误差
  • 损失放大
    • 反向传播前扩大2^k倍loss,防止loss下溢出
    • 反向传播后将权重梯度还原

优化3:多模型融合

  • 动机:baseline 错误集中于歧义性错误,采用多级医学命名实体识别系统以消除歧义性

  • 方法:差异化多级模型融合系统

    • 模型框架差异化:BERT-CRF & BERT-SPAN & BERT-MRC
    • 训练数据差异化:更换随机种子、更换句子切分长度(256、512)
    • 多级模型融合策略
  • 融合模型1——BERT-SPAN

    • 采用SPAN指针的形式替代CRF模块,加快训练速度
    • 以半指针-半标注的结构预测实体的起始位置,同时标注过程中给出实体类别
    • 采用严格解码形式,重叠实体选取logits最大的一个,保证准确率
    • 使用label smooth缓解过拟合问题

  • 融合模型2——BERT-MRC
    • 基于阅读理解的方式处理NER任务
      • query:实体类型的描述来作为query
      • doc:分句后的原始文本作为doc
    • 针对每一种类型构造一个样本,训练时有大量负样本,可以随机选取30%加入训练,其余丢弃,保证效率
    • 预测时对每一类都需构造一次样本,对解码输出不做限制,保证召回率
    • 使用label smooth缓解过拟合问题
    • MRC在本次数据集上精度表现不佳,且训练和推理效率较低,仅作为提升召回率的方案,提供代码仅供学习,不推荐日常使用

  • 多级融合策略
    • CRF/SPAN/MRC 5折交叉验证得到的模型进行第一级概率融合,将 logits 平均后解码实体
    • CRF/SPAN/MRC 概率融合后的模型进行第二级投票融合,获取最终结果

优化4:半监督学习

  • 动机:为了缓解医疗场景下的标注语料稀缺的问题, 我们使用半监督学习(伪标签)充分利用未标注的500条初赛测试集
  • 策略:动态伪标签
    • 首先使用原始标注数据训练一个基准模型M
    • 使用基准模型M对初赛测试集进行预测得到伪标签
    • 将伪标签加入训练集,赋予伪标签一个动态可学习权重(图中alpha),加入真实标签数据中共同训练得到模型M’

- tips:使用多模融合的基准模型减少伪标签的噪音;权重也可以固定,选取需多尝试哪个效果好,本质上是降低伪标签的loss权重,是缓解伪标签噪音的一种方法。

其他无明显提升的尝试方案

  • 取BERT后四层动态加权输出,无明显提升
  • BERT 输出后加上BiLSTM / IDCNN 模块,过拟合严重,训练速度大大降低
  • 数据增强,对同类实体词进行随机替换,以扩充训练数据
  • BERT-SPAN / MRC 模型采用focal loss / dice loss 等缓解标签不平衡
  • 利用构造的领域词典修正模型输出

最终线上成绩72.90%,复赛Rank 1,决赛Rank 1

Ref

[1] Zhao et al., UER: An Open-Source Toolkit for Pre-training Models, EMNLP-IJCNLP, 2019. [2] Madry et al., Towards Deep Learning Models Resistant to Adversarial Attacks, ICLR, 2018.

Owner
zxx飞翔的鱼
Speak less and do more.
zxx飞翔的鱼
A PyTorch implementation of paper "Learning Shared Semantic Space for Speech-to-Text Translation", ACL (Findings) 2021

Chimera: Learning Shared Semantic Space for Speech-to-Text Translation This is a Pytorch implementation for the "Chimera" paper Learning Shared Semant

Chi Han 43 Dec 28, 2022
🐍💯pySBD (Python Sentence Boundary Disambiguation) is a rule-based sentence boundary detection that works out-of-the-box.

pySBD: Python Sentence Boundary Disambiguation (SBD) pySBD - python Sentence Boundary Disambiguation (SBD) - is a rule-based sentence boundary detecti

Nipun Sadvilkar 549 Jan 06, 2023
Contains links to publicly available datasets for modeling health outcomes using speech and language.

speech-nlp-datasets Contains links to publicly available datasets for modeling various health outcomes using speech and language. Speech-based Corpora

Tuka Alhanai 77 Dec 07, 2022
Open Source Neural Machine Translation in PyTorch

OpenNMT-py: Open-Source Neural Machine Translation OpenNMT-py is the PyTorch version of the OpenNMT project, an open-source (MIT) neural machine trans

OpenNMT 5.8k Jan 04, 2023
[Preprint] Escaping the Big Data Paradigm with Compact Transformers, 2021

Compact Transformers Preprint Link: Escaping the Big Data Paradigm with Compact Transformers By Ali Hassani[1]*, Steven Walton[1]*, Nikhil Shah[1], Ab

SHI Lab 367 Dec 31, 2022
Telegram bot to auto post messages of one channel in another channel as soon as it is posted, without the forwarded tag.

Channel Auto-Post Bot This bot can send all new messages from one channel, directly to another channel (or group, just in case), without the forwarded

Aditya 128 Dec 29, 2022
This is a MD5 password/passphrase brute force tool

CROWES-PASS-CRACK-TOOl This is a MD5 password/passphrase brute force tool How to install: Do 'git clone https://github.com/CROW31/CROWES-PASS-CRACK-TO

9 Mar 02, 2022
Sentello is python script that simulates the anti-evasion and anti-analysis techniques used by malware.

sentello Sentello is a python script that simulates the anti-evasion and anti-analysis techniques used by malware. For techniques that are difficult t

Malwation 62 Oct 02, 2022
Code for "Finetuning Pretrained Transformers into Variational Autoencoders"

transformers-into-vaes Code for Finetuning Pretrained Transformers into Variational Autoencoders (our submission to NLP Insights Workshop 2021). Gathe

Seongmin Park 22 Nov 26, 2022
Translate U is capable of translating the text present in an image from one language to the other.

Translate U is capable of translating the text present in an image from one language to the other. The app uses OCR and Google translate to identify and translate across 80+ languages.

Neelanjan Manna 1 Dec 22, 2021
customer care chatbot made with Rasa Open Source.

Customer Care Bot Customer care bot for ecomm company which can solve faq and chitchat with users, can contact directly to team. 🛠 Features Basic E-c

Dishant Gandhi 23 Oct 27, 2022
GPT-3 command line interaction

Writer_unblock Straight-forward command line interfacing with GPT-3. Finding yourself stuck at a conceptual stage? Spinning your wheels needlessly on

Seth Nuzum 6 Feb 10, 2022
Task-based datasets, preprocessing, and evaluation for sequence models.

SeqIO: Task-based datasets, preprocessing, and evaluation for sequence models. SeqIO is a library for processing sequential data to be fed into downst

Google 290 Dec 26, 2022
Repository of the Code to Chatbots, developed in Python

Description In this repository you will find the Code to my Chatbots, developed in Python. I'll explain the structure of this Repository later. Requir

Li-am K. 0 Oct 25, 2022
Code for Text Prior Guided Scene Text Image Super-Resolution

Code for Text Prior Guided Scene Text Image Super-Resolution

82 Dec 26, 2022
Official PyTorch implementation of "Dual Path Learning for Domain Adaptation of Semantic Segmentation".

Dual Path Learning for Domain Adaptation of Semantic Segmentation Official PyTorch implementation of "Dual Path Learning for Domain Adaptation of Sema

27 Dec 22, 2022
Universal End2End Training Platform, including pre-training, classification tasks, machine translation, and etc.

背景 安装教程 快速上手 (一)预训练模型 (二)机器翻译 (三)文本分类 TenTrans 进阶 1. 多语言机器翻译 2. 跨语言预训练 背景 TrenTrans是一个统一的端到端的多语言多任务预训练平台,支持多种预训练方式,以及序列生成和自然语言理解任务。 安装教程 git clone git

Tencent Minority-Mandarin Translation Team 42 Dec 20, 2022
Textlesslib - Library for Textless Spoken Language Processing

textlesslib Textless NLP is an active area of research that aims to extend NLP t

Meta Research 379 Dec 27, 2022
A method to generate speech across multiple speakers

VoiceLoop PyTorch implementation of the method described in the paper VoiceLoop: Voice Fitting and Synthesis via a Phonological Loop. VoiceLoop is a n

Facebook Archive 873 Dec 15, 2022
💬 Open source machine learning framework to automate text- and voice-based conversations: NLU, dialogue management, connect to Slack, Facebook, and more - Create chatbots and voice assistants

Rasa Open Source Rasa is an open source machine learning framework to automate text-and voice-based conversations. With Rasa, you can build contextual

Rasa 15.3k Dec 30, 2022