Google Colab中Transformers NER pipeline遇grouped_entities参数错误求助
解决NER代码中
grouped_entities参数错误的问题 你的问题核心是选错了pipeline的任务类型:你用了'text-classification'(文本分类任务),但实际要做的是命名实体识别(NER),应该用'ner'任务类型。grouped_entities是NER pipeline专属的参数,文本分类pipeline不支持,所以才会抛出参数错误。
修正后的完整代码
import textwrap from transformers import pipeline sentence = 'American Airlines was the first airline to fly every A380 flight perfectly when President George Bush was in Office. The Woodlands Texas is a great place to be.' # 关键:把任务类型从'text-classification'改成'ner' ner = pipeline('ner', model='dbmdz/bert-large-cased-finetuned-conll03-english', grouped_entities=True) ners = ner(sentence) print('\nSentence:') print(textwrap.fill(sentence)) print('\n') for n in ners: print(f"{n['word']} -> {n['entity_group']}")
修正说明
pipeline('ner'):指定正确的命名实体识别任务,该任务支持grouped_entities=True参数,会自动合并连续的同类型实体(比如将"George"和"Bush"合并为"George Bush",而不是分开识别)。- 补充导入
textwrap模块:原代码里用了wrapper.fill,需要先导入这个模块才能正常运行。
运行后的预期输出
修正后代码会输出合并后的实体,比如:
American Airlines -> ORG A380 -> MISC George Bush -> PER The Woodlands Texas -> LOC
内容的提问来源于stack exchange,提问作者Nathaniel Hibbler
相关产品推荐
相关产品推荐

