譯者 | 布加迪
審校 | 重樓
使用Hugging Face Transformers對(duì)T5模型進(jìn)行微調(diào)以處理問題回答任務(wù)很簡(jiǎn)單:只需為模型提供問題和上下文,它就能學(xué)會(huì)生成正確的答案。
T5是一個(gè)功能強(qiáng)大的模型,旨在幫助計(jì)算機(jī)理解和生成人類語言。T5的全稱是“文本到文本轉(zhuǎn)換器”。它是一個(gè)可以完成許多語言任務(wù)的模型。T5將所有任務(wù)視為文本到文本問題。我們?cè)诒疚闹袑W(xué)習(xí)如何優(yōu)化T5以回答問題。
安裝所需的庫
首先,我們必須安裝必要的庫:
pip install transformers datasets torch
- Transformer:提供T5模型及其他Transformer架構(gòu)的Hugging Face庫。
- 數(shù)據(jù)集:訪問和處理數(shù)據(jù)集的庫。
- Torch:幫助構(gòu)建和訓(xùn)練神經(jīng)網(wǎng)絡(luò)的深度學(xué)習(xí)庫。
加載數(shù)據(jù)集
為了對(duì)T5進(jìn)行微調(diào)以回答問題,我們將使用BoolQ數(shù)據(jù)集,該數(shù)據(jù)集含有答案為二進(jìn)制(是/否)的問題/答案對(duì)。你可以使用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())
預(yù)處理數(shù)據(jù)
T5要求輸入采用特定的格式。我們需要更改數(shù)據(jù)集,以便問題和答案都是文本格式。輸入格式為問題:上下文:,輸出將是答案。現(xiàn)在,我們需要加載T5模型及其分詞器(Tokenizer)。分詞器將把我們的文本輸入轉(zhuǎn)換成模型可以理解的詞元ID(token ID)。接下來,我們需要對(duì)輸入和輸出數(shù)據(jù)進(jìn)行分詞。分詞器將文本轉(zhuǎn)換成輸入ID和注意力掩碼,這是訓(xùn)練模型所必需的。
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)準(zhǔn)備好了,我們可以對(duì)T5模型進(jìn)行微調(diào)了。Hugging的Trainer API通過處理訓(xùn)練循環(huán)、優(yōu)化和評(píng)估簡(jiǎn)化了這個(gè)過程。
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()
評(píng)估模型
在微調(diào)之后,重要的是在驗(yàn)證集上評(píng)估模型,看看它如何很好地回答問題。你可以使用Trainer的評(píng)估方法。
# 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}
進(jìn)行預(yù)測(cè)
一旦T5模型經(jīng)過微調(diào)和評(píng)估,我們就可以用它來預(yù)測(cè)新的問題回答任務(wù)。為此,我們可以準(zhǔn)備一個(gè)新的輸入(問題和上下文),對(duì)其進(jìn)行分詞,從模型生成輸出(答案)。
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
結(jié)論
總之,微調(diào)T5可以幫助它更好地回答問題。我們學(xué)習(xí)了如何準(zhǔn)備數(shù)據(jù)和訓(xùn)練模型。使用Hugging庫使這個(gè)過程更容易。訓(xùn)練后,T5可以聽懂問題并給出正確的答案。這對(duì)聊天機(jī)器人或搜索引擎等許多應(yīng)用大有幫助。
原文標(biāo)題:How to Fine-Tune T5 for Question Answering Tasks with Hugging Face Transformers,作者:Jayita Gulati