譯者 | 布加迪
審校 | 重樓
使用Hugging Face Transformers對T5模型進行微調(diào)以處理問題回答任務很簡單:只需為模型提供問題和上下文,它就能學會生成正確的答案。
T5是一個功能強大的模型,旨在幫助計算機理解和生成人類語言。T5的全稱是“文本到文本轉換器”。它是一個可以完成許多語言任務的模型。T5將所有任務視為文本到文本問題。我們在本文中將學習如何優(yōu)化T5以回答問題。
安裝所需的庫
首先,我們必須安裝必要的庫:
pip install transformers datasets torch
- Transformer:提供T5模型及其他Transformer架構的Hugging Face庫。
- 數(shù)據(jù)集:訪問和處理數(shù)據(jù)集的庫。
- Torch:幫助構建和訓練神經(jīng)網(wǎng)絡的深度學習庫。
加載數(shù)據(jù)集
為了對T5進行微調(diào)以回答問題,我們將使用BoolQ數(shù)據(jù)集,該數(shù)據(jù)集含有答案為二進制(是/否)的問題/答案對。你可以使用Hugging Face的數(shù)據(jù)集庫來加載BoolQ數(shù)據(jù)集。
from datasets import load_dataset
# Load the BoolQ dataset
dataset = load_dataset("boolq")
# Display the first few rows of the dataset
print(dataset['train'].to_pandas().head())
預處理數(shù)據(jù)
T5要求輸入采用特定的格式。我們需要更改數(shù)據(jù)集,以便問題和答案都是文本格式。輸入格式為問題:上下文:,輸出將是答案?,F(xiàn)在,我們需要加載T5模型及其分詞器(Tokenizer)。分詞器將把我們的文本輸入轉換成模型可以理解的詞元ID(token ID)。接下來,我們需要對輸入和輸出數(shù)據(jù)進行分詞。分詞器將文本轉換成輸入ID和注意力掩碼,這是訓練模型所必需的。
from transformers import T5Tokenizer, T5ForConditionalGeneration, Trainer, TrainingArguments
# Initialize the T5 tokenizer and model (T5-small in this case)
tokenizer = T5Tokenizer.from_pretrained("t5-small")
model = T5ForConditionalGeneration.from_pretrained("t5-small")
# Preprocessing the dataset: Prepare input-output pairs for T5
def preprocess_function(examples):
inputs = [f"Question: {question} Passage: {passage}" for question, passage in zip(examples['question'], examples['passage'])]
targets = ['true' if answer else 'false' for answer in examples['answer']]
# Tokenize inputs and outputs
model_inputs = tokenizer(inputs, max_length=512, truncation=True, padding='max_length')
labels = tokenizer(targets, max_length=10, truncation=True, padding='max_length')
model_inputs["labels"] = labels["input_ids"]
return model_inputs
# Preprocess the dataset
tokenized_dataset = dataset.map(preprocess_function, batched=True)
微調(diào)T5
現(xiàn)在數(shù)據(jù)已經(jīng)準備好了,我們可以對T5模型進行微調(diào)了。Hugging的Trainer API通過處理訓練循環(huán)、優(yōu)化和評估簡化了這個過程。
from transformers import Trainer, TrainingArguments
training_args = TrainingArguments(
output_dir="./results",
evaluation_strategy="epoch",
learning_rate=2e-5,
per_device_train_batch_size=8,
per_device_eval_batch_size=8,
num_train_epochs=3,
weight_decay=0.01,
logging_dir="./logs",
logging_steps=10,
)
# Initialize the Trainer
trainer = Trainer(
model=model,
args=training_args,
train_dataset=tokenized_dataset["train"],
eval_dataset=tokenized_dataset["validation"],
)
# Fine-tune the model
trainer.train()
評估模型
在微調(diào)之后,重要的是在驗證集上評估模型,看看它如何很好地回答問題。你可以使用Trainer的評估方法。
# Evaluate the model on the validation dataset
eval_results = trainer.evaluate()
# Print the evaluation results
print(f"Evaluation results: {eval_results}")
Evaluation results: {‘eval_loss’: 0.03487783297896385, ‘eval_runtime’: 37.2638, ‘eval_samples_per_second’: 87.753, ‘eval_steps_per_second’: 10.976, ‘epoch’: 3.0}
進行預測
一旦T5模型經(jīng)過微調(diào)和評估,我們就可以用它來預測新的問題回答任務。為此,我們可以準備一個新的輸入(問題和上下文),對其進行分詞,從模型生成輸出(答案)。
from transformers import T5Tokenizer, T5ForConditionalGeneration
# Load the fine-tuned model and tokenizer
model = T5ForConditionalGeneration.from_pretrained("./results")
tokenizer = T5Tokenizer.from_pretrained("t5-base")
# Prepare a new input
input_text = "question: Is the sky blue? context: The sky is blue on a clear day."
# Tokenize the input
input_ids = tokenizer(input_text, return_tensors="pt").input_ids
# Generate the answer using the model
output_ids = model.generate(input_ids)
# Decode the generated tokens to get the predicted answer
predicted_answer = tokenizer.decode(output_ids[0], skip_special_tokens=True)
# Print the predicted answer
print(f"Predicted answer: {predicted_answer}") # Predicted answer: yes
結論
總之,微調(diào)T5可以幫助它更好地回答問題。我們學習了如何準備數(shù)據(jù)和訓練模型。使用Hugging庫使這個過程更容易。訓練后,T5可以聽懂問題并給出正確的答案。這對聊天機器人或搜索引擎等許多應用大有幫助。
原文標題:How to Fine-Tune T5 for Question Answering Tasks with Hugging Face Transformers,作者:Jayita Gulati