NLP transformers - token 分类

文章目录



标记分类为句子中的各个标记分配标签。最常见的标记分类任务之一是命名实体识别 (NER)。 NER 尝试为句子中的每个实体查找标签,例如人、位置或组织。

本指南将向您展示如何:

  1. WNUT 17数据集上微调DistilBERT以检测新实体。
  2. 使用您的微调模型进行推理。

在开始之前,请确保已安装所有必需的库:

python 复制代码
pip install transformers datasets evaluate seqeval

我们鼓励您登录 Hugging Face 帐户,以便您可以上传模型并与社区分享。出现提示时,输入您的令牌进行登录:

python 复制代码
from huggingface_hub import notebook_login

notebook_login()

加载 WNUT 17 数据集

首先从 🤗 数据集库加载 WNUT 17 数据集:

python 复制代码
from datasets import load_dataset

wnut = load_dataset("wnut_17")

然后看一个数据样例:

python 复制代码
wnut["train"][0]

{'id': '0',
 'ner_tags': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0],
 'tokens': ['@paulwalk', 'It', "'s", 'the', 'view', 'from', 'where', 'I', "'m", 'living', 'for', 'two', 'weeks', '.', 'Empire', 'State', 'Building', '=', 'ESB', '.', 'Pretty', 'bad', 'storm', 'here', 'last', 'evening', '.']
}

每个数字ner_tags代表一个实体。将数字转换为其标签名称 以找出实体是:

python 复制代码
label_list = wnut["train"].features[f"ner_tags"].feature.names
label_list

[
    "O",
    "B-corporation",
    "I-corporation",
    "B-creative-work",
    "I-creative-work",
    "B-group",
    "I-group",
    "B-location",
    "I-location",
    "B-person",
    "I-person",
    "B-product",
    "I-product",
]

每个前缀的字母ner_tag表示实体的标记位置:

  • B-表示实体的开始。
  • I-表示令牌包含在同一实体内(例如,State令牌是实体的一部分,如 Empire State Building)。
  • 0表示该 token 不对应于任何实体。

预处理

下一步是加载 DistilBERT 分词器来预处理该tokens字段:

python 复制代码
from transformers import AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased")

正如您在上面的示例tokens字段中看到的,看起来输入已经被tokenized。

但输入实际上尚未被标记化,您需要设置is_split_into_words=True将单词标记为子词。例如:

python 复制代码
example = wnut["train"][0]
tokenized_input = tokenizer(example["tokens"], is_split_into_words=True)
tokens = tokenizer.convert_ids_to_tokens(tokenized_input["input_ids"])
tokens
['[CLS]', '@', 'paul', '##walk', 'it', "'", 's', 'the', 'view', 'from', 'where', 'i', "'", 'm', 'living', 'for', 'two', 'weeks', '.', 'empire', 'state', 'building', '=', 'es', '##b', '.', 'pretty', 'bad', 'storm', 'here', 'last', 'evening', '.', '[SEP]']

然而,这会添加一些特殊的标记[CLS][SEP],并且子词tokenization 会在输入和标签之间造成不匹配。

对应于单个标签的单个单词 现在可以被分成两个子单词。您需要通过以下方式重新对齐标记和标签:

  1. 使用 word_ids 方法将 所有tokens 映射到其相应的单词。
  2. 将标签分配-100给特殊标记[CLS][SEP],因此 PyTorch 损失函数会忽略它们(请参阅CrossEntropyLoss)。
  3. 仅标记给定单词的第一个标记。分配-100给同一单词的其他子标记。

以下是如何创建一个函数来重新对齐标记和标签,并将序列截断为不长于 DistilBERT 的最大输入长度:

python 复制代码
def tokenize_and_align_labels(examples):
    tokenized_inputs = tokenizer(examples["tokens"], truncation=True, is_split_into_words=True)

    labels = []
    for i, label in enumerate(examples[f"ner_tags"]):
        word_ids = tokenized_inputs.word_ids(batch_index=i)  # Map tokens to their respective word.
        previous_word_idx = None
        label_ids = []
        for word_idx in word_ids:  # Set the special tokens to -100.
            if word_idx is None:
                label_ids.append(-100)
            elif word_idx != previous_word_idx:  # Only label the first token of a given word.
                label_ids.append(label[word_idx])
            else:
                label_ids.append(-100)
            previous_word_idx = word_idx
        labels.append(label_ids)

    tokenized_inputs["labels"] = labels
    return tokenized_inputs

