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を介した以下の1行のインストールも利用できます:

$ 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