Hub documentation

在 Hugging Face 上使用 OpenCLIP

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

在 Hugging Face 上使用 OpenCLIP

OpenCLIP 是 OpenAI 的 CLIP 的开源实现。

在 Hub 上探索 OpenCLIP

您可以在模型页面左侧进行筛选,以查找 OpenCLIP 模型。

托管在 Hub 上的 OpenCLIP 模型配有模型卡片,其中包含有关这些模型的有用信息。得益于 OpenCLIP 与 Hugging Face Hub 的集成,您只需几行代码即可加载 OpenCLIP 模型。您还可以使用 Inference Endpoints 部署这些模型。

安装

要开始使用,您可以遵循OpenCLIP 安装指南。 您也可以通过 pip 使用以下单行命令进行安装:

$ pip install open_clip_torch

使用现有模型

所有 OpenCLIP 模型都可以轻松地从 Hub 加载:

import open_clip

model, preprocess = open_clip.create_model_from_pretrained('hf-hub:laion/CLIP-ViT-g-14-laion2B-s12B-b42K')
tokenizer = open_clip.get_tokenizer('hf-hub:laion/CLIP-ViT-g-14-laion2B-s12B-b42K')

加载完成后,您可以对图像和文本进行编码,以执行零样本图像分类:

import torch
from PIL import Image
import requests

url = 'http://images.cocodataset.org/val2017/000000039769.jpg'
image = Image.open(requests.get(url, stream=True).raw)
image = preprocess(image).unsqueeze(0)
text = tokenizer(["a diagram", "a dog", "a cat"])

with torch.no_grad(), torch.cuda.amp.autocast():
    image_features = model.encode_image(image)
    text_features = model.encode_text(text)
    image_features /= image_features.norm(dim=-1, keepdim=True)
    text_features /= text_features.norm(dim=-1, keepdim=True)

    text_probs = (100.0 * image_features @ text_features.T).softmax(dim=-1)

print("Label probs:", text_probs) 

它会输出每个可能类别的概率:

Label probs: tensor([[0.0020, 0.0034, 0.9946]])

如果您想加载特定的 OpenCLIP 模型,可以单击模型卡片中的 Use in OpenCLIP,即可获得可用的代码片段!

其他资源

Update on GitHub