问答
原始文本:
huggingface.co/docs/transformers/v4.37.2/en/tasks/question_answering
www.youtube-nocookie.com/embed/ajPx5LwJD-I
问答任务根据问题返回答案。如果您曾经向 Alexa、Siri 或 Google 等虚拟助手询问天气情况,那么您之前使用过问答模型。问答任务有两种常见类型:
- 提取式:从给定的上下文中提取答案。
- 生成式:从上下文中生成一个正确回答问题的答案。
本指南将向您展示如何:
- 在SQuAD数据集上微调DistilBERT以进行提取式问答。
- 使用您微调的模型进行推理。
本教程中演示的任务由以下模型架构支持:
ALBERT, BART, BERT, BigBird, BigBird-Pegasus, BLOOM, CamemBERT, CANINE, ConvBERT, Data2VecText, DeBERTa, DeBERTa-v2, DistilBERT, ELECTRA, ERNIE, ErnieM, Falcon, FlauBERT, FNet, Funnel Transformer, OpenAI GPT-2, GPT Neo, GPT NeoX, GPT-J, I-BERT, LayoutLMv2, LayoutLMv3, LED, LiLT, Longformer, LUKE, LXMERT, MarkupLM, mBART, MEGA, Megatron-BERT, MobileBERT, MPNet, MPT, MRA, MT5, MVP, Nezha, Nyströmformer, OPT, QDQBert, Reformer, RemBERT, RoBERTa, RoBERTa-PreLayerNorm, RoCBert, RoFormer, Splinter, SqueezeBERT, T5, UMT5, XLM, XLM-RoBERTa, XLM-RoBERTa-XL, XLNet, X-MOD, YOSO
在开始之前,请确保已安装所有必要的库:
pip install transformers datasets evaluate
我们鼓励您登录您的 Hugging Face 帐户,这样您就可以上传和与社区分享您的模型。在提示时,输入您的令牌以登录:
>>> from huggingface_hub import notebook_login >>> notebook_login()
加载 SQuAD 数据集
首先加载来自🤗数据集库的 SQuAD 数据集的较小子集。这将让您有机会进行实验,并确保一切正常,然后再花更多时间在完整数据集上进行训练。
>>> from datasets import load_dataset >>> squad = load_dataset("squad", split="train[:5000]")
使用train_test_split方法将数据集的train拆分为训练集和测试集:
>>> squad = squad.train_test_split(test_size=0.2)
然后看一个例子:
>>> squad["train"][0] {'answers': {'answer_start': [515], 'text': ['Saint Bernadette Soubirous']}, 'context': 'Architecturally, the school has a Catholic character. Atop the Main Building\'s gold dome is a golden statue of the Virgin Mary. Immediately in front of the Main Building and facing it, is a copper statue of Christ with arms upraised with the legend "Venite Ad Me Omnes". Next to the Main Building is the Basilica of the Sacred Heart. Immediately behind the basilica is the Grotto, a Marian place of prayer and reflection. It is a replica of the grotto at Lourdes, France where the Virgin Mary reputedly appeared to Saint Bernadette Soubirous in 1858\. At the end of the main drive (and in a direct line that connects through 3 statues and the Gold Dome), is a simple, modern stone statue of Mary.', 'id': '5733be284776f41900661182', 'question': 'To whom did the Virgin Mary allegedly appear in 1858 in Lourdes France?', 'title': 'University_of_Notre_Dame' }
这里有几个重要的字段:
answers:答案标记的起始位置和答案文本。context:模型需要从中提取答案的背景信息。question:模型应该回答的问题。
预处理
www.youtube-nocookie.com/embed/qgaM0weJHpA
接下来的步骤是加载一个 DistilBERT tokenizer 来处理question和context字段:
>>> from transformers import AutoTokenizer >>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
有一些特定于问答任务的预处理步骤,您应该注意:
- 数据集中的一些示例可能具有超出模型最大输入长度的非常长的
context。为了处理更长的序列,只截断context,设置truncation="only_second"。 - 接下来,通过设置
return_offset_mapping=True将答案的起始和结束位置映射到原始的context。 - 有了映射,现在您可以找到答案的起始和结束标记。使用
sequence_ids方法找到偏移的哪部分对应于question,哪部分对应于context。
以下是您可以创建的函数,用于截断和映射answer的起始和结束标记到context:
>>> def preprocess_function(examples): ... questions = [q.strip() for q in examples["question"]] ... inputs = tokenizer( ... questions, ... examples["context"], ... max_length=384, ... truncation="only_second", ... return_offsets_mapping=True, ... padding="max_length", ... ) ... offset_mapping = inputs.pop("offset_mapping") ... answers = examples["answers"] ... start_positions = [] ... end_positions = [] ... for i, offset in enumerate(offset_mapping): ... answer = answers[i] ... start_char = answer["answer_start"][0] ... end_char = answer["answer_start"][0] + len(answer["text"][0]) ... sequence_ids = inputs.sequence_ids(i) ... # Find the start and end of the context ... idx = 0 ... while sequence_ids[idx] != 1: ... idx += 1 ... context_start = idx ... while sequence_ids[idx] == 1: ... idx += 1 ... context_end = idx - 1 ... # If the answer is not fully inside the context, label it (0, 0) ... if offset[context_start][0] > end_char or offset[context_end][1] < start_char: ... start_positions.append(0) ... end_positions.append(0) ... else: ... # Otherwise it's the start and end token positions ... idx = context_start ... while idx <= context_end and offset[idx][0] <= start_char: ... idx += 1 ... start_positions.append(idx - 1) ... idx = context_end ... while idx >= context_start and offset[idx][1] >= end_char: ... idx -= 1 ... end_positions.append(idx + 1) ... inputs["start_positions"] = start_positions ... inputs["end_positions"] = end_positions ... return inputs
要在整个数据集上应用预处理函数,请使用🤗 Datasets map函数。您可以通过设置batched=True来加速map函数,以一次处理数据集的多个元素。删除您不需要的任何列:
>>> tokenized_squad = squad.map(preprocess_function, batched=True, remove_columns=squad["train"].column_names)
现在使用 DefaultDataCollator 创建一批示例。与🤗 Transformers 中的其他数据收集器不同,DefaultDataCollator 不会应用任何额外的预处理,如填充。
Pytorch 隐藏 Pytorch 内容
>>> from transformers import DefaultDataCollator >>> data_collator = DefaultDataCollator()
TensorFlow 隐藏 TensorFlow 内容
>>> from transformers import DefaultDataCollator >>> data_collator = DefaultDataCollator(return_tensors="tf")
训练
Pytorch 隐藏 Pytorch 内容
如果您不熟悉使用 Trainer 微调模型,请查看这里的基本教程 here!
您现在可以开始训练您的模型了!使用 AutoModelForQuestionAnswering 加载 DistilBERT:
>>> from transformers import AutoModelForQuestionAnswering, TrainingArguments, Trainer >>> model = AutoModelForQuestionAnswering.from_pretrained("distilbert-base-uncased")
此时,只剩下三个步骤:
- 在 TrainingArguments 中定义您的训练超参数。唯一必需的参数是
output_dir,指定保存模型的位置。通过设置push_to_hub=True(您需要登录到 Hugging Face 才能上传模型),您将把这个模型推送到 Hub。 - 将训练参数传递给 Trainer,同时还有模型、数据集、tokenizer 和数据收集器。
- 调用 train()来微调您的模型。
>>> training_args = TrainingArguments( ... output_dir="my_awesome_qa_model", ... evaluation_strategy="epoch", ... learning_rate=2e-5, ... per_device_train_batch_size=16, ... per_device_eval_batch_size=16, ... num_train_epochs=3, ... weight_decay=0.01, ... push_to_hub=True, ... ) >>> trainer = Trainer( ... model=model, ... args=training_args, ... train_dataset=tokenized_squad["train"], ... eval_dataset=tokenized_squad["test"], ... tokenizer=tokenizer, ... data_collator=data_collator, ... ) >>> trainer.train()
训练完成后,使用 push_to_hub()方法将您的模型共享到 Hub,以便每个人都可以使用您的模型:
>>> trainer.push_to_hub()
TensorFlow 隐藏 TensorFlow 内容
如果您不熟悉使用 Keras 微调模型,请查看这里的基本教程 here!
要在 TensorFlow 中微调模型,请首先设置优化器函数、学习率调度和一些训练超参数:
>>> from transformers import create_optimizer >>> batch_size = 16 >>> num_epochs = 2 >>> total_train_steps = (len(tokenized_squad["train"]) // batch_size) * num_epochs >>> optimizer, schedule = create_optimizer( ... init_lr=2e-5, ... num_warmup_steps=0, ... num_train_steps=total_train_steps, ... )
然后您可以使用 TFAutoModelForQuestionAnswering 加载 DistilBERT:
>>> from transformers import TFAutoModelForQuestionAnswering >>> model = TFAutoModelForQuestionAnswering("distilbert-base-uncased")
使用 prepare_tf_dataset()将数据集转换为tf.data.Dataset格式:
>>> tf_train_set = model.prepare_tf_dataset( ... tokenized_squad["train"], ... shuffle=True, ... batch_size=16, ... collate_fn=data_collator, ... ) >>> tf_validation_set = model.prepare_tf_dataset( ... tokenized_squad["test"], ... shuffle=False, ... batch_size=16, ... collate_fn=data_collator, ... )
使用compile为训练配置模型:
>>> import tensorflow as tf >>> model.compile(optimizer=optimizer)
在开始训练之前的最后一件事是提供一种将您的模型推送到 Hub 的方法。这可以通过在 PushToHubCallback 中指定推送模型和标记器的位置来完成:
>>> from transformers.keras_callbacks import PushToHubCallback >>> callback = PushToHubCallback( ... output_dir="my_awesome_qa_model", ... tokenizer=tokenizer, ... )
最后,您已经准备好开始训练您的模型了!使用您的训练和验证数据集、时代数以及回调函数调用fit来微调模型:
>>> model.fit(x=tf_train_set, validation_data=tf_validation_set, epochs=3, callbacks=[callback])
一旦训练完成,您的模型将自动上传到 Hub,这样每个人都可以使用它!
要了解如何为问题回答微调模型的更深入示例,请查看相应的PyTorch 笔记本或TensorFlow 笔记本。
评估
问题回答的评估需要大量的后处理。为了不占用太多时间,本指南跳过了评估步骤。Trainer 仍然在训练过程中计算评估损失,因此您不会完全不了解模型的性能。
如果您有更多时间,并且对如何评估问题回答模型感兴趣,请查看🤗 Hugging Face 课程中的问题回答章节!
推理
很好,现在您已经微调了一个模型,可以用它进行推理了!
提出一个问题和一些上下文,您希望模型进行预测:
>>> question = "How many programming languages does BLOOM support?" >>> context = "BLOOM has 176 billion parameters and can generate text in 46 languages natural languages and 13 programming languages."
尝试使用您微调过的模型进行推理的最简单方法是在 pipeline()中使用它。用您的模型实例化一个问题回答的pipeline,并将文本传递给它:
>>> from transformers import pipeline >>> question_answerer = pipeline("question-answering", model="my_awesome_qa_model") >>> question_answerer(question=question, context=context) {'score': 0.2058267742395401, 'start': 10, 'end': 95, 'answer': '176 billion parameters and can generate text in 46 languages natural languages and 13'}
如果您愿意,也可以手动复制pipeline的结果:
Pytorch 隐藏 Pytorch 内容
对文本进行标记化并返回 PyTorch 张量:
>>> from transformers import AutoTokenizer >>> tokenizer = AutoTokenizer.from_pretrained("my_awesome_qa_model") >>> inputs = tokenizer(question, context, return_tensors="pt")
将您的输入传递给模型并返回logits:
>>> import torch >>> from transformers import AutoModelForQuestionAnswering >>> model = AutoModelForQuestionAnswering.from_pretrained("my_awesome_qa_model") >>> with torch.no_grad(): ... outputs = model(**inputs)
从模型输出中获取开始和结束位置的最高概率:
>>> answer_start_index = outputs.start_logits.argmax() >>> answer_end_index = outputs.end_logits.argmax()
解码预测的标记以获取答案:
>>> predict_answer_tokens = inputs.input_ids[0, answer_start_index : answer_end_index + 1] >>> tokenizer.decode(predict_answer_tokens) '176 billion parameters and can generate text in 46 languages natural languages and 13'
TensorFlow 隐藏 TensorFlow 内容
对文本进行标记化并返回 TensorFlow 张量:
>>> from transformers import AutoTokenizer >>> tokenizer = AutoTokenizer.from_pretrained("my_awesome_qa_model") >>> inputs = tokenizer(question, text, return_tensors="tf")
将您的输入传递给模型并返回logits:
>>> from transformers import TFAutoModelForQuestionAnswering >>> model = TFAutoModelForQuestionAnswering.from_pretrained("my_awesome_qa_model") >>> outputs = model(**inputs)
从模型输出中获取开始和结束位置的最高概率:
>>> answer_start_index = int(tf.math.argmax(outputs.start_logits, axis=-1)[0]) >>> answer_end_index = int(tf.math.argmax(outputs.end_logits, axis=-1)[0])
解码预测的标记以获取答案:
>>> predict_answer_tokens = inputs.input_ids[0, answer_start_index : answer_end_index + 1] >>> tokenizer.decode(predict_answer_tokens) '176 billion parameters and can generate text in 46 languages natural languages and 13'
Transformers 4.37 中文文档(三)(2)https://developer.aliyun.com/article/1564649