多模态情感分析

使用 Hugging Face 的多模态模型

James Chapman

Curriculum Manager, DataCamp

视觉-语言模型(VLM)

通用视觉-语言模型架构示意图

  • 图像与文本分别编码
  • 特征融合
  • 生成共享表示
    • 一模多用,覆盖多任务
使用 Hugging Face 的多模态模型

视觉推理任务

  • VQA:图像 + 问题 → 直接回答图像内容

视觉问答示例:热狗

1 https://arxiv.org/pdf/1505.00468
使用 Hugging Face 的多模态模型

视觉推理任务

  • VQA:图像 + 问题 → 直接回答图像内容
  • 匹配:图像 + 陈述 → 真/假 判定

匹配示例:热狗与相关陈述

使用 Hugging Face 的多模态模型

视觉推理任务

  • VQA:图像 + 问题 → 直接回答图像内容
  • 匹配:图像 + 陈述 → 真/假 判定
  • 蕴含:图像 + 对比文本 → 语义关系检验

蕴含示例:热狗,含蕴含、中立、矛盾假设

使用 Hugging Face 的多模态模型

用例:股价影响

from datasets import load_dataset
dset = "RealTimeData/bbc_news_alltime"
dataset = load_dataset(dset, '2017-01', 
                       split="train")


image = dataset[87]["top_image"] content = dataset[87]["content"] print(content)
'Ford\'s decision to cancel a $1.6bn 
investment in Mexico and 
invest an extra $700m in Michigan ...

新闻文章中的图片:汽车生产投资

使用 Hugging Face 的多模态模型

Qwen 2 VLMs

from transformers import Qwen2VLForConditionalGeneration
from qwen_vl_utils import process_vision_info


vl_model = Qwen2VLForConditionalGeneration.from_pretrained( "Qwen/Qwen2-VL-2B-Instruct", device_map="auto", torch_dtype="auto" )
使用 Hugging Face 的多模态模型

预处理器

from transformers import Qwen2VLProcessor

min_pixels = 224 * 224
max_pixels = 448 * 448
vl_model_processor = Qwen2VLProcessor.from_pretrained(
    "Qwen/Qwen2-VL-2B-Instruct", min_pixels=min_pixels, max_pixels=max_pixels
)
使用 Hugging Face 的多模态模型

多模态提示

text_query = f"Is the sentiment of the following content good or bad for the Ford share price:
{article_text}. Provide reasoning."


chat_template = [ { "role": "user", "content": [ {"type": "image", "image": article_image}, {"type": "text", "text": text_query} ] } ]
使用 Hugging Face 的多模态模型

VLM 分类

text = vl_model_processor.apply_chat_template(chat_template, tokenize=False,
                                              add_generation_prompt=True)

image_inputs, _ = process_vision_info(chat_template)
inputs = vl_model_processor(text=[text], images=image_inputs, padding=True, return_tensors="pt")
generated_ids = vl_model.generate(**inputs, max_new_tokens=500)
generated_ids_trimmed = [out_ids[len(in_ids) :] for in_ids, out_ids\ in zip(inputs.input_ids, generated_ids)]
使用 Hugging Face 的多模态模型

VLM 分类

output_text = vl_model_processor.batch_decode(
    generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
)
print(output_text[0])
The sentiment of the provided text is negative. The author is expressing concern and
skepticism ...
使用 Hugging Face 的多模态模型

Vamos praticar!

使用 Hugging Face 的多模态模型

Preparing Video For Download...