要将预处理函数 应用于整个数据集,请使用 🤗 数据集map函数。您可以通过设置 batched=True 一次处理数据集的多个元素来加速该map函数:

python 复制代码
tokenized_wnut = wnut.map(tokenize_and_align_labels, batched=True)

现在使用 DataCollatorWithPadding创建一批示例。在整理过程中动态地将句子填充 到 批次中的最长长度,比将 整个数据集 填充到 最大长度 更有效。


python 复制代码
from transformers import DataCollatorForTokenClassification

data_collator = DataCollatorForTokenClassification(tokenizer=tokenizer)

Evaluate

在训练期间包含指标通常有助于评估模型的性能。您可以使用 🤗 Evaluate库快速加载评估方法。对于此任务,加载seqeval框架(请参阅 🤗 评估快速浏览以了解有关如何加载和计算指标的更多信息)。

Seqeval 实际上会产生几个分数:精确度、召回率、F1 和准确度。

python 复制代码
import evaluate

seqeval = evaluate.load("seqeval")

首先获取 NER 标签,然后创建一个 传递真实预测 和真实标签的函数 给 compute 来计算分数:

python 复制代码
import numpy as np

labels = [label_list[i] for i in example[f"ner_tags"]]


def compute_metrics(p):
    predictions, labels = p
    predictions = np.argmax(predictions, axis=2)

    true_predictions = [
        [label_list[p] for (p, l) in zip(prediction, label) if l != -100]
        for prediction, label in zip(predictions, labels)
    ]
    true_labels = [
        [label_list[l] for (p, l) in zip(prediction, label) if l != -100]
        for prediction, label in zip(predictions, labels)
    ]

    results = seqeval.compute(predictions=true_predictions, references=true_labels)
    return {
        "precision": results["overall_precision"],
        "recall": results["overall_recall"],
        "f1": results["overall_f1"],
        "accuracy": results["overall_accuracy"],
    }

您的 compute_metrics 函数现在已准备就绪,您将在设置训练时返回该函数。


Train

在开始训练模型之前,请使用 id2labellabel2id 创建 预期 id 到其标签的映射:

python 复制代码
id2label = {
    0: "O",
    1: "B-corporation",
    2: "I-corporation",
    3: "B-creative-work",
    4: "I-creative-work",
    5: "B-group",
    6: "I-group",
    7: "B-location",
    8: "I-location",
    9: "B-person",
    10: "I-person",
    11: "B-product",
    12: "I-product",
}
label2id = {
    "O": 0,
    "B-corporation": 1,
    "I-corporation": 2,
    "B-creative-work": 3,
    "I-creative-work": 4,
    "B-group": 5,
    "I-group": 6,
    "B-location": 7,
    "I-location": 8,
    "B-person": 9,
    "I-person": 10,
    "B-product": 11,
    "I-product": 12,
}

如果您不熟悉使用 Trainer微调模型,请查看此处的基本教程!

您现在就可以开始训练您的模型了!使用AutoModelForTokenClassification加载 DistilBERT以及预期标签的数量和标签映射:

python 复制代码
from transformers import AutoModelForTokenClassification, TrainingArguments, Trainer

model = AutoModelForTokenClassification.from_pretrained(
    "distilbert/distilbert-base-uncased", num_labels=13, id2label=id2label, label2id=label2id
)

此时,只剩下三步:

  1. TrainingArguments中定义训练超参数。唯一必需的参数是output_dir指定保存模型的位置。您可以通过设置 push_to_hub=True 将此模型推送到 Hub (您需要登录 Hugging Face 才能上传模型)。在每个 epoch 结束时,Trainer将评估 seqeval 分数并保存训练检查点。
  2. 将训练参数 以及模型、数据集、分词器、数据整理器和 compute_metrics 函数传递给 Trainer
  3. 调用train() 来微调您的模型。
python 复制代码
training_args = TrainingArguments(
    output_dir="my_awesome_wnut_model",
    learning_rate=2e-5,
    per_device_train_batch_size=16,
    per_device_eval_batch_size=16,
    num_train_epochs=2,
    weight_decay=0.01,
    evaluation_strategy="epoch",
    save_strategy="epoch",
    load_best_model_at_end=True,
    push_to_hub=True,
)

trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=tokenized_wnut["train"],
    eval_dataset=tokenized_wnut["test"],
    tokenizer=tokenizer,
    data_collator=data_collator,
    compute_metrics=compute_metrics,
)

trainer.train()

训练完成后,使用 push_to_hub()方法将您的模型共享到 Hub,以便每个人都可以使用您的模型:

python 复制代码
trainer.push_to_hub()

有关如何微调标记分类模型的更深入示例,请查看相应的 PyTorch 笔记本TensorFlow 笔记本


推理

太好了,现在您已经微调了模型,您可以使用它进行推理!

获取一些您想要进行推理的文本:

python 复制代码
text = "The Golden State Warriors are an American professional basketball team based in San Francisco."

尝试微调模型进行推理的最简单方法是在pipeline()中使用它。使用您的模型实例化pipelinefor NER,并将您的文本传递给它:

python 复制代码
from transformers import pipeline

classifier = pipeline("ner", model="stevhliu/my_awesome_wnut_model")
classifier(text)

json 复制代码
[{'entity': 'B-location',
  'score': 0.42658573,
  'index': 2,
  'word': 'golden',
  'start': 4,
  'end': 10},
 {'entity': 'I-location',
  'score': 0.35856336,
  'index': 3,
  'word': 'state',
  'start': 11,
  'end': 16},
 {'entity': 'B-group',
  'score': 0.3064001,
  'index': 4,
  'word': 'warriors',
  'start': 17,
  'end': 25},
 {'entity': 'B-location',
  'score': 0.65523505,
  'index': 13,
  'word': 'san',
  'start': 80,
  'end': 83},
 {'entity': 'B-location',
  'score': 0.4668663,
  'index': 14,
  'word': 'francisco',
  'start': 84,
  'end': 93}]

pipeline如果您愿意,您还可以手动复制结果:


对文本进行分词 并返回 PyTorch 张量:

python 复制代码
from transformers import AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("stevhliu/my_awesome_wnut_model")
inputs = tokenizer(text, return_tensors="pt")

将您的输入传递给模型并返回logits

python 复制代码
from transformers import AutoModelForTokenClassification

model = AutoModelForTokenClassification.from_pretrained("stevhliu/my_awesome_wnut_model")
with torch.no_grad():
    logits = model(**inputs).logits

获取概率最高的类,并使用模型的id2label映射将其转换为文本标签:

python 复制代码
predictions = torch.argmax(logits, dim=2)
predicted_token_class = [model.config.id2label[t.item()] for t in predictions[0]]
predicted_token_class

['O',
 'O',
 'B-location',
 'I-location',
 'B-group',
 'O',
 'O',
 'O',
 'O',
 'O',
 'O',
 'O',
 'O',
 'B-location',
 'B-location',
 'O',
 'O']

2024-04-29(一)

相关推荐
吉小雨5 分钟前
PyTorch经典模型
人工智能·pytorch·python
无名之逆30 分钟前
计算机专业的就业方向
java·开发语言·c++·人工智能·git·考研·面试
CV-杨帆35 分钟前
大语言模型-教育方向数据集
人工智能·语言模型·自然语言处理
Jackilina_Stone1 小时前
【AI】简单了解AIGC与ChatGPT
人工智能·chatgpt·aigc
paixiaoxin1 小时前
学术新手进阶:Zotero插件全解锁,打造你的高效研究体验
人工智能·经验分享·笔记·机器学习·学习方法·zotero
破晓的历程1 小时前
【机器学习】:解锁数据背后的智慧宝藏——深度探索与未来展望
人工智能·机器学习
AiBoxss1 小时前
AI工具集推荐,简化工作流程!提升效率不是梦!
人工智能
crownyouyou1 小时前
最简单的一文安装Pytorch+CUDA
人工智能·pytorch·python
WenGyyyL1 小时前
变脸大师:基于OpenCV与Dlib的人脸换脸技术实现
人工智能·python·opencv
首席数智官1 小时前
阿里云AI基础设施全面升级,模型算力利用率提升超20%
人工智能·阿里云·云计算