ゼロショット画像分類

Hugging Face で学ぶマルチモーダルモデル

James Chapman

Curriculum Manager, DataCamp

CLIP

  • Contrastive Language-Image Pre-training(対照言語画像事前学習)
  • 画像とテキストの類似度をスコア化
  • 4億の画像–テキスト対で学習
  • 2つのエンコーダ
    • ビジョンエンコーダ
    • テキストエンコーダ
  • 近い画像・テキストは似た配列を出力

CLIPのテキストと画像のエンコード図

1 https://openai.com/index/clip/
Hugging Face で学ぶマルチモーダルモデル

ゼロショット学習

  • 学習していないタスクも実行

飛行機のゼロショット学習のランキング

1 https://openai.com/index/clip/
Hugging Face で学ぶマルチモーダルモデル

ユースケース:商品カテゴリ分類

from datasets import load_dataset
import matplotlib.pyplot as plt

dset = "rajuptvs/ecommerce_products_clip"
dataset = load_dataset(dset)

print(dataset["train"][0]["Description"])
plt.imshow(dataset["train"][0]["image"]) plt.show()
Blive High quality premium Full sleeves printed 
Shirt direct from the manufacturers.Gives you 
a clean and classy look while also 
making you feel comfortable.Trusted 
brand online and no compromise on quality.

データセットのシャツ画像

Hugging Face で学ぶマルチモーダルモデル

CLIPによるゼロショット学習

model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")


categories = ["shirt", "trousers", "shoes", "dress", "hat", "bag", "watch"]
inputs = processor(text=categories, images=dataset["train"][0]["image"], return_tensors="pt", padding=True) outputs = model(**inputs)
probs = outputs.logits_per_image.softmax(dim=1)
categories[probs.argmax().item()]
shirt
Hugging Face で学ぶマルチモーダルモデル

CLIPスコア

  • 符号化した画像と説明文の類似度
  • 範囲は100(完全一致)〜0(不一致)
from torchmetrics.functional.multimodal import clip_score


image = dataset["train"][0]["image"] description = dataset["train"][0]["Description"]
from torchvision.transforms import ToTensor image = ToTensor()(image)*255
score = clip_score(image, description, "openai/clip-vit-base-patch32")
print(f"CLIP score: {score}")
CLIP score: 28.495952606201172
Hugging Face で学ぶマルチモーダルモデル

練習しましょう!

Hugging Face で学ぶマルチモーダルモデル

Preparing Video For Download...