Transformers documentation

ゼロショット画像分類

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

ゼロショット画像分類

Zero-shot image classification は、特定のカテゴリのラベル付き例を含むデータで明示的に訓練されていないモデルを使用して、画像を異なるカテゴリに分類するタスクです。

従来、画像分類では、特定のラベル付き画像のセットでモデルを訓練する必要があり、このモデルは特定の画像特徴をラベルに「対応させる」ことを学習します。新しいラベルのセットを含む分類タスクでこのようなモデルを使用する必要がある場合、モデルを「再調整」するためにファインチューニングが求められます。

一方、ゼロショットまたはオープンボキャブラリーの画像分類モデルは、通常、画像とその関連する説明からなる大規模なデータセットで訓練されたマルチモーダルモデルです。これらのモデルは、ゼロショット画像分類を含む多くの下流タスクに使用できる、整合性のあるビジョン・言語表現を学習します。

これは画像分類のより柔軟なアプローチであり、追加の学習データなしで、モデルが新しいカテゴリや未知のカテゴリに一般化できるようにします。また、ユーザーが対象オブジェクトの自由形式のテキスト記述で画像をクエリできるようにします。

このガイドでは、次のことを学びます。

  • ゼロショット画像分類パイプラインを作成します
  • 手動でゼロショット画像分類の推論を実行する

開始前に、必要なライブラリがすべてインストールされていることを確認してください。

pip install -q "transformers[torch]" pillow

Zero-shot画像分類パイプライン

ゼロショット画像分類に対応するモデルで推論を試す最も簡単な方法は、対応するpipeline()を使用することです。 Hugging Face Hub上のチェックポイントからパイプラインをインスタンス化します:

>>> from transformers import pipeline

>>> checkpoint = "openai/clip-vit-large-patch14"
>>> detector = pipeline(model=checkpoint, task="zero-shot-image-classification")

次に、分類したい画像を選択します。

>>> from PIL import Image
>>> import requests

>>> url = "https://unsplash.com/photos/g8oS8-82DxI/download?ixid=MnwxMjA3fDB8MXx0b3BpY3x8SnBnNktpZGwtSGt8fHx8fDJ8fDE2NzgxMDYwODc&force=true&w=640"
>>> image = Image.open(requests.get(url, stream=True).raw)

>>> image
Photo of an owl

画像と候補オブジェクトラベルをpipelineに渡します。ここでは画像を直接渡していますが、他の適切なオプションとしては、画像へのローカルパスや画像URLがあります。 候補ラベルは、この例のように単純な単語でも、より記述的なものでも構いません。

>>> predictions = detector(image, candidate_labels=["fox", "bear", "seagull", "owl"])
>>> predictions
[{'score': 0.9996670484542847, 'label': 'owl'},
 {'score': 0.000199399160919711, 'label': 'seagull'},
 {'score': 7.392891711788252e-05, 'label': 'fox'},
 {'score': 5.96074532950297e-05, 'label': 'bear'}]

手動によるゼロショット画像分類

ゼロショット画像分類パイプラインの使い方を確認したので、次はゼロショット画像分類を手動で実行する方法を見ていきましょう。

Hugging Face Hub上のチェックポイントからモデルと関連するプロセッサを読み込むことから始めます。 ここでは、以前と同じチェックポイントを使用します:

>>> from transformers import AutoProcessor, AutoModelForZeroShotImageClassification

>>> model = AutoModelForZeroShotImageClassification.from_pretrained(checkpoint)
>>> processor = AutoProcessor.from_pretrained(checkpoint)

気分転換に、別の画像を使ってみましょう。

>>> from PIL import Image
>>> import requests

>>> url = "https://unsplash.com/photos/xBRQfR2bqNI/download?ixid=MnwxMjA3fDB8MXxhbGx8fHx8fHx8fHwxNjc4Mzg4ODEx&force=true&w=640"
>>> image = Image.open(requests.get(url, stream=True).raw)

>>> image
Photo of a car

プロセッサーを使用して、モデルへの入力を準備します。プロセッサーは、モデル用に画像をリサイズして正規化して準備する画像プロセッサーと、テキスト入力を処理するトークナイザーを組み合わせます。

>>> candidate_labels = ["tree", "car", "bike", "cat"]
# follows the pipeline prompt template to get same results
>>> candidate_labels = [f'This is a photo of {label}.' for label in candidate_labels]
>>> inputs = processor(images=image, text=candidate_labels, return_tensors="pt", padding=True)

入力をモデルに通し、結果を後処理します:

>>> import torch

>>> with torch.no_grad():
...     outputs = model(**inputs)

>>> logits = outputs.logits_per_image[0]
>>> probs = logits.softmax(dim=-1).numpy()
>>> scores = probs.tolist()

>>> result = [
...     {"score": score, "label": candidate_label}
...     for score, candidate_label in sorted(zip(probs, candidate_labels), key=lambda x: -x[0])
... ]

>>> result
[{'score': 0.998572, 'label': 'car'},
 {'score': 0.0010570387, 'label': 'bike'},
 {'score': 0.0003393686, 'label': 'tree'},
 {'score': 3.1572064e-05, 'label': 'cat'}]
Update on GitHub