自动模型方式 - NER 任务
1 课程概览
本课讲解自动模型方式进行 NER(命名实体识别)。NER 本质上是分类任务,也叫序列标注任务。实体词识别是句法分析的基础,句法分析又是 NLP 任务的核心。使用 AutoModelForTokenClassification 加载模型,需要额外加载配置文件 AutoConfig。配置文件包含 id_to_label 映射。
2 核心概念与定义
- NER(Named Entity Recognition):命名实体识别。
- 序列标注任务:NER 的本质,对每个 token 进行分类。
- AutoModelForTokenClassification:专门加载 token 分类模型的类。
- AutoConfig:自动配置,加载配置文件。
- id_to_label:id 到标签的映射。
3 模型与算法详解
NER 的本质
NER 本质上是分类任务,也叫序列标注任务。
- 实体词识别是句法分析的基础
- 句法分析是 NLP 任务的核心
- NER 是序列标注任务(token 级别的分类)
模型加载
使用
AutoModelForTokenClassification加载模型。
my_model = AutoModelForTokenClassification.from_pretrained(model_name)
配置文件
需要额外加载配置文件
AutoConfig。
config = AutoConfig.from_pretrained(model_name)
id_to_label 映射
配置文件包含 id_to_label 映射。
| id | label | 说明 |
|---|---|---|
| 1 | B-ADDRESS | 地址开始 |
| 12 | MOVIE | 电影 |
| ... | ... | ... |
NER 流程
0. 定义变量记录模型名
1. 加载 Tokenizer(分词器)
2. 加载模型(AutoModelForTokenClassification)
3. 加载配置文件(AutoConfig)
4. 数据张量化
5. 送给模型
6. 输出实体识别结果
模型选择
使用 RoBERTa 模型。
| 任务 | 模型 |
|---|---|
| NER | roberta |
实体类型
模型可识别的实体类型。
| 实体 | 说明 |
|---|---|
| ADDRESS | 地址 |
| BOOK | 书名 |
| COMPANY | 公司 |
| GAME | 游戏 |
| ... | ... |
4 数学原理与推导
NER
$$\text{tags} = \text{model}(\text{input_ids}, \text{attention_mask})$$
其中:
- $\text{input_ids}$ 是文本的 id 序列
- $\text{tags}$ 是每个 token 的标签
序列标注
$$P(\text{tag}_i | \text{token}_1, ..., \text{token}_n) = \text{model}(\text{token}_1, ..., \text{token}_n)$$
5 代码示例
import torch
from transformers import AutoConfig, AutoModelForTokenClassification, AutoTokenizer
def dm06_ner():
"""自动模型方式:NER 任务"""
# 0. 定义变量记录模型名
model_name = "C:/software/softwallg/pretrained_model/roberta"
# 1. 加载 Tokenizer(分词器)
my_tokenizer = AutoTokenizer.from_pretrained(model_name)
# 2. 加载模型(使用 AutoModelForTokenClassification)
my_model = AutoModelForTokenClassification.from_pretrained(model_name)
# 3. 加载配置文件(AutoConfig)
config = AutoConfig.from_pretrained(model_name)
# 4. 数据张量化
text = "我爱北京天安门上太阳升"
inputs = my_tokenizer.encode_plus(
text,
return_tensors='pt' # 返回二维张量
)
print(f"输入文本: {text}")
print(f"输入张量: {inputs}")
# 5. 送给模型
my_model.eval()
with torch.no_grad():
output = my_model(**inputs)
# 6. 输出实体识别结果
logits = output.logits
predictions = torch.argmax(logits, dim=2)
# 将 id 转成标签
id_to_label = config.id2label
tokens = my_tokenizer.convert_ids_to_tokens(inputs['input_ids'][0])
print(f"\n实体识别结果:")
for token, pred_id in zip(tokens, predictions[0]):
label = id_to_label.get(pred_id.item(), 'O')
print(f" {token}: {label}")
return my_model
# 测试
if __name__ == "__main__":
print("=== 自动模型方式:NER 任务 ===")
model = dm06_ner()
代码说明
| 代码 | 说明 |
|---|---|
AutoModelForTokenClassification.from_pretrained() | 加载 token 分类模型 |
AutoConfig.from_pretrained() | 加载配置文件 |
config.id2label | id 到标签的映射 |
torch.argmax(logits, dim=2) | 取最大值索引 |
convert_ids_to_tokens() | 将 id 转成 token |
6 重难点与易错提醒
- ❗重点:NER 本质上是分类任务,也叫序列标注任务。
- ❗重点:使用
AutoModelForTokenClassification加载模型。 - ❗重点:需要额外加载配置文件
AutoConfig。 - ⚠️易错:id_to_label 映射在配置文件中。
- 💡深入理解:实体词识别是句法分析的基础,句法分析是 NLP 任务的核心。
7 课堂问答精选
Q1:NER 的本质是什么?
A:NER 本质上是分类任务,也叫序列标注任务。对每个 token 进行分类,识别实体。
Q2:NER 使用什么类加载模型?
A:使用 AutoModelForTokenClassification 加载模型。
Q3:为什么需要加载配置文件?
A:配置文件包含 id_to_label 映射,用于将模型输出的 id 转成对应的标签(如 B-ADDRESS、MOVIE 等)。
Q4:实体词识别和句法分析有什么关系?
A:实体词识别是句法分析的基础,句法分析又是 NLP 任务的核心。要先识别出实体,才能进行句法分析。
8 本课小结
- NER:命名实体识别,本质是序列标注任务。
- 使用
AutoModelForTokenClassification加载模型。 - 需要额外加载配置文件
AutoConfig。 - 配置文件包含 id_to_label 映射。
- 实体词识别是句法分析的基础,句法分析是 NLP 任务的核心。
9 延伸思考
- 具体模型方式如何使用?
- 具体模型和自动模型有什么区别?