|
|
from datasets import load_dataset |
|
|
from transformers import T5ForConditionalGeneration, T5TokenizerFast, Trainer, TrainingArguments |
|
|
import evaluate |
|
|
import numpy as np |
|
|
|
|
|
|
|
|
dataset = load_dataset("cnn_dailymail", "3.0.0") |
|
|
|
|
|
|
|
|
tokenizer = T5TokenizerFast.from_pretrained("t5-small") |
|
|
model = T5ForConditionalGeneration.from_pretrained("t5-small") |
|
|
|
|
|
|
|
|
def preprocess_function(examples): |
|
|
inputs = ["summarize: " + doc for doc in examples["article"]] |
|
|
model_inputs = tokenizer(inputs, max_length=512, truncation=True) |
|
|
labels = tokenizer(text_target=examples["highlights"], max_length=128, truncation=True) |
|
|
model_inputs["labels"] = labels["input_ids"] |
|
|
return model_inputs |
|
|
|
|
|
tokenized_datasets = dataset.map(preprocess_function, batched=True, remove_columns=["article", "highlights", "id"]) |
|
|
|
|
|
|
|
|
rouge = evaluate.load("rouge") |
|
|
|
|
|
def compute_metrics(eval_pred): |
|
|
predictions, labels = eval_pred |
|
|
decoded_preds = tokenizer.batch_decode(predictions, skip_special_tokens=True) |
|
|
labels = np.where(labels != -100, labels, tokenizer.pad_token_id) |
|
|
decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True) |
|
|
result = rouge.compute(predictions=decoded_preds, references=decoded_labels) |
|
|
return {k: v * 100 for k, v in result.items()} |
|
|
|
|
|
|
|
|
training_args = TrainingArguments( |
|
|
output_dir="./results", |
|
|
evaluation_strategy="epoch", |
|
|
learning_rate=3e-4, |
|
|
per_device_train_batch_size=2, |
|
|
per_device_eval_batch_size=2, |
|
|
num_train_epochs=1, |
|
|
save_strategy="epoch", |
|
|
predict_with_generate=True, |
|
|
push_to_hub=False |
|
|
) |
|
|
|
|
|
|
|
|
trainer = Trainer( |
|
|
model=model, |
|
|
args=training_args, |
|
|
train_dataset=tokenized_datasets["train"].select(range(2000)), |
|
|
eval_dataset=tokenized_datasets["validation"].select(range(500)), |
|
|
tokenizer=tokenizer, |
|
|
compute_metrics=compute_metrics |
|
|
) |
|
|
|
|
|
trainer.train() |
|
|
trainer.save_model("./t5-news-summarizer") |
|
|
tokenizer.save_pretrained("./t5-news-summarizer") |
|
|
|