Transformers 文件

零樣本影像分類

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

零樣本影像分類

零樣本影像分類是一項任務,它涉及使用一個未在包含特定類別標記資料的模型上進行顯式訓練的模型,將影像分類到不同的類別中。

傳統上,影像分類需要在一個特定的標記影像集上訓練模型,該模型學習將某些影像特徵“對映”到標籤。當需要將此類模型用於引入新標籤集的分類任務時,需要進行微調以“重新校準”模型。

相比之下,零樣本或開放詞彙影像分類模型通常是多模態模型,它們已經在一個包含大量影像和相關描述的資料集上進行了訓練。這些模型學習對齊的視覺-語言表示,可用於許多下游任務,包括零樣本影像分類。

這是一種更靈活的影像分類方法,允許模型泛化到新的和未見的類別,而無需額外的訓練資料,並使使用者能夠使用目標物件的自由形式文字描述來查詢影像。

在本指南中,您將學習如何

  • 建立零樣本影像分類流水線
  • 手動執行零樣本影像分類推理

在開始之前,請確保您已安裝所有必要的庫

pip install -q "transformers[torch]" pillow

零樣本影像分類流水線

嘗試使用支援零樣本影像分類的模型進行推理的最簡單方法是使用相應的 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

將影像和候選物件標籤傳遞給流水線。這裡我們直接傳遞影像;其他合適的選項包括影像的本地路徑或影像 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

使用處理器準備模型的輸入。處理器結合了影像處理器,該處理器透過調整大小和標準化來準備影像,以及一個處理文字輸入的tokenizer。

>>> 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'}]
< > 在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.