clip
OpenAIが開発した視覚と言語をつなぐモデルで、4億枚の画像とテキストのペアで学習済み。ファインチューニング不要でゼロショット画像分類、画像とテキストのマッチング、クロスモーダル検索を実現する。画像検索やコンテンツモデレーション、汎用的な画像理解タスクに最適。
description の原文を見る
OpenAI's model connecting vision and language. Enables zero-shot image classification, image-text matching, and cross-modal retrieval. Trained on 400M image-text pairs. Use for image search, content moderation, or vision-language tasks without fine-tuning. Best for general-purpose image understanding.
SKILL.md 本文
CLIP - Contrastive Language-Image Pre-Training
自然言語から画像を理解するOpenAIのモデル。
CLIPの使用時期
以下の場合に使用:
- ゼロショット画像分類(学習データ不要)
- 画像テキスト類似度/マッチング
- セマンティック画像検索
- コンテンツモデレーション(NSFW、暴力検出)
- ビジュアル質問応答
- クロスモーダル検索(画像→テキスト、テキスト→画像)
メトリクス:
- GitHubスター25,300+
- 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
# モデルをロード
device = "cuda" if torch.cuda.is_available() else "cpu"
model, preprocess = clip.load("ViT-B/32", device=device)
# 画像をロード
image = preprocess(Image.open("photo.jpg")).unsqueeze(0).to(device)
# 可能なラベルを定義
text = clip.tokenize(["a dog", "a cat", "a bird", "a car"]).to(device)
# 類似度を計算
with torch.no_grad():
image_features = model.encode_image(image)
text_features = model.encode_text(text)
# コサイン類似度
logits_per_image, logits_per_text = model(image, text)
probs = logits_per_image.softmax(dim=-1).cpu().numpy()
# 結果を出力
labels = ["a dog", "a cat", "a bird", "a car"]
for label, prob in zip(labels, probs[0]):
print(f"{label}: {prob:.2%}")
利用可能なモデル
# モデル(サイズ順)
models = [
"RN50", # ResNet-50
"RN101", # ResNet-101
"ViT-B/32", # Vision Transformer(推奨)
"ViT-B/16", # より高品質、遅い
"ViT-L/14", # 最高品質、最も遅い
]
model, preprocess = clip.load("ViT-B/32")
| モデル | パラメータ | 速度 | 品質 |
|---|---|---|---|
| RN50 | 102M | 速い | 良好 |
| ViT-B/32 | 151M | 中程度 | より良い |
| ViT-L/14 | 428M | 遅い | 最高 |
画像テキスト類似度
# 埋め込みを計算
image_features = model.encode_image(image)
text_features = model.encode_text(text)
# 正規化
image_features /= image_features.norm(dim=-1, keepdim=True)
text_features /= text_features.norm(dim=-1, keepdim=True)
# コサイン類似度
similarity = (image_features @ text_features.T).item()
print(f"Similarity: {similarity:.4f}")
セマンティック画像検索
# 画像をインデックス化
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)
# テキストクエリで検索
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)
# 最も類似した画像を検索
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}")
コンテンツモデレーション
# カテゴリを定義
categories = [
"safe for work",
"not safe for work",
"violent content",
"graphic content"
]
text = clip.tokenize(categories).to(device)
# 画像をチェック
with torch.no_grad():
logits_per_image, _ = model(image, text)
probs = logits_per_image.softmax(dim=-1)
# 分類を取得
max_idx = probs.argmax().item()
max_prob = probs[0, max_idx].item()
print(f"Category: {categories[max_idx]} ({max_prob:.2%})")
バッチ処理
# 複数の画像を処理
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)
# テキストをバッチ処理
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)
# 類似度マトリックス(10画像 × 3テキスト)
similarities = image_features @ text_features.T
print(similarities.shape) # (10, 3)
ベクトルデータベースとの統合
# CLIP埋め込みをChroma/FAISSに格納
import chromadb
client = chromadb.Client()
collection = client.create_collection("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 = "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倍高速
- 画像を前処理 - 提供されている前処理関数を使用
パフォーマンス
| 操作 | CPU | GPU (V100) |
|---|---|---|
| 画像エンコード | ~200ms | ~20ms |
| テキストエンコード | ~50ms | ~5ms |
| 類似度計算 | <1ms | <1ms |
制限事項
- 細粒度タスク向けではない - 広いカテゴリに最適
- 説明的なテキストが必須 - あいまいなラベルは性能が低い
- Webデータでのバイアス - データセットバイアスがある可能性
- バウンディングボックスなし - 画像全体のみ
- 空間理解が限定的 - 位置情報/数え上げは弱い
リソース
- GitHub: https://github.com/openai/CLIP ⭐ 25,300+
- 論文: https://arxiv.org/abs/2103.00020
- Colab: https://colab.research.google.com/github/openai/clip/
- ライセンス: MIT
ライセンス: MIT(寛容ライセンスのため全文を引用しています) · 原本リポジトリ
詳細情報
- 作者
- davila7
- ライセンス
- MIT
- 最終更新
- 不明
Source: https://github.com/davila7/claude-code-templates / ライセンス: MIT
関連スキル
agent-browser
AI エージェント向けのブラウザ自動化 CLI です。ウェブサイトとの対話が必要な場合に使用します。ページ遷移、フォーム入力、ボタンクリック、スクリーンショット取得、データ抽出、ウェブアプリのテスト、ブラウザ操作の自動化など、あらゆるブラウザタスクに対応できます。「ウェブサイトを開く」「フォームに記入する」「ボタンをクリックする」「スクリーンショットを取得する」「ページからデータを抽出する」「このウェブアプリをテストする」「サイトにログインする」「ブラウザ操作を自動化する」といった要求や、プログラマティックなウェブ操作が必要なタスクで起動します。
anyskill
AnySkill — あなたのプライベート・スキルクラウド。GitHubを基盤としたリポジトリからエージェントスキルを管理、同期、動的にロードできます。自然言語でクラウドスキルを検索し、オンデマンドでプロンプトを自動ロード、カスタムスキルのアップロードと共有、スキルバンドルの一括インストールが可能です。OpenClaw、Antigravity、Claude Code、Cursorに対応しています。
engram
AIエージェント向けの永続的なメモリシステムです。バグ修正、意思決定、発見、設定変更の後はmem_saveを使用してください。ユーザーが「覚えている」「記憶している」と言及した場合、または以前のセッションと重複する作業を開始する際はmem_searchを使用します。セッション終了前にmem_session_summaryを使用して、コンテキストを保持してください。
skyvern
AI駆動のブラウザ自動化により、任意のウェブサイトを自動化できます。フォーム入力、データ抽出、ファイルダウンロード、ログイン、複数ステップのワークフロー実行など、ユーザーがウェブサイトと連携する必要があるときに使用します。Skyvernは、LLMとコンピュータビジョンを活用して、未知のサイトも自動操作可能です。Python SDK、TypeScript SDK、REST API、MCPサーバー、またはCLIを通じて統合できます。
pinchbench
PinchBenchベンチマークを実行して、OpenClawエージェントの実世界タスクにおけるパフォーマンスを評価できます。モデルの機能テスト、モデル間の比較、ベンチマーク結果のリーダーボード提出、またはOpenClawのセットアップがカレンダー、メール、リサーチ、コーディング、複数ステップのワークフローにどの程度対応しているかを確認する際に使用します。
openui
OpenUIとOpenUI Langを使用してジェネレーティブUIアプリを構築できます。これらはLLM生成インターフェースのためのトークン効率的なオープン標準です。OpenUI、@openuidev、ジェネレーティブUI、LLMからのストリーミングUI、AI向けコンポーネントライブラリ、またはjson-render/A2UIの置き換えについて述べる際に使用します。スキャフォルディング、defineComponent、システムプロンプト、Renderer、およびOpenUI Lang出力のデバッグに対応しています。