Transformers 文档

图像描述

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

图像描述

图像描述是预测给定图像的描述的任务。其常见的现实世界应用包括帮助视力受损人士,帮助他们应对不同的情况。因此,图像描述通过向人们描述图像,有助于提高内容的可访问性。

本指南将向您展示如何

  • 微调图像描述模型。
  • 使用微调后的模型进行推理。

在开始之前,请确保您已安装所有必要的库

pip install transformers datasets evaluate -q
pip install jiwer -q

我们鼓励您登录您的 Hugging Face 帐户,以便您可以上传模型并与社区分享。出现提示时,输入您的令牌以登录

from huggingface_hub import notebook_login

notebook_login()

加载 Pokémon 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
    })
})

该数据集具有两个特征,imagetext

许多图像描述数据集包含每个图像的多个描述。在这些情况下,常见的策略是在训练期间从可用的描述中随机抽样一个描述。

使用 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)
Sample training images

预处理数据集

由于数据集具有两种模态(图像和文本),因此预处理管道将预处理图像和描述。

为此,请加载与您即将微调的模型关联的处理器类。

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 分数词错误率进行评估。在本指南中,您将使用词错误率 (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
Test 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 上更新