clip について
OpenAIのCLIPを扱う技術ガイドです。画像とテキストを対応付けるモデルで、ゼロショット画像分類、セマンティック検索、コンテンツ審査、クロスモーダル検索の開発に役立ちます。
主な機能
- 01ゼロショット画像分類
- 02画像とテキストの類似度計算
- 03セマンティック画像検索
- 04コンテンツ審査の分類
- 05画像の一括エンコード
活用シーン
- 01学習データなしでの画像分類
- 02テキスト説明による画像検索
- 03画像コンテンツの安全カテゴリ判定
- 04画像からテキストへのクロスモーダル検索
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ orchestra-research/ ai-research-skills --skill clipインストール後、Claude Code で/clipを入力して読み込まれたか確認します。
同梱ファイルreferences/applications.md
詳細
CLIP - Contrastive Language-Image Pre-Training
自然言語から画像を理解する OpenAI のモデルです。
CLIP を使うタイミング
使用する場合:
- ゼロショット画像分類(学習データが不要)
- 画像とテキストの類似度計算・マッチング
- セマンティック画像検索
- コンテンツモデレーション(NSFW や暴力の検出)
- 視覚的質問応答
- クロスモーダル検索(画像→テキスト、テキスト→画像)
Metrics:
- 25,300+ GitHub スター
- 4 億組の画像-テキストペアで学習
- ゼロショットで ImageNet 上の ResNet-50 と同等の性能
- MIT ライセンス
代わりに使うとよいもの:
- BLIP-2: より高性能なキャプション生成
- LLaVA: 視覚言語チャット
- Segment Anything: 画像セグメンテーション
クイックスタート
インストール
pip install git+https://github.com/openai/CLIP.git
pip install torch torchvision ftfy regex tqdm
ゼロショット分類
import torch
import clip
from PIL import Image
# Load model
device = "cuda" if torch.cuda.is_available() else "cpu"
model, preprocess = clip.load("ViT-B/32", device=device)
# Load image
image = preprocess(Image.open("photo.jpg")).unsqueeze(0).to(device)
# Define possible labels
text = clip.tokenize(["a dog", "a cat", "a bird", "a car"]).to(device)
# Compute similarity
with torch.no_grad():
image_features = model.encode_image(image)
text_features = model.encode_text(text)
# Cosine similarity
logits_per_image, logits_per_text = model(image, text)
probs = logits_per_image.softmax(dim=-1).cpu().numpy()
# Print results
labels = ["a dog", "a cat", "a bird", "a car"]
for label, prob in zip(labels, probs[0]):
print(f"{label}: {prob:.2%}")
利用可能なモデル
# Models (sorted by size)
models = [
"RN50", # ResNet-50
"RN101", # ResNet-101
"ViT-B/32", # Vision Transformer (recommended)
"ViT-B/16", # Better quality, slower
"ViT-L/14", # Best quality, slowest
]
model, preprocess = clip.load("ViT-B/32")
| Model | Parameters | Speed | Quality |
|---|---|---|---|
| RN50 | 102M | Fast | Good |
| ViT-B/32 | 151M | Medium | Better |
| ViT-L/14 | 428M | Slow | Best |
画像-テキスト類似度
# Compute embeddings
image_features = model.encode_image(image)
text_features = model.encode_text(text)
# Normalize
image_features /= image_features.norm(dim=-1, keepdim=True)
text_features /= text_features.norm(dim=-1, keepdim=True)
# Cosine similarity
similarity = (image_features @ text_features.T).item()
print(f"Similarity: {similarity:.4f}")
セマンティック画像検索
# Index images
image_paths = ["img1.jpg", "img2.jpg", "img3.jpg"]
image_embeddings = []
for img_path in image_paths:
image = preprocess(Image.open(img_path)).unsqueeze(0).to(device)
with torch.no_grad():
embedding = model.encode_image(image)
embedding /= embedding.norm(dim=-1, keepdim=True)
image_embeddings.append(embedding)
image_embeddings = torch.cat(image_embeddings)
# Search with text query
query = "a sunset over the ocean"
text_input = clip.tokenize([query]).to(device)
with torch.no_grad():
text_embedding = model.encode_text(text_input)
text_embedding /= text_embedding.norm(dim=-1, keepdim=True)
# Find most similar images
similarities = (text_embedding @ image_embeddings.T).squeeze(0)
top_k = similarities.topk(3)
for idx, score in zip(top_k.indices, top_k.values):
print(f"{image_paths[idx]}: {score:.3f}")
コンテンツモデレーション
# Define categories
categories = [
"safe for work",
"not safe for work",
"violent content",
"graphic content"
]
text = clip.tokenize(categories).to(device)
# Check image
with torch.no_grad():
logits_per_image, _ = model(image, text)
probs = logits_per_image.softmax(dim=-1)
# Get classification
max_idx = probs.argmax().item()
max_prob = probs[0, max_idx].item()
print(f"Category: {categories[max_idx]} ({max_prob:.2%})")
バッチ処理
# Process multiple images
images = [preprocess(Image.open(f"img{i}.jpg")) for i in range(10)]
images = torch.stack(images).to(device)
with torch.no_grad():
image_features = model.encode_image(images)
image_features /= image_features.norm(dim=-1, keepdim=True)
# Batch text
texts = ["a dog", "a cat", "a bird"]
text_tokens = clip.tokenize(texts).to(device)
with torch.no_grad():
text_features = model.encode_text(text_tokens)
text_features /= text_features.norm(dim=-1, keepdim=True)
# Similarity matrix (10 images × 3 texts)
similarities = image_features @ text_features.T
print(similarities.shape) # (10, 3)
ベクトルデータベースとの連携
# Store CLIP embeddings in Chroma/FAISS
import chromadb
client = chromadb.Client()
collection = client.create_collection("image_embeddings")
# Add image embeddings
for img_path, embedding in zip(image_paths, image_embeddings):
collection.add(
embeddings=[embedding.cpu().numpy().tolist()],
metadatas=[{"path": img_path}],
ids=[img_path]
)
# Query with text
query = "a sunset"
text_embedding = model.encode_text(clip.tokenize([query]))
results = collection.query(
query_embeddings=[text_embedding.cpu().numpy().tolist()],
n_results=5
)
ベストプラクティス
- ほとんどのケースでは ViT-B/32 を使用する - 性能と速度のバランスがよい
- 埋め込みを正規化する - コサイン類似度の計算に必要
- バッチ処理を行う - より効率的
- 埋め込みをキャッシュする - 再計算のコストが高い
- 説明的なラベルを使う - ゼロショットの性能が向上する
- GPU の使用を推奨 - 10〜50 倍高速
- 画像を前処理する - 提供されている前処理関数を使用する
パフォーマンス
| Operation | CPU | GPU (V100) |
|---|---|---|
| Image encoding | ~200ms | ~20ms |
| Text encoding | ~50ms | ~5ms |
| Similarity compute | <1ms | <1ms |
制限事項
- きめ細かいタスクには不向き - 大まかなカテゴリに最適
- 説明的なテキストが必要 - 曖昧なラベルでは性能が低下する
- Web データに起因する偏り - データセット由来のバイアスを含む場合がある
- バウンディングボックスは出力しない - 画像全体のみが対象
- 空間理解が限定的 - 位置関係や数の把握は弱い
リソース
- GitHub: https://github.com/openai/CLIP ⭐ 25,300+
- Paper: https://arxiv.org/abs/2103.00020
- Colab: https://colab.research.google.com/github/openai/clip/
- License: MIT
コメント
Markdown 対応