2. 请使用transformers库中的预训练中文模型(如hfl/chinese-bert-wwm或uer/roberta-base-finetuned-cluener2020-chinese),对以下文本进行命名实体识别。 输入文本:梅兰芳是京剧艺术大师,擅长《贵妃醉酒》《霸王别姬》等剧目。他曾率团赴美国、苏联演出,推动中国文化传播。 任务要求: (4)加载transformers预训练中文NER模型(5分) (5)对以上“输入文本”进行实体识别(25分) (6)输出格式如下:(10分) [ {"word": "梅兰芳", "entity": "PER"}, {"word": "《贵妃醉酒》", "entity": "WORK"}, {"word": "《霸王别姬》", "entity": "WORK"}, {"word": "美国", "entity": "LOC"}, {"word": "苏联", "entity": "LOC"}, {"word": "中国", "entity": "LOC"} ] 源代码: 运行结果截图:
时间: 2025-05-26 18:26:26 浏览: 33
### 使用 Hugging Face Transformers 库加载预训练中文 NER 模型
要使用 Hugging Face 的 `transformers` 库加载预训练的中文命名实体识别(NER)模型并对文本进行处理,可以按照以下步骤操作。这里以 `uer/roberta-base-finetuned-cluener2020-chinese` 模型为例,该模型专为中文命名实体识别任务进行了微调[^2]。
#### 安装必要的库
首先需要安装 `transformers` 和 `torch` 或 `tensorflow`,这是运行模型所必需的依赖项。
```bash
pip install transformers torch
```
#### 加载模型和分词器
接下来编写代码来加载模型和分词器,并对输入文本进行预测。
```python
from transformers import AutoTokenizer, AutoModelForTokenClassification
import torch
# 初始化分词器和模型
tokenizer = AutoTokenizer.from_pretrained("uer/roberta-base-finetuned-cluener2020-chinese")
model = AutoModelForTokenClassification.from_pretrained("uer/roberta-base-finetuned-cluener2020-chinese")
# 输入待处理的文本
text = "京剧大师梅兰芳是中国著名的表演艺术家,他主演过许多经典剧目,如《霸王别姬》和《贵妃醉酒》,其艺术成就享誉世界。"
# 对文本进行分词
tokens = tokenizer(text, return_tensors="pt", max_length=128, truncation=True)
# 获取模型预测结果
with torch.no_grad():
outputs = model(**tokens)
predictions = torch.argmax(outputs.logits, dim=-1).squeeze().tolist()
token_ids = tokens["input_ids"].squeeze().tolist()
# 映射标签到原始单词
labels = model.config.id2label
result_tokens = []
for token_id, pred in zip(token_ids, predictions):
word = tokenizer.decode([token_id])
label = labels[pred]
if not word.startswith('##'):
result_tokens.append((word.replace(" ", ""), label))
# 输出 JSON 结果
ner_results = {"entities": []}
current_entity = None
entity_type = None
for tok, lbl in result_tokens:
if lbl.startswith("B-"): # 开始一个新的实体
current_entity = tok
entity_type = lbl.split("-")[1]
elif lbl.startswith("I-") and current_entity is not None: # 继续当前实体
current_entity += tok
else: # 当前字符不属于任何实体
if current_entity is not None:
ner_results["entities"].append({"text": current_entity, "type": entity_type})
current_entity = None
entity_type = None
print(ner_results)
```
这段代码实现了以下几个功能:
1. **加载模型与分词器**:通过 `AutoTokenizer` 和 `AutoModelForTokenClassification` 类分别加载适合 CLUE NER 数据集的 RoBERTa 模型及其对应的分词器。
2. **文本分词**:将输入字符串转化为模型可接受的形式。
3. **推理阶段**:利用已加载好的模型对输入序列做出预测。
4. **解析输出**:把模型产生的 logits 转换成最终的人类可读标签,并进一步整理成易于理解的 JSON 格式输出。
#### 示例输出
假设我们有如下一段描述京剧大师梅兰芳的文字,经过上述流程后可能会获得这样的 JSON 格式的实体抽取结果:
```json
{
"entities": [
{
"text": "梅兰芳",
"type": "PERSON"
},
{
"text": "中国",
"type": "LOC"
},
{
"text": "霸王别姬",
"type": "WORK_OF_ART"
},
{
"text": "贵妃醉酒",
"type": "WORK_OF_ART"
}
]
}
```
---
###
阅读全文
相关推荐



















