Chuyển tới nội dung chính

{/* Trang này được tạo tự động từ SKILL.md của kỹ năng bởi website/scripts/generate-skill-docs.py. Chỉnh sửa nguồn SKILL.md, không phải trang này. */}

CLIp

Mô hình kết nối tầm nhìn và ngôn ngữ của OpenAI. Cho phép phân loại hình ảnh không chụp, khớp văn bản hình ảnh và truy xuất đa phương thức. Được đào tạo về các cặp văn bản-hình ảnh 400M. Sử dụng để tìm kiếm hình ảnh, kiểm duyệt nội dung hoặc các tác vụ ngôn ngữ thị giác mà không cần tinh chỉnh. Tốt nhất cho sự hiểu biết hình ảnh có mục đích chung.

Siêu dữ liệu kỹ năng

NguồnTùy chọn — cài đặt với
`Hermes skills install official/mlops/CLIp
`
Đường dẫn

optional-skills/mlops/CLIp ` | | Phiên bản |

1.0.0 ` | | Tác giả | Nghiên cứu dàn nhạc | | Giấy phép | MIT | | Phụ thuộc |

transformers

, `torch

, pillow | | Nền tảng | Linux, macOS, Windows | | Thẻ |

Multimodal

, `CLIP

, `Vision-Language

, `Zero-Shot

, `Image Classification

, `OpenAI

, `Image Search

, `Cross-Modal Retrieval

, Content Moderation |

Tham khảo: đầy đủ SKILL.md

thông tin

Sau đây là định nghĩa kỹ năng đầy đủ mà Hermes tải khi kỹ năng này được kích hoạt. Đây là những gì tác nhân coi là hướng dẫn khi kỹ năng được kích hoạt.

CLIP - Đào tạo trước về ngôn ngữ-hình ảnh tương phản

Mô hình của OpenAI hiểu hình ảnh từ ngôn ngữ tự nhiên.

Khi nào nên sử dụng CLIP`Sử dụng khi:

  • Phân loại hình ảnh Zero-shot (không cần dữ liệu đào tạo)
  • Tương tự/khớp giữa hình ảnh và văn bản
  • Tìm kiếm hình ảnh ngữ nghĩa
  • Kiểm duyệt nội dung (phát hiện NSFW, bạo lực)
  • Trả lời câu hỏi trực quan
  • Truy xuất đa phương thức (hình ảnh→văn bản, văn bản→hình ảnh)

Số liệu:

  • 25.300+ sao GitHub
  • Được đào tạo về cặp văn bản-hình ảnh 400M
  • Phù hợp với ResNet-50 trên ImageNet (không bắn)
  • Giấy phép MIT`Thay vào đó hãy sử dụng các lựa chọn thay thế:
  • BLIP-2: Chú thích tốt hơn
  • LLaVA: Trò chuyện bằng ngôn ngữ thị giác
  • Phân đoạn mọi thứ: Phân đoạn hình ảnh

Bắt đầu nhanh

Cài đặt

pip install git+https://GitHub.com/OpenAI/CLIP.git
pip install torch torchvision ftfy regex tqdm

`

### Phân loại không bắn

`Python
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%}")

`
``##Mẫu có sẵn

`Python

# 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")

`

| Người mẫu | Thông số | Tốc độ | Chất lượng |
|-------|-----------------|-------|----------|
| RN50 | 102 triệu | Nhanh | Tốt |
| ViT-B/32 | 151 triệu | Trung bình | Tốt hơn |
| ViT-L/14 | 428 triệu | Chậm | Tốt nhất |

## Sự tương đồng giữa hình ảnh và văn bản

``` python

# 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}")

`

## Tìm kiếm hình ảnh theo ngữ nghĩa

``` python

# 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}")

`

## Kiểm duyệt nội dung

``` python

# 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%})")

`

## Xử lý hàng loạt

``` python

# 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)

`

## Tích hợp với cơ sở dữ liệu vectơ

``` python

# 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
)

`

## Các phương pháp hay nhất
1. **Sử dụng ViT-B/32 cho hầu hết các trường hợp** - Cân bằng tốt
2. **Bình thường hóa các phần nhúng** - Bắt buộc đối với độ tương tự cosine
3. **Xử lý hàng loạt** - Hiệu quả hơn
4. **Nhúng bộ đệm** - Tốn kém khi tính toán lại
5. **Sử dụng nhãn mô tả** - Hiệu suất chụp ảnh không điểm tốt hơn
6. **Khuyến nghị GPU** - nhanh hơn 10-50×
7. **Tiền xử lý hình ảnh** - Sử dụng chức năng tiền xử lý được cung cấp

## Hiệu suất

| Hoạt động | CPU | GPU (V100) |
|----------||------|-------------|
| Mã hóa hình ảnh | ~200 mili giây | ~20ms |
| Mã hóa văn bản | ~50 mili giây | ~5 mili giây |
| Tính toán tương tự | <1ms | <1ms |

## Hạn chế
1. **Không dành cho các nhiệm vụ chi tiết** - Tốt nhất cho các danh mục rộng
2. **Yêu cầu văn bản mô tả** - Nhãn mơ hồ hoạt động kém
3. **Thành kiến về dữ liệu web** - Có thể có thành kiến về dữ liệu
4. **Không có hộp giới hạn** - Chỉ toàn bộ hình ảnh
5. **Hiểu biết không gian hạn chế** - Vị trí/đếm yếu

## Tài nguyên
- **GitHub**: https://GitHub.com/OpenAI/CLIP ⭐ 25.300+
- **Giấy**: https://arxiv.org/abs/2103.00020
- **Colab**: https://colab.research.Google.com/GitHub/OpenAI/CLIp/
- **Giấy phép**: MIT