Transformers documentation

视觉问答

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.24.0).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

视觉问答

视觉问答(VQA)是指基于图像回答开放式问题的任务。 支持该任务的模型的输入通常是图像和问题的组合,输出则是以自然语言表达的答案。

VQA 的一些值得注意的用例示例包括:

  • 面向视障人士的无障碍应用。
  • 教育领域:针对讲座或教材中呈现的视觉材料提出问题。VQA 还可应用于互动式博物馆展览或历史遗址。
  • 客户服务与电子商务:VQA 可以通过允许用户询问有关产品的问题来提升用户体验。
  • 图像检索:VQA 模型可用于检索具有特定特征的图像。例如,用户可以询问“有狗吗?”以从一组图像中找出所有包含狗的图像。

在本指南中,您将学习如何:

  • 在 Graphcore/vqa 数据集上微调一个分类 VQA 模型,具体为 ViLT。
  • 使用您微调后的 ViLT 进行推理。
  • 使用 BLIP-2 等生成式模型运行零样本 VQA 推理。

微调 ViLT

ViLT 模型将文本嵌入整合到 Vision Transformer (ViT) 中,使其能够以极简的设计实现视觉与语言预训练 (VLP)。该模型可用于多种下游任务。对于 VQA 任务,会在顶部放置一个分类器头(即在 [CLS] token 的最终隐藏状态之上添加一个线性层),并进行随机初始化。因此,视觉问答被处理为一个分类问题。

更新的模型,例如 BLIP、BLIP-2 和 InstructBLIP,将 VQA 视为生成任务。本指南稍后部分将演示如何使用它们进行零样本 VQA 推理。

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

pip install -q transformers datasets

我们鼓励您与社区分享您的模型。请登录您的 Hugging Face 账户,将其上传到 🤗 Hub。 当系统提示时,请输入您的 token 以完成登录:

>>> from huggingface_hub import notebook_login

>>> notebook_login()

让我们将模型检查点定义为一个全局变量。

>>> model_checkpoint = "dandelin/vilt-b32-mlm"

加载数据

为了便于说明,本指南使用了标注好的视觉问答数据集 Graphcore/vqa 的一个非常小的样本。

作为 Graphcore/vqa 数据集的替代方案,您可以从官方的 VQA 数据集页面 手动下载相同的数据。如果您更喜欢使用自定义数据来跟随本教程,请查阅 🤗 Datasets 文档中的 创建图像数据集 指南。

让我们加载验证集中的前 200 个样本,并探索数据集的特征:

>>> from datasets import load_dataset

>>> dataset = load_dataset("Graphcore/vqa", split="validation[:200]")
>>> dataset
Dataset({
    features: ['question', 'question_type', 'question_id', 'image_id', 'answer_type', 'label'],
    num_rows: 200
})

让我们通过一个示例来了解数据集的特性:

>>> dataset[0]
{'question': 'Where is he looking?',
 'question_type': 'none of the above',
 'question_id': 262148000,
 'image_id': '/root/.cache/huggingface/datasets/downloads/extracted/ca733e0e000fb2d7a09fbcc94dbfe7b5a30750681d0e965f8e0a23b1c2f98c75/val2014/COCO_val2014_000000262148.jpg',
 'answer_type': 'other',
 'label': {'ids': ['at table', 'down', 'skateboard', 'table'],
  'weights': [0.30000001192092896,
   1.0,
   0.30000001192092896,
   0.30000001192092896]}}

与任务相关的特征包括:

  • question:需要从图像中回答的问题
  • image_id:问题所指向的图像的路径
  • label:标注

我们可以移除其余的特征,因为它们不再需要:

>>> dataset = dataset.remove_columns(['question_type', 'question_id', 'answer_type'])

如你所见,label 特征包含由不同人工标注者收集的针对同一问题的多个答案(此处称为 ids)。 这是因为问题的答案可能具有主观性。在此例中,问题是“他在看哪里?”。有些人将其标注为“向下”,另一些人标注为“看向桌子”,还有一人标注为“滑板”,等等。

请查看该图像,并考虑你会给出哪个答案:

>>> from PIL import Image

>>> image = Image.open(dataset[0]['image_id'])
>>> image
VQA Image Example

