Transformers 文档

图像特征提取

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

图像特征提取

图像特征提取是提取给定图像的语义上有意义的特征的任务。 这有很多用例,包括图像相似度和图像检索。 此外,大多数计算机视觉模型可以用于图像特征提取,其中可以移除特定于任务的头部(图像分类、物体检测等)并获得特征。 这些特征在更高层次上非常有用:边缘检测、角点检测等等。 它们也可能包含关于真实世界的信息(例如,猫的样子),这取决于模型的深度。 因此,这些输出可以用于在特定数据集上训练新的分类器。

在本指南中,您将

  • 学习在 image-feature-extraction pipeline 之上构建一个简单的图像相似度系统。
  • 使用裸模型推理完成相同的任务。

使用 image-feature-extraction Pipeline 的图像相似度

我们有两张猫坐在渔网上的图片,其中一张是生成的。

from PIL import Image
import requests

img_urls = ["https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/cats.png", "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/cats.jpeg"]
image_real = Image.open(requests.get(img_urls[0], stream=True).raw).convert("RGB")
image_gen = Image.open(requests.get(img_urls[1], stream=True).raw).convert("RGB")

让我们看看 pipeline 的实际应用。 首先,初始化 pipeline。 如果您没有向其传递任何模型,pipeline 将自动使用 google/vit-base-patch16-224 进行初始化。 如果您想计算相似度,请将 pool 设置为 True。

import torch
from transformers import pipeline
from accelerate.test_utils.testing import get_backend
# automatically detects the underlying device type (CUDA, CPU, XPU, MPS, etc.)
DEVICE, _, _ = get_backend()
pipe = pipeline(task="image-feature-extraction", model_name="google/vit-base-patch16-384", device=DEVICE, pool=True)

要使用 pipe 进行推理,请将两张图像都传递给它。

outputs = pipe([image_real, image_gen])

输出包含这两张图像的池化嵌入。

# get the length of a single output
print(len(outputs[0][0]))
# show outputs
print(outputs)

# 768
# [[[-0.03909236937761307, 0.43381670117378235, -0.06913255900144577,

要获得相似度分数,我们需要将它们传递给相似度函数。

from torch.nn.functional import cosine_similarity

similarity_score = cosine_similarity(torch.Tensor(outputs[0]),
                                     torch.Tensor(outputs[1]), dim=1)

print(similarity_score)

# tensor([0.6043])

如果您想获得池化之前的最后一个隐藏状态,请避免为 pool 参数传递任何值,因为它默认设置为 False。 这些隐藏状态对于基于模型特征训练新的分类器或模型非常有用。

pipe = pipeline(task="image-feature-extraction", model_name="google/vit-base-patch16-224", device=DEVICE)
outputs = pipe(image_real)

由于输出是未池化的,我们获得了最后一个隐藏状态,其中第一维是批大小,最后两维是嵌入形状。

import numpy as np
print(np.array(outputs).shape)
# (1, 197, 768)

使用 AutoModel 获取特征和相似度

我们还可以使用 transformers 的 AutoModel 类来获取特征。 AutoModel 加载任何没有特定于任务的头部的 transformers 模型,我们可以使用它来获取特征。

from transformers import AutoImageProcessor, AutoModel

processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224")
model = AutoModel.from_pretrained("google/vit-base-patch16-224").to(DEVICE)

让我们编写一个简单的推理函数。 我们将首先将输入传递给 processor,然后将其输出传递给 model

def infer(image):
  inputs = processor(image, return_tensors="pt").to(DEVICE)
  outputs = model(**inputs)
  return outputs.pooler_output

我们可以将图像直接传递给此函数并获得嵌入。

embed_real = infer(image_real)
embed_gen = infer(image_gen)

我们可以再次获得嵌入的相似度。

from torch.nn.functional import cosine_similarity

similarity_score = cosine_similarity(embed_real, embed_gen, dim=1)
print(similarity_score)

# tensor([0.6061], device='cuda:0', grad_fn=<SumBackward1>)
< > 在 GitHub 上更新