用于医疗目的的自定义命名实体识别模型——使用 spaCy 模型

背景和目标

NER 是计算机识别和分类文本中特定信息的一种方式,它有很多应用,包括在医疗保健领域。通过构建和部署自定义 NER 模型,您可以自动化从医疗记录中提取此信息的过程,从而节省时间和精力。

但是,在构建医疗保健数据模型时需要牢记一些挑战和注意事项。这就是为什么我很高兴今天能与您深入探讨这个话题。我们将讨论使用自定义 NER 进行医疗保健的所有细节,希望在我们的讨论结束时,您将很好地理解它是如何工作的以及如何在您的项目中使用它。

空间模型

spaCy 是一个免费的开源库,用于在 MIT 许可证下获得许可的 Python 自然语言处理 (NLP)。它旨在构建 NLP 中的信息提取系统。spaCy 的工作原理是将文本转换为 Doc 对象,然后通过管道过程。

训练数据期间使用的管道通常包括标记器、词形还原器、解析器和实体识别器。然后它们中的每一个都返回一个处理过的 Doc 对象作为输出。spaCy 快速且易于使用,使其成为各行业 NLP 任务的热门选择。

语言处理管道

为什么使用 spaCy?

  • 免费和开源

  • spacy.io 网站上组织良好、结构化且易于访问的文档

  • 能够分析大量结构化或非结构化数据

  • 流行,有许多现有的参考项目

怎么做?

导入数据集

首先,我们导入spaCy并下载英文流水线工具。

import spacy
!python -m spacy download en_core_web_lg
nlp = spacy.load('en_core_web_lg')
nlp

然后,我们导入数据集。您可以在此链接中找到此数据集。在此步骤中,我们还检查数据集的内容。

import json 
with open('/content/Corona2.json','r') as f:
  data = json.load(f)
#data set source:https://www.kaggle.com/datasets/finalepoch/medical-ner
data['examples'][0].keys()

dict_keys(['id', 'content', 'metadata', 'annotations', 'classifications'])

训练数据集

之后,我们就可以开始训练数据集了。它创建一个实体值,例如开始索引、结束索引和标签。

training_data = []
for example in data['examples']:
  temp_dict = {}
  temp_dict['text'] = example['content']
  temp_dict['entities'] = []
  for annotation in example['annotations']:
    start = annotation['start']
    end =annotation['end']
    label = annotation['tag_name'].upper()
    temp_dict['entities'].append((start,end,label))
  training_data.append(temp_dict)
print(training_data[0])

{'text': "While bismuth compounds (Pepto-Bismol) decreased the number of bowel movements in those with travelers' diarrhea, they do not decrease the length of illness.[91] Anti-motility agents like loperamide are also effective at reducing the number of stools but not the duration of disease.[8] These agents should be used only if bloody diarrhea is not present.[92]\n\nDiosmectite, a natural aluminomagnesium silicate clay, is effective in alleviating symptoms of acute diarrhea in children,[93] and also has some effects in chronic functional diarrhea, radiation-induced diarrhea, and chemotherapy-induced diarrhea.[45] Another absorbent agent used for the treatment of mild diarrhea is kaopectate.\n\nRacecadotril an antisecretory medication may be used to treat diarrhea in children and adults.[86] It has better tolerability than loperamide, as it causes less constipation and flatulence.[94]", 'entities': [(360, 371, 'MEDICINE'), (383, 408, 'MEDICINE'), (104, 112, 'MEDICALCONDITION'), (679, 689, 'MEDICINE'), (6, 23, 'MEDICINE'), (25, 37, 'MEDICINE'), (461, 470, 'MEDICALCONDITION'), (577, 589, 'MEDICINE'), (853, 865, 'MEDICALCONDITION'), (188, 198, 'MEDICINE'), (754, 762, 'MEDICALCONDITION'), (870, 880, 'MEDICALCONDITION'), (823, 833, 'MEDICINE'), (852, 853, 'MEDICALCONDITION'), (461, 469, 'MEDICALCONDITION'), (535, 543, 'MEDICALCONDITION'), (692, 704, 'MEDICINE'), (563, 571, 'MEDICALCONDITION')]}

我们可以在下面看到训练模型的例子。

#Slicing 
training_data[0]['text'][360:371]

'Diosmectite'

为 spaCy 模型创建配置

接下来,我们将训练数据集转换为 Doc 对象,以便可以使用 spaCy 模型。

from spacy.tokens import DocBin
from tqdm import tqdm 
nlp = spacy.blank('en')
doc_bin = DocBin()
from spacy.util import filter_spans

for training_example in tqdm(training_data):
  text =training_example['text']
  labels =training_example['entities']
  doc = nlp.make_doc(text)
  ents = []
  for start,end,label in labels:
    span = doc.char_span(start,end,label=label,alignment_mode ='contract')
    if span is None:
      print('Skipping entity')
    else:
      ents.append(span)
  filtered_ents =filter_spans(ents)
  doc.ents =filtered_ents
  doc_bin.add(doc)
doc_bin.to_disk('train.spacy')

之后,我们根据 spacy.io 网站指南创建一个基本模型配置。

这一次,我们将选择 NER 组件。

然后创建一个新的配置文件。

创建一个新的基础配置后,我们在基础配置的基础上创建一个新的。

一个新的配置文件被创建。

使用 spaCy 模型训练

现在,我们可以使用 spaCy 模型来训练我们的数据集。

使用 EPOCH = 25,我们得到的平均分数为 0.94。

流水线过程将创建一个新的 model-best 文件夹。

最后,我们可以尝试我们的模型来预测新文档。

nlp_ner =spacy.load("model-best")

#input document 
doc = nlp_ner("Mose Escherichia coli do not cause disease,naturally living in the gut,but virulent strains can cause infection,neonatal meningits,and stomach ache.That can be cured using azithromycin antibiotics,though that the rate of resistance to commonly used ab=ntibiotics is increasing and they are generally not recommended.")

colors ={'PATHOGEN':"#DC143C","MEDICINE":"#7DF6D9","MEDICALCONDITION":"#07DA63"}
options = {"colors":colors}

spacy.displacy.render(doc,style="ent",options=options,jupyter=True)

结果

结论

基于训练和预测测试结果,我们的模型可以准确识别医疗文档中的病原体类型、药物和健康状况。例如,该模型可以将大肠杆菌识别为病原体,将脑膜炎和胃痛识别为健康状况,将阿奇霉素识别为药物(抗生素)。总体而言,该模型在识别医疗文档中的这些实体方面表现良好。

  • 9
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 19
    评论
Spacy是一个功能强大的Python自然语言处理库,用于进行命名实体识别。它可以自动识别人名、地名、组织名称等实体,并将它们分类到预定义的实体类型中。但是,Spacy默认提供的实体类型可能不足以满足我们的具体需求。因此,我们需要自定义Spacy命名实体识别器,以便它可以识别我们所需的实体类型。 下面是如何自定义Spacy命名实体识别器,以识别中文实体: 1. 安装Spacy和中文语言模型 首先,需要安装Spacy和中文语言模型。可以使用以下命令进行安装: ``` !pip install spacy !pip install -U spacy[cuda110] !pip install jieba !pip install pkuseg !pip install pandas !pip install numpy !pip install scikit-learn !pip install tqdm !pip install matplotlib !pip install seaborn !pip install pyecharts !pip install openpyxl ``` 2. 创建一个新的实体类型 要创建一个新的实体类型,首先需要创建一个空的语言模型。然后,在语言模型中添加新的实体类型。以下是如何创建一个新的实体类型: ``` import spacy # 创建一个新的实体类型 nlp = spacy.load('zh_core_web_sm') nlp.entity.add_label('MY_ENTITY') ``` 这将创建一个新的实体类型“MY_ENTITY”。 3. 训练命名实体识别器 要训练命名实体识别器,需要准备一些已标注的语料库。在本例中,我们将使用一个包含1000个中文文本的语料库。每个文本都已经标注了我们要识别的实体类型。 以下是如何准备数据: ``` import pandas as pd # 读取已标注的语料库 df = pd.read_excel('corpus.xlsx') # 将语料库转换为Spacy的训练数据格式 TRAIN_DATA = [] for i, row in df.iterrows(): text = row['text'] entities = [] for ent in row['entities']: start, end, label = ent entities.append((start, end, 'MY_ENTITY')) TRAIN_DATA.append((text, {'entities': entities})) ``` 然后,我们可以使用Spacy的训练API来训练命名实体识别器。以下是训练命名实体识别器的代码: ``` import random from tqdm import tqdm from spacy.util import minibatch, compounding # 训练命名实体识别器 def train_ner(nlp, train_data, n_iter=10): # 获取命名实体识别器组件 ner = nlp.get_pipe('ner') # 添加新的实体标签 for _, annotations in train_data: for ent in annotations.get('entities'): ner.add_label(ent[2]) # 禁用其它管道组件 other_pipes = [pipe for pipe in nlp.pipe_names if pipe != 'ner'] with nlp.disable_pipes(*other_pipes): # 只训练命名实体识别器组件 optimizer = nlp.begin_training() for i in range(n_iter): # 随机化训练数据 random.shuffle(train_data) # 使用minibatch训练 batches = minibatch(train_data, size=compounding(4.0, 32.0, 1.001)) for batch in tqdm(batches, desc='Training', leave=False): texts, annotations = zip(*batch) nlp.update(texts, annotations, sgd=optimizer) return nlp # 训练命名实体识别器 nlp = spacy.load('zh_core_web_sm') nlp.entity.add_label('MY_ENTITY') nlp = train_ner(nlp, TRAIN_DATA) ``` 4. 测试命名实体识别器 训练完成后,我们可以使用命名实体识别器来识别新的文本中的实体。以下是如何使用命名实体识别器来测试文本: ``` # 测试命名实体识别器 text = '钢铁侠是美国漫威漫画公司的一名超级英雄。' doc = nlp(text) # 输出识别结果 for ent in doc.ents: print(ent.text, ent.label_) ``` 输出结果应该是: ``` 钢铁侠 MY_ENTITY 美国漫威漫画公司 MY_ENTITY 超级英雄 MY_ENTITY ``` 这表明命名实体识别器成功地识别了“钢铁侠”、“美国漫威漫画公司”和“超级英雄”这三个实体。
评论 19
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Sonhhxg_柒

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值