- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我是 spacy 和 python 的新手,我正在使用 python 和 nltk 训练我自己的 spacy 模型,这是我训练数据和测试数据的代码,如果我给出与文本数据相同的测试数据,则输出是正确的,但是我无法识别超过 2 个标签,每次编译代码时,标签识别都是不同且不正确的,我引用了 spacy 网站,但我无法找到解决方案。请帮助我!!
from __future__ import unicode_literals, print_function
import plac
import random
from pathlib import Path
import spacy
# new entity label
# training data
# Note: If you're using an existing model, make sure to mix in examples of
# other entity types that spaCy correctly recognized before. Otherwise, your
# model might learn the new type, but "forget" what it previously knew.
# https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
TRAIN_DATA = [
("Duck quacks, Dog barks", {
'entities': [(0,4,'Bird'), (13,16,'Animal')]
}),
("Duck eats fish, Dog eats meat", {
'entities': [(0,4,'Bird'), (16,19,'Animal')]
}),
("Duck eats fish, Dog eats meat", {
'entities': [(0,4,'Bird'), (16,19,'Animal')]
})
]
@plac.annotations(
model=("Model name. Defaults to blank 'en' model.", "option", "m", str),
new_model_name=("New model name for model meta.", "option", "nm", str),
output_dir=("Optional output directory", "option", "o", Path),
n_iter=("Number of training iterations", "option", "n", int))
def main(model=None, new_model_name='Animal', output_dir=None, n_iter=20):
"""Set up the pipeline and entity recognizer, and train the new
entity."""
if model is not None:
nlp = spacy.load(model) # load existing spaCy model
print("Loaded model '%s'" % model)
else:
nlp = spacy.blank('en') # create blank Language class
print("Created blank 'en' model")
# Add entity recognizer to model if it's not in the pipeline
# nlp.create_pipe works for built-ins that are registered with spaCy
if 'ner' not in nlp.pipe_names:
ner = nlp.create_pipe('ner')
nlp.add_pipe(ner)
# otherwise, get it, so we can add labels to it
else:
ner = nlp.get_pipe('ner')
# add new entity label to entity recognizer
for _, annotations in TRAIN_DATA:
for ent in annotations.get('entities'):
ner.add_label(ent[2])
print("Label '%s'" % ent[2])
# 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
optimizer = nlp.begin_training()
for itn in range(n_iter):
random.shuffle(TRAIN_DATA)
losses = {}
for text, annotations in TRAIN_DATA:
nlp.update([text], [annotations], sgd=optimizer, drop=0.35,
losses=losses)
print(losses)
# test the trained model
test_text = 'Duck eats Nippot, Dog eats meat'
doc = nlp(test_text)
print("Entities in '%s'" % test_text)
for ent in doc.ents:
print(ent.label_, ent.text)
# save model to output directory
if output_dir is not None:
output_dir = Path(output_dir)
if not output_dir.exists():
output_dir.mkdir()
nlp.meta['name'] = new_model_name # rename model
nlp.to_disk(output_dir)
print("Saved model to", output_dir)
# test the saved model
print("Loading from", output_dir)
nlp2 = spacy.load(output_dir)
doc2 = nlp2(test_text)
for ent in doc2.ents:
print(ent.label_, ent.text)
if __name__ == '__main__':
plac.call(main)
最佳答案
更改是针对脚本中的优化器代码。另外,避免添加重复的标签,因此创建一个标签列表,然后通过 ner.add_label 添加。
TRAIN_DATA = [
("Duck quacks, Dog barks", {
'entities': [(0,4,'Bird'), (13,16,'Animal')]
}),
("Duck eats fish, Dog eats meat", {
'entities': [(0,4,'Bird'), (16,19,'Animal')]
}),
("Duck eats fish, Dog eats meat", {
'entities': [(0,4,'Bird'), (16,19,'Animal')]
})
]
label_ = ['Bird', 'Animal']
@plac.annotations(
model=("Model name. Defaults to blank 'en' model.", "option", "m", str),
new_model_name=("New model name for model meta.", "option", "nm", str),
output_dir=("Optional output directory", "option", "o", Path),
n_iter=("Number of training iterations", "option", "n", int))
def main(model=None, new_model_name='Animal', output_dir=None, n_iter=20):
"""Set up the pipeline and entity recognizer, and train the new
entity."""
if model is not None:
nlp = spacy.load(model) # load existing spaCy model
print("Loaded model '%s'" % model)
else:
nlp = spacy.blank('en') # create blank Language class
print("Created blank 'en' model")
# Add entity recognizer to model if it's not in the pipeline
# nlp.create_pipe works for built-ins that are registered with spaCy
if 'ner' not in nlp.pipe_names:
ner = nlp.create_pipe('ner')
nlp.add_pipe(ner)
# otherwise, get it, so we can add labels to it
else:
ner = nlp.get_pipe('ner')
# add new entity label to entity recognizer
# for _, annotations in TRAIN_DATA:
# for ent in annotations.get('entities'):
# ner.add_label(ent[2])
# print("Label '%s'" % ent[2])
for LABEL in label_: # add new entity label to entity recognizer
ner.add_label(LABEL) # this way you avoid adding duplicate labels.
if model is None:
optimizer = nlp.begin_training()
# Note that 'begin_training' initializes the models, so it'll zero out
# existing entity types.
else:
optimizer = nlp.entity.create_optimizer()
# 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
# optimizer = nlp.begin_training() # made changes above for the same
for itn in range(n_iter):
random.shuffle(TRAIN_DATA)
losses = {}
for text, annotations in TRAIN_DATA:
nlp.update([text], [annotations], sgd=optimizer, drop=0.35,
losses=losses)
print(losses)
# test the trained model
test_text = 'Duck and Dog eats Nippot, Dog eats meat'
doc = nlp(test_text)
print("Entities in '%s'" % test_text)
for ent in doc.ents:
print(ent.label_, ent.text)
# save model to output directory
if output_dir is not None:
output_dir = Path(output_dir)
if not output_dir.exists():
output_dir.mkdir()
nlp.meta['name'] = new_model_name # rename model
nlp.to_disk(output_dir)
print("Saved model to", output_dir)
# test the saved model
print("Loading from", output_dir)
nlp2 = spacy.load(output_dir)
doc2 = nlp2(test_text)
for ent in doc2.ents:
print(ent.label_, ent.text)
输出:
Entities in 'Duck and Dog eats Nippot, Dog eats meat'
Bird Duck
Animal Dog
Animal Dog
关于python - 无法使用 python 识别 spacy 中的两个或多个标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49612091/
我有一段文本和索引条目,其中一些指示出现在文本中的重要多词表达 (MWE)(例如生物学文本的“海绵骨”)。我想使用这些条目在 spaCy 中构建自定义匹配器,以便我可以识别文本中出现的 MWE。一个附
我想在 Spacy 中使用德语 lemmatizer,但我对结果感到非常惊讶: import spacy nlp = spacy.load("de_dep_news_trf") [token.lemm
要将我的句子拆分为标记,我正在执行以下操作,这很慢 import spacy nlp = spacy.load("en_core_web_lg") text = "This is a test.
我已经使用空间很长一段时间了,我真的很喜欢这种置换 有没有一种方法可以让我们在网页中从我的数据集中提供多个文本,如一个小箭头,以重定向到下一条记录并标记实体。 我使用的代码如下。 def valida
我有变量 trainData它具有以下简化格式。 [ ('Paragraph_A', {"entities": [(15, 26, 'DiseaseClass'), (443, 449, 'Disea
我正在尝试测试在另一台计算机上运行的模型,但是当我尝试将其导入我的笔记本时,出现以下错误:ModuleNotFoundError:没有名为“spacy.pipeline.pipes”的模块; 'spa
我正在尝试测试在另一台计算机上运行的模型,但是当我尝试将其导入我的笔记本时,出现以下错误:ModuleNotFoundError:没有名为“spacy.pipeline.pipes”的模块; 'spa
当处理数百万文档并将它们保存为空间文档以供以后使用(更多处理、可视化、提取特征)时,一种明显的扩展解决方案是并行/分布式处理。这意味着每个并行进程都将拥有自己的 Vocab,这些 Vocab 可能会随
我正在使用 Spacy 大型模型,但它错误地使用与我的领域无关的类别标记实体,例如“艺术作品”可能导致它无法识别本应属于组织的内容。 是否可以限制 NER 仅返回人员、位置和组织? 最佳答案 简答:
我正在像这样使用 SpaCy 创建一个短语匹配器: import spacy from spacy.matcher import PhraseMatcher nlp = spacy.load("en"
我正在尝试使用 spaCy Matcher 工作获得以下简单示例: import en_core_web_sm from spacy.matcher import Matcher nlp = en_c
它没有出现在 pip list zeke$ pip list | grep spacy spacy (1.7.3) 如何获取模型名称? 我试过了,还是不行 echo "spaCy model:" py
我在 "Training an additional entity type" 中有新 NER 类型的训练数据spaCy 文档的部分。 TRAIN_DATA = [ ("Horses are
给定一个 token ,它是具有多个 token 的命名实体的一部分,是否有直接方法来获取该实体的跨度? 例如,考虑这个有两个词命名实体的句子: >>> doc = nlp("This year wa
如何限制 Spacy 使用的 CPU 数量? 我想从大量句子中提取词性和命名实体。由于 RAM 的限制,我首先使用 Python NLTK 将我的文档解析为句子。然后我遍历我的句子并使用 nlp.pi
显然 for doc in nlp.pipe(sequence) 比运行 for el in order: doc = nlp(el) .. 我遇到的问题是我的序列实际上是一个元组序列,其中包含用于将
显然 for doc in nlp.pipe(sequence) 比运行 for el in order: doc = nlp(el) .. 我遇到的问题是我的序列实际上是一个元组序列,其中包含用于将
我已经下载了 spaCy,但每次尝试 nlp = spacy.load("en_core_web_lg") 命令时,我都会收到此错误: OSError:[E050] 找不到模型“en_core_web
到目前为止,我一直在使用 spacy 2.3.1,并为我的自定义语言类(class)训练并保存了几个管道。但是现在使用 spacy 3.0 和 spacy.load('model-path') 我遇到
我安装了 spacy 使用 python3 install spacy 并使用下载了两个英文模型 python3 -m spacy download en 和 python3 -m spacy dow
我是一名优秀的程序员,十分优秀!