视觉问答(VQA)

使用 Hugging Face 的多模态模型

James Chapman

Curriculum Manager, DataCamp

多模态问答任务

VQA 模型中图像与文本处理流程示意图

  1. 将问题文本与另一模态分别编码
使用 Hugging Face 的多模态模型

多模态问答任务

VQA 模型中图像与文本处理流程示意图

  1. 将问题文本与另一模态分别编码
  2. 合并编码后的特征
使用 Hugging Face 的多模态模型

多模态问答任务

VQA 模型中图像与文本处理流程示意图

  1. 将问题文本与另一模态分别编码
  2. 合并编码后的特征
  3. 通过额外层预测答案词元
使用 Hugging Face 的多模态模型

VQA

import requests
from PIL import Image

url = "https://www.worldanimalprotection
.org/cdn-cgi/image/width=1920,format=
auto/globalassets/images/elephants/1
033551-elephant.jpg"


image = Image.open(requests.get(url, stream=True).raw)
text = "What animal is in this photo?"

野外大象的照片

使用 Hugging Face 的多模态模型

VQA

 

  • 模型掌握多种对象的图像与文本特征
  • 可复用模型,无需额外微调

聚焦动物并识别的示意图

使用 Hugging Face 的多模态模型

VQA

from transformers import ViltProcessor, ViltForQuestionAnswering


processor = ViltProcessor.from_pretrained("dandelin/vilt-b32-finetuned-vqa") model = ViltForQuestionAnswering.from_pretrained("dandelin/vilt-b32-finetuned-vqa")
encoding = processor(image, text, return_tensors="pt")
outputs = model(**encoding)
idx = outputs.logits.argmax(-1).item()
print("Predicted answer:", model.config.id2label[idx])
Predicted answer: elephant
使用 Hugging Face 的多模态模型

文档 VQA

  • 将 VQA 扩展到图表、表格与图像中文本(OCR)检测
from datasets import load_dataset
from transformers import pipeline

dataset = load_dataset("lmms-lab/DocVQA")


import matplotlib.pyplot as plt plt.imshow(dataset["test"][2]["image"]) plt.show()

包含图表和柱状图的文档图像

使用 Hugging Face 的多模态模型

文档 VQA

Google Tessearact 标志

  • 运行 OCR 需额外依赖
  • 通过 pip 安装 pytesseract
  • 通过软件包安装器安装 Tesseract OCR(如 apt-getexehomebrew/macports

带有 OCR 的咖啡招牌图片

使用 Hugging Face 的多模态模型

文档 VQA

from transformers import pipeline
pipe = pipeline("document-question-answering", "impira/layoutlm-document-qa")

result = pipe( dataset["test"][2]["image"], "What was the gross income in 2011-2012?" )
使用 Hugging Face 的多模态模型

文档 VQA

print(result)
[{'score': 0.05149758607149124,
  'answer': '3 36073 Crores', ...}]

包含图表和柱状图的文档图像

使用 Hugging Face 的多模态模型

Vamos praticar!

使用 Hugging Face 的多模态模型

Preparing Video For Download...