由于问题和答案存在歧义,此类数据集被视为多标签分类问题(因为可能有多个正确答案)。此外,并非仅仅创建一个 one-hot 编码向量,而是根据某个答案在标注中出现的次数,创建一个软编码(soft encoding)。

例如,在上面的示例中,由于答案“down”被选中的频率远高于其他答案,因此它的得分(在数据集中称为 weight)为 1.0,而其他答案的得分均 < 1.0。

为了稍后使用合适的分类头实例化模型,让我们创建两个字典:一个将标签名称映射为整数,另一个则反之:

>>> import itertools

>>> labels = [item['ids'] for item in dataset['label']]
>>> flattened_labels = list(itertools.chain(*labels))
>>> unique_labels = list(set(flattened_labels))

>>> label2id = {label: idx for idx, label in enumerate(unique_labels)}
>>> id2label = {idx: label for label, idx in label2id.items()}

现在我们已经有了映射关系,可以用对应的 id 替换字符串答案,并将数据集展平,以便更方便地进行后续预处理。

>>> def replace_ids(inputs):
...   inputs["label"]["ids"] = [label2id[x] for x in inputs["label"]["ids"]]
...   return inputs


>>> dataset = dataset.map(replace_ids)
>>> flat_dataset = dataset.flatten()
>>> flat_dataset.features
{'question': Value(dtype='string', id=None),
 'image_id': Value(dtype='string', id=None),
 'label.ids': Sequence(feature=Value(dtype='int64', id=None), length=-1, id=None),
 'label.weights': Sequence(feature=Value(dtype='float64', id=None), length=-1, id=None)}

预处理数据

下一步是加载 ViLT 处理器,为模型准备图像和文本数据。ViltProcessor 将 BERT 分词器和 ViLT 图像处理器封装为一个便捷的单一处理器:

>>> from transformers import ViltProcessor

>>> processor = ViltProcessor.from_pretrained(model_checkpoint)

要预处理数据,我们需要使用 ViltProcessor 对图像和问题进行编码。该处理器将使用 BertTokenizerFast 对文本进行分词,并为文本数据创建 input_ids、attention_mask 和 token_type_ids。 对于图像,处理器将利用 ViltImageProcessor 对图像进行缩放和归一化,并创建 pixel_values 和 pixel_mask。

所有这些预处理步骤都在底层自动完成,我们只需调用 processor 即可。不过,我们仍然需要 准备目标标签。在这种表示方式中,每个元素对应一个可能的答案(标签)。对于正确答案,该元素保存 其对应的分数(权重),而其余元素则设为零。

以下函数将 processor 应用于图像和问题,并按照上述方式格式化标签:

>>> import torch

>>> def preprocess_data(examples):
...     image_paths = examples['image_id']
...     images = [Image.open(image_path) for image_path in image_paths]
...     texts = examples['question']

...     encoding = processor(images, texts, padding="max_length", truncation=True, return_tensors="pt")

...     for k, v in encoding.items():
...           encoding[k] = v.squeeze()

...     targets = []

...     for labels, scores in zip(examples['label.ids'], examples['label.weights']):
...         target = torch.zeros(len(id2label))

...         for label, score in zip(labels, scores):
...             target[label] = score

...         targets.append(target)

...     encoding["labels"] = targets

...     return encoding

要对整个数据集应用预处理函数,请使用 🤗 Datasets 的 map 函数。通过设置 batched=True 以一次处理数据集中的多个元素,可以加速 map。此时,您可以自由删除不需要的列。

>>> processed_dataset = flat_dataset.map(preprocess_data, batched=True, remove_columns=['question','question_type',  'question_id', 'image_id', 'answer_type', 'label.ids', 'label.weights'])
>>> processed_dataset
Dataset({
    features: ['input_ids', 'token_type_ids', 'attention_mask', 'pixel_values', 'pixel_mask', 'labels'],
    num_rows: 200
})

作为最后一步,使用 DefaultDataCollator 创建一个示例批次:

>>> from transformers import DefaultDataCollator

>>> data_collator = DefaultDataCollator()

训练模型

现在您可以开始训练模型了!使用 ViltForQuestionAnswering 加载 ViLT。请指定标签数量以及标签映射:

>>> from transformers import ViltForQuestionAnswering

