Transformers 文档
图像字幕
并获得增强的文档体验
开始使用
图像字幕
图像字幕任务是对给定图像生成文字描述。常见的实际应用包括帮助视障人士导航不同的场景。因此,图像字幕通过向人们描述图像来帮助提高内容的可访问性。
本指南将向您展示如何:
- 微调图像字幕模型。
- 使用微调模型进行推理。
在开始之前,请确保您已安装所有必要的库
pip install transformers datasets evaluate -q pip install jiwer -q
我们鼓励您登录到 Hugging Face 帐户,以便您可以将模型上传并与社区共享。当出现提示时,输入您的令牌进行登录。
from huggingface_hub import notebook_login
notebook_login()
加载宝可梦 BLIP 字幕数据集
使用 🤗 Dataset 库加载包含 {图像-字幕} 对的数据集。要在 PyTorch 中创建自己的图像字幕数据集,您可以按照 此 Notebook 进行操作。
from datasets import load_dataset
ds = load_dataset("lambdalabs/pokemon-blip-captions")
ds
DatasetDict({
train: Dataset({
features: ['image', 'text'],
num_rows: 833
})
})
数据集包含两个特征,`image` 和 `text`。
许多图像字幕数据集每张图像包含多个字幕。在这些情况下,常见的策略是在训练期间从可用字幕中随机抽取一个字幕。
使用 train_test_split 方法将数据集的训练集拆分为训练集和测试集
ds = ds["train"].train_test_split(test_size=0.1)
train_ds = ds["train"]
test_ds = ds["test"]
让我们可视化训练集中的几个样本。
from textwrap import wrap
import matplotlib.pyplot as plt
import numpy as np
def plot_images(images, captions):
plt.figure(figsize=(20, 20))
for i in range(len(images)):
ax = plt.subplot(1, len(images), i + 1)
caption = captions[i]
caption = "\n".join(wrap(caption, 12))
plt.title(caption)
plt.imshow(images[i])
plt.axis("off")
sample_images_to_visualize = [np.array(train_ds[i]["image"]) for i in range(5)]
sample_captions = [train_ds[i]["text"] for i in range(5)]
plot_images(sample_images_to_visualize, sample_captions)

预处理数据集
由于数据集有两种模态(图像和文本),因此预处理管道将对图像和字幕进行预处理。
为此,加载与您将要微调的模型相关的处理器类。
from transformers import AutoProcessor
checkpoint = "microsoft/git-base"
processor = AutoProcessor.from_pretrained(checkpoint)
处理器将在内部预处理图像(包括调整大小和像素缩放)并对字幕进行分词。
def transforms(example_batch):
images = [x for x in example_batch["image"]]
captions = [x for x in example_batch["text"]]
inputs = processor(images=images, text=captions, padding="max_length")
inputs.update({"labels": inputs["input_ids"]})
return inputs
train_ds.set_transform(transforms)
test_ds.set_transform(transforms)
数据集准备好后,您现在可以设置模型以进行微调。
加载基础模型
将 “microsoft/git-base” 加载到 `AutoModelForCausalLM` 对象中。
from transformers import AutoModelForCausalLM
model = AutoModelForCausalLM.from_pretrained(checkpoint)
评估
图像字幕模型通常使用 Rouge Score 或 词错误率 (Word Error Rate, WER) 进行评估。在本指南中,您将使用词错误率 (WER)。
我们使用 🤗 Evaluate 库来完成此操作。有关 WER 的潜在限制和其他注意事项,请参阅 此指南。
from evaluate import load
import torch
wer = load("wer")
def compute_metrics(eval_pred):
logits, labels = eval_pred
predicted = logits.argmax(-1)
decoded_labels = processor.batch_decode(labels, skip_special_tokens=True)
decoded_predictions = processor.batch_decode(predicted, skip_special_tokens=True)
wer_score = wer.compute(predictions=decoded_predictions, references=decoded_labels)
return {"wer_score": wer_score}
训练!
现在,您已准备好开始微调模型。您将使用 🤗 Trainer 来完成此操作。
首先,使用 TrainingArguments 定义训练参数。
from transformers import TrainingArguments, Trainer
model_name = checkpoint.split("/")[1]
training_args = TrainingArguments(
output_dir=f"{model_name}-pokemon",
learning_rate=5e-5,
num_train_epochs=50,
fp16=True,
per_device_train_batch_size=32,
per_device_eval_batch_size=32,
gradient_accumulation_steps=2,
save_total_limit=3,
eval_strategy="steps",
eval_steps=50,
save_strategy="steps",
save_steps=50,
logging_steps=50,
remove_unused_columns=False,
push_to_hub=True,
label_names=["labels"],
load_best_model_at_end=True,
)
然后将它们与数据集和模型一起传递给 🤗 Trainer。
trainer = Trainer( model=model, args=training_args, train_dataset=train_ds, eval_dataset=test_ds, compute_metrics=compute_metrics, )
要开始训练,只需在 Trainer 对象上调用 train()。
trainer.train()
您应该会看到训练损失随着训练的进行而平稳下降。
训练完成后,使用 push_to_hub() 方法将您的模型分享到 Hub,以便所有人都可以使用您的模型。
trainer.push_to_hub()
推理
从 `test_ds` 中取一个样本图像来测试模型。
from PIL import Image
import requests
url = "https://huggingface.co/datasets/sayakpaul/sample-datasets/resolve/main/pokemon.png"
image = Image.open(requests.get(url, stream=True).raw)
image

from accelerate.test_utils.testing import get_backend
# automatically detects the underlying device type (CUDA, CPU, XPU, MPS, etc.)
device, _, _ = get_backend()
inputs = processor(images=image, return_tensors="pt").to(device)
pixel_values = inputs.pixel_values
调用 `generate` 并解码预测。
generated_ids = model.generate(pixel_values=pixel_values, max_length=50)
generated_caption = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
print(generated_caption)
a drawing of a pink and blue pokemon
看起来微调后的模型生成了一个非常好的字幕!
< > 在 GitHub 上更新