SigLip2 运行测试代码 接另一篇文章,虽然Gemma2的前序工作用的是SigLip。

Python3.8

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

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)


您可能感兴趣的与本文相关的镜像

Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值