SigLip2 运行测试代码
接另一篇文章,Gemma2的前序工作,虽然用的是SigLip。
import torch
from transformers import pipeline, AutoProcessor, AutoModel
from PIL import Image
import requests
import matplotlib.pyplot as plt
IMAGE_PATH = "D:/test_image.jpg" # 替换为你的图片路径
# 初始化模型和处理器
device = "cuda" if torch.cuda.is_available() else "cpu"
# 检查是否有可用的GPU
print(f"Using device: {device}")
checkpoint = "google/siglip2-base-patch16-256"
model = AutoModel.from_pretrained(checkpoint).to(device)
processor = AutoProcessor.from_pretrained(checkpoint, use_fast=True)
# 加载图片和候选标签
image = Image.open(IMAGE_PATH).convert("RGB")
candidate_labels = [
"a standing cat with striped fur", # 添加姿势和毛色描述
"a dog wearing a harness", # 强调服饰特征
"tiled floor background", # 包含背景信息
"two animals in a corner" # 空间关系描述
]
texts = [f"This is a photo of {label}." for label in candidate_labels]
# 使用模型训练时的标准文本模板
inputs = processor(
text=texts,
images=image,
padding="max_length",
max_length=64,
return_tensors="pt"
).to(device)
with torch.no_grad():
outputs = model(**inputs)
# 提取归一化后的视觉嵌入向量(模型最后输出的已归一化版本)
visual_embeds = outputs.image_embeds
# 输出嵌入向量的维度信息
print("视觉嵌入维度:", visual_embeds.shape)
# 输出前5个维度的数值示例(避免打印过多内容)
print("视觉嵌入示例值:", visual_embeds[0, :5].cpu().numpy())
# 如果要获取未归一化的原始嵌入,可以访问编码器输出
# vision_outputs = model.get_image_features(**inputs)
# raw_visual_embeds = vision_outputs.last_hidden_state
# outputs.image_embeds (batch, embed_dim) 归一化后的视觉嵌入(L2-normalized),可直接用于相似度计算
# outputs.text_embeds (batch, embed_dim) 归一化后的文本嵌入(L2-normalized)
# outputs.logits_per_image (batch, text_batch) 图像到文本的匹配分数(未归一化,直接通过矩阵乘法计算得到)
# outputs.logits_per_text (text_batch, batch) 文本到图像的匹配分数(与 logits_per_image 互为转置)
# ----------------------------------------------------------
# 5. 计算相似度
logits_per_image = outputs.logits_per_image # 获取图文匹配分数
manual_probs = torch.sigmoid(logits_per_image) # 转换为概率值
# 格式化输出结果
formatted_outputs = [{"label": label, "score": float(prob)}
for label, prob in zip(candidate_labels, manual_probs[0])]
print("\n格式化输出结果:", formatted_outputs)
672

被折叠的 条评论
为什么被折叠?



