我们如何使用 Spacy minibatch 和 GoldParse 来使用 BILUO 标记方案训练 NER 模型?

2024-02-21

我对 spacy ner 模型的输入数据位于BILUO标记方案,我希望使用相同的作为某些要求的一部分。当我尝试在没有小批量的情况下简单地训练模型时,它工作得很好(注释部分)。但我无法弄清楚如何在这里使用 minibatch 和 GoldParse 来提高模型的准确性。我的期望是否有效,因为我找不到这种组合的单个示例?另外,我已经用开始、结束、标签格式的方法训练了模型。请帮我弄清楚这一部分。我的代码如下,

import spacy
from spacy.gold import offsets_from_biluo_tags
from spacy.gold import biluo_tags_from_offsets
import random
from spacy.util import minibatch, compounding
from os import path
from tqdm import tqdm


def train_spacy(data, iterations, model=None):
    TRAIN_DATA = data
    print(f"downloads = {model}")
    if model is not None and path.exists(model):
        print(f"training existing model")
        nlp = spacy.load(model)
        print("Model is Loaded '%s'" % model)
    else:
        print(f"Creating new model")

        nlp = spacy.blank('en')  # create blank Language class

    if 'ner' not in nlp.pipe_names:
        ner = nlp.create_pipe('ner')
        nlp.add_pipe(ner, last=True)
    else:
        ner = nlp.get_pipe('ner')

    # Based on template, get labels and save those for further training
    LABEL = ["Name", "ORG"]

    for i in LABEL:
        # print(i)
        ner.add_label(i)

    # get names of other pipes to disable them during training
    other_pipes = [pipe for pipe in nlp.pipe_names if pipe != 'ner']
    with nlp.disable_pipes(*other_pipes):  # only train NER
        if model is None:
            optimizer = nlp.begin_training()
        else:
            optimizer = nlp.entity.create_optimizer()
        tags = dict()
        for itn in range(iterations):
            print("Starting iteration " + str(itn))
            random.shuffle(TRAIN_DATA)
            losses = {}
            # for text, annotations in tqdm(TRAIN_DATA):
            #     print(f"text={text}, an={annotations}")
            #     tags['entities'] = offsets_from_biluo_tags(nlp(text), annotations)
            #     print(f"a={tags}")
            #     nlp.update([text],  # batch of texts
            #                [tags],  # batch of annotations
            #                drop=0.5,  # dropout - make it harder to memorise data
            #                sgd=optimizer,  # callable to update weights
            #                losses=losses)
            # print(losses)
            batches = minibatch(TRAIN_DATA, size=compounding(4.0, 16.0, 1.001))
            # type 2 with mini batch
            for batch in batches:
                texts, annotations = zip(*batch)
                print(texts)
                tags = {'entities': annotations}
                nlp.update(
                    texts,  # batch of texts
                    [tags],  # batch of annotations
                    drop=0.4,  # dropout - make it harder to memorise data
                    losses=losses,
                    sgd=optimizer
                )
            print(losses)
    return nlp

data_biluo = [
    ('I am Shah Khan, I work in MS Co', ['O', 'O', 'B-Name', 'L-Name', 'O', 'O', 'O', 'B-ORG', 'L-ORG']),
    ('I am Tom Tomb, I work in Telecom Networks', ['O', 'O', 'B-Name', 'L-Name', 'O', 'O', 'O', 'B-ORG', 'L-ORG'])
]


model = train_spacy(data_biluo, 10)
model.to_disk('./Vectors/')

您的小批量有两个问题:

  1. tags应该是带有偏移量的 ner 标签的可迭代对象
  2. your data_biluo不考虑,在句子的中间。

一旦你纠正了那些你就可以走了:

import spacy
from spacy.gold import offsets_from_biluo_tags, GoldParse
from spacy.util import minibatch, compounding
import random
from tqdm import tqdm

def train_spacy(data, iterations, model=None):
    TRAIN_DATA = data
    print(f"downloads = {model}")
    if model is not None and path.exists(model):
        print(f"training existing model")
        nlp = spacy.load(model)
        print("Model is Loaded '%s'" % model)
    else:
        print(f"Creating new model")

        nlp = spacy.blank('en')  # create blank Language class

    if 'ner' not in nlp.pipe_names:
        ner = nlp.create_pipe('ner')
        nlp.add_pipe(ner, last=True)
    else:
        ner = nlp.get_pipe('ner')

    # Based on template, get labels and save those for further training
    LABEL = ["Name", "ORG"]

    for i in LABEL:
        # print(i)
        ner.add_label(i)

    # get names of other pipes to disable them during training
    other_pipes = [pipe for pipe in nlp.pipe_names if pipe != 'ner']
    with nlp.disable_pipes(*other_pipes):  # only train NER
        if model is None:
            optimizer = nlp.begin_training()
        else:
            optimizer = nlp.entity.create_optimizer()
        tags = dict()
        for itn in range(iterations):
            print("Starting iteration " + str(itn))
            random.shuffle(TRAIN_DATA)
            losses = {}
            batches = minibatch(TRAIN_DATA, size=compounding(4.0, 16.0, 1.001))
            # type 2 with mini batch
            for batch in batches:
                texts, _ = zip(*batch)
                golds = [GoldParse(nlp.make_doc(t),entities = a) for t,a in batch]
                nlp.update(
                    texts,  # batch of texts
                    golds,  # batch of annotations
                    drop=0.4,  # dropout - make it harder to memorise data
                    losses=losses,
                    sgd=optimizer
                )
            print(losses)
    return nlp

data_biluo = [
    ('I am Shah Khan, I work in MS Co', ['O', 'O', 'B-Name', 'L-Name', 'O', 'O', 'O', 'O', 'B-ORG', 'L-ORG']),
    ('I am Tom Tomb, I work in Telecom Networks', ['O', 'O', 'B-Name', 'L-Name', 'O', 'O', 'O', 'O', 'B-ORG', 'L-ORG'])
]


model = train_spacy(data_biluo, 10)

Starting iteration 0
{'ner': 17.999998331069946}
Starting iteration 1
{'ner': 16.6766300201416}
Starting iteration 2
{'ner': 16.997647166252136}
Starting iteration 3
{'ner': 16.486496448516846}
Starting iteration 4
{'ner': 15.695325374603271}
Starting iteration 5
{'ner': 14.312554001808167}
Starting iteration 6
{'ner': 12.099276185035706}
Starting iteration 7
{'ner': 11.473928153514862}
Starting iteration 8
{'ner': 8.814643770456314}
Starting iteration 9
{'ner': 7.233813941478729}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

我们如何使用 Spacy minibatch 和 GoldParse 来使用 BILUO 标记方案训练 NER 模型? 的相关文章

  • 将 ical 附件的邮件消息的内容类型设置为“text/calendar; method=REQUEST”

    我正在尝试使用 App Engine 邮件 API 从 App Engine 发送 iCalendar 格式的 ics 文件 这在 GMail 中非常有效 但是 Outlook 无法识别该文件 我认为问题在于内容类型设置为 文本 日历 而不
  • 删除 tkinter 文本默认绑定

    我正在制作一个简单的 tkinter 文本编辑器 但我想要所有默认绑定文本小部件如果可能的话删除 例如当我按Ctrl i它默认插入一个制表符 我制作了一个事件绑定来打印文本框中有多少行 我将事件绑定设置为Ctrl i以及 当我运行它时 它会
  • 我可以同时打开两个 Tkinter Windows 吗?

    可以同时打开2个窗口吗 import tkinter as Tk import random import math root Tk Tk canvas Tk Canvas root background image Tk PhotoIma
  • DataFrame.loc 的“索引器太多”

    我读了关于切片器的文档 http pandas pydata org pandas docs stable advanced html using slicers一百万次 但我从来没有理解过它 所以我仍在试图弄清楚如何使用loc切片Data
  • 获取字符串模板中所有标识符列表的函数(Python)

    对于标准库string template在Python中 有没有一个函数可以获取所有标识符的列表 例如 使用以下 xml 文件
  • Asyncio:从未检索到任务异常的怪异

    假设我有一个简单的代码 import asyncio async def exc print 1 0 loop asyncio get event loop loop create task exc try loop run forever
  • cxfreeze virtualenv 中缺少 distutils 模块

    从 python3 2 项目运行 cxfreeze 二进制文件时 我收到以下运行时错误 project dist project distutils init py 13 UserWarning The virtualenv distuti
  • 右键单击 QPushButton 上的 contextMenu

    对于我的应用程序 我在 Qt Designer 中创建了一个 GUI 并将其转换为 python 2 6 代码 关于一些QPushButton 与设计器创建 我想添加右键单击上下文菜单 菜单选项取决于应用程序状态 如何实现这样的上下文菜单
  • 如何在 python 中使用交叉验证执行 GridSearchCV

    我正在执行超参数调整RandomForest如下使用GridSearchCV X np array df features all features y np array df gold standard labels x train x
  • ImproperlyConfigured at / 不允许空静态前缀 - Django

    我正在使用 Django 上传 显示图像 该网站部署在 Heroku 上 下列的this https coderwall com p bz0sng教程我能够成功上传图像 但是 图像并未显示在模板中 然后我了解到我的 urls py 末尾应该
  • 为什么 pip 已经是最新的了却要求我升级?

    我全新安装了 python 3 7 1 64 位 并使用最新的 pyCharm 作为我的 IDE 我在这台机器上没有安装其他 python 我去安装 numpy 并收到以下消息 venv C Users John PycharmProjec
  • Pygame:有人可以帮我实现双跳吗?

    我知道已经有其他关于此问题的帖子了 但我的运动系统与我发现的有点不同 所以随后我问这个问题 我的运动系统基于一个名为的命名元组Move up left right down 然后就是这个 def update self move block
  • 列表中的特定范围(python)

    我有一个从文本字符串中提取的整数列表 因此当我打印该列表 我称之为test I get 135 2256 1984 3985 1991 1023 1999 我想打印或制作一个仅包含特定范围内的数字的新列表 例如1000 2000之间 我尝试
  • 如何在类型提示中定义元组或列表的大小

    有没有办法在参数的类型提示中定义元组或列表的大小 目前我正在使用这样的东西 from typing import List Optional Tuple def function name self list1 List Class1 if
  • 将二进制数据视为文件对象?

    在此代码片段 由另一个人编写 中 self archive是一个大文件的路径并且raw file是以二进制数据形式读取的文件内容 with open self archive rb as f f seek offset raw file s
  • 如何使用 python 模块的多个 git 分支?

    我想使用 git 来同时处理我正在编写的模块中的多个功能 我目前正在使用 SVN 只有一个工作区 因此我的 PYTHONPATH 上只有该工作区 我意识到这不太理想 所以我想知道是否有人可以建议一种更 正确 的方法来做到这一点 让我用一个假
  • Rasa core 和 Rasa nlu 之间的区别

    我试图理解之间的区别拉莎核心 https core rasa ai and Rasa NLU https nlu rasa ai installation html从官方文档看的 但我不太明白 我的理解是Rasa core用于引导对话流程
  • 将函数按元素应用于两个 DataFrame

    如何应用函数z ij f x ij y ij 来自数据框X and Y相同大小并将结果保存到 DataFrameZ 这取决于你有什么样的功能 很多功能已经被矢量化为数据框 例如 等等 所以对于这些功能 你可以简单地做Z X Y or Z X
  • 将二进制数转换为包含每个二进制数的数组

    我试图将二进制值转换为每个 1 0 的列表 但我得到默认的二进制值而不是列表 我有一个字符串 我将每个字符转换为二进制 它给了我一个列表 其中每个字符都有一个字符串 现在我试图将每个字符串拆分为值为 0 1 的整数 但我什么也得不到 if
  • 在Python中使用os.makedirs创建目录时出现权限问题

    我只是想处理上传的文件并将其写入工作目录中 该目录的名称是系统时间戳 问题是我想以完全权限创建该目录 777 但我不能 使用以下代码创建的目录755权限 def handle uploaded file upfile cTimeStamp

随机推荐