>>> model = ViltForQuestionAnswering.from_pretrained(model_checkpoint, num_labels=len(id2label), id2label=id2label, label2id=label2id)

此时,只剩下三个步骤:

  1. 在 TrainingArguments 中定义训练超参数:
>>> from transformers import TrainingArguments

>>> repo_id = "MariaK/vilt_finetuned_200"

>>> training_args = TrainingArguments(
...     output_dir=repo_id,
...     per_device_train_batch_size=4,
...     num_train_epochs=20,
...     save_steps=200,
...     logging_steps=50,
...     learning_rate=5e-5,
...     save_total_limit=2,
...     remove_unused_columns=False,
...     push_to_hub=True,
... )
  1. 将训练参数与模型、数据集、处理器和数据整理器一起传递给 Trainer。
>>> from transformers import Trainer

>>> trainer = Trainer(
...     model=model,
...     args=training_args,
...     data_collator=data_collator,
...     train_dataset=processed_dataset,
...     processing_class=processor,
... )
  1. 调用 train() 来微调你的模型。
>>> trainer.train()

训练完成后,使用 push_to_hub() 方法将您的模型共享到 Hub,即可在 🤗 Hub 上分享您的最终模型:

>>> trainer.push_to_hub()

推理

现在,您已经微调了 ViLT 模型并将其上传到 🤗 Hub,可以使用它进行推理。

  1. 获取一张图像和一个问题,并使用来自您模型的处理器为模型准备它们。
  2. 将结果或预处理结果通过模型进行前向传播。
  3. 从 logits 中获取最可能答案的 id,并在 id2label 中查找对应的实际答案。
>>> processor = ViltProcessor.from_pretrained("MariaK/vilt_finetuned_200")

>>> image = Image.open(example['image_id'])
>>> question = example['question']

>>> # prepare inputs
>>> inputs = processor(image, question, return_tensors="pt")

>>> model = ViltForQuestionAnswering.from_pretrained("MariaK/vilt_finetuned_200")

>>> # forward pass
>>> with torch.no_grad():
...     outputs = model(**inputs)

>>> logits = outputs.logits
>>> idx = logits.argmax(-1).item()
>>> print("Predicted answer:", model.config.id2label[idx])
Predicted answer: down

零样本 VQA

之前的模型将 VQA 视为分类任务。一些较新的模型,例如 BLIP、BLIP-2 和 InstructBLIP,将 VQA 视为生成任务。我们以 BLIP-2 为例。它引入了一种新的视觉-语言预训练范式,在该范式中,可以使用任何预训练视觉编码器与 LLM 的组合(详见 BLIP-2 博客文章)。这使得在包括视觉问答在内的多种视觉-语言任务上都能取得最先进的结果。

下面演示如何使用该模型进行 VQA。首先,加载模型。这里我们会显式地将模型发送到 GPU(如果可用),而在之前的训练过程中我们无需这样做,因为 Trainer 会自动处理:

>>> from transformers import AutoProcessor, Blip2ForConditionalGeneration
from accelerate import Accelerator
>>> import torch

>>> processor = AutoProcessor.from_pretrained("Salesforce/blip2-opt-2.7b")
>>> model = Blip2ForConditionalGeneration.from_pretrained("Salesforce/blip2-opt-2.7b", dtype=torch.float16)
>>> device = Accelerator().device
>>> model.to(device)

模型以图像和文本作为输入,因此我们使用 VQA 数据集中第一个示例中完全相同的图像/问题对:

>>> example = dataset[0]
>>> image = Image.open(example['image_id'])
>>> question = example['question']

要在视觉问答任务中使用 BLIP-2,文本提示必须遵循特定格式:Question: {} Answer:。

>>> prompt = f"Question: {question} Answer:"

现在,我们需要使用模型的处理器对图像/提示进行预处理,将处理后的输入传入模型,并解码输出:

>>> inputs = processor(image, text=prompt, return_tensors="pt").to(device, torch.float16)

>>> generated_ids = model.generate(**inputs, max_new_tokens=10)
>>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip()
>>> print(generated_text)
"He is looking at the crowd"

如你所见,模型识别出了人群以及面部的朝向(向下看),但它似乎忽略了人群位于滑冰者身后的事实。尽管如此,在无法获取人工标注数据集的情况下,这种方法仍能快速产生有用的结果。

Update on GitHub