【ゼロショット画像分類】AutoGluonとTransformersでそれぞれゼロショット画像分類(Zero-Shot Image Classification)を実行。どちらが簡潔に書けるか?

画像


AutoGluon

Pythonスクリプト

from autogluon.multimodal import download, MultiModalPredictor

segway_image = download( "https://live.staticflickr.com/7236/7114602897_9cf00b2820_b.jpg")

predictor = MultiModalPredictor(problem_type="zero_shot_image_classification")

text_list = ['segway', 'bicycle', 'wheel', 'car']

prob = predictor.predict_proba({"image": [segway_image]}, {"text": text_list})

for i, text in enumerate(text_list):
    print(f"{text}: {prob[0][i]:.6f}")
    
'''
maxIndex = prob.argmax()
print(f"{text_list[maxIndex]}:{prob[0][maxIndex]:.6f}")
'''

結果

segway: 0.999972
bicycle: 0.000006
wheel: 0.000020
car: 0.000002

環境構築

pip install -U setuptools wheel
pip install torch==1.13.1+cu117 torchvision==0.14.1+cu117 --extra-index-url https://download.pytorch.org/whl/cu117
pip install autogluon

Transformers

Pythonスクリプト

from transformers import CLIPProcessor, CLIPModel
from diffusers.utils import load_image

image = load_image("https://live.staticflickr.com/7236/7114602897_9cf00b2820_b.jpg")

model = CLIPModel.from_pretrained("openai/clip-vit-large-patch14")
processor = CLIPProcessor.from_pretrained("openai/clip-vit-large-patch14")

text_list = ['segway', 'bicycle', 'wheel', 'car']

inputs = processor(text=text_list, images=image, return_tensors="pt", padding=True)

outputs = model(**inputs)

logits_per_image = outputs.logits_per_image # this is the image-text similarity score
prob = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities

for i, text in enumerate(text_list):
    print(f"{text}: {prob[0][i].item():.6f}")

'''
maxIndex = prob.detach().numpy().argmax()
print(f"{text_list[maxIndex]}:{prob[0][maxIndex].item():.6f}")
'''

結果

segway: 0.999937
bicycle: 0.000025
wheel: 0.000034
car: 0.000004

環境構築

pip install torch==2.0.1+cu117 --index-url https://download.pytorch.org/whl/cu117
pip install diffusers transformers

さいごに

どちらも学習済みモデルを自動的にダウンロードしてくれるため事前準備は不要です。

AutoGluonもTransformersも2023年6月現在積極的に開発がすすんでいるライブラリです。

AutoGluonは動作環境の安定性を重視している印象でPyTorchのバージョンは1.xが推奨されています。

どちらを使っても非常に簡潔に書けました。

以下の環境を使用しています。

Windows 11
CUDA 11.7
Python 3.10




このエントリーをはてなブックマークに追加