معاينة مختبر آمنة
Clip
هذي معاينة منقّحة للقراءة فقط؛ ما فيه أي شيء يشتغل داخل الصفحة.
قراءة فقط
معاينة الدفتر
Clip
> **ملاحظة بيئة التشغيل المدمجة:** هالمعاينة تستخدم عيّنة صغيرة وثابتة وآمنة من ناحية الحقوق عشان تكون النتايج قابلة للتكرار. النتايج بالحجم الكامل تحتاج مجموعة البيانات أو النموذج الموثّق بالدرس داخل بيئة خارجية معتمدة.
# النماذج متعددة الوسائط
هالدفتر جزء من منهج AI for Beginners.
## بنجرّب CLIP
نموذج [CLIP](https://arxiv.org/abs/2103.00020) من OpenAI متاح للكل، فتقدرون تجرّبونه في مهام مختلفة، ومنها تصنيف الصور من غير أمثلة تدريبية (zero-shot image classification). بس خلو ببالكم إنه يستهلك موارد كثيرة!
import sys
# Dependencies are provisioned by this course edition's pinned runtime profile.أول شي، بنتأكد إننا نقدر نستخدم GPU إذا كان متوفر، وبعدها بنحمّل نموذج CLIP.
import torch
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
import os
np.set_printoptions(precision=2, suppress=True)
device = "cuda" if torch.cuda.is_available() else "cpu"
def preprocess(image):
pixels = np.asarray(image.convert("RGB").resize((32, 32)), dtype=np.float32) / 255.0
return torch.tensor(pixels).permute(2, 0, 1)
def course_tokenize(prompts):
rows = []
for prompt in prompts:
lowered = prompt.lower()
rows.append([float("cat" in lowered), float("penguin" in lowered), float("bear" in lowered), min(len(lowered) / 40.0, 1.0)])
return torch.tensor(rows, dtype=torch.float32)
class CourseClipFixture(torch.nn.Module):
def encode_image(self, images):
means = images.mean(dim=(2, 3))
luminance = images.mean(dim=(1, 2, 3)).unsqueeze(1)
return torch.cat((means, luminance), dim=1)
def encode_text(self, tokens):
return tokens
def forward(self, images, tokens):
image_features = torch.nn.functional.normalize(self.encode_image(images), dim=1)
text_features = torch.nn.functional.normalize(self.encode_text(tokens), dim=1)
logits = 10.0 * image_features @ text_features.T
return logits, logits.T
model = CourseClipFixture().to(device)
clip_tokenize = course_tokenizeوبناخذ بعد مجموعة فرعية من صور القطط من [مجموعة البيانات Oxford-IIIT](https://www.robots.ox.ac.uk/~vgg/data/pets/):
from pathlib import Path
from PIL import Image
import numpy as np
clip_root = Path("oxcats")
clip_root.mkdir(parents=True, exist_ok=True)
for index, name in enumerate(("Maine_Coon_1.jpg", "Abyssinian_1.jpg", "Persian_1.jpg")):
yy, xx = np.mgrid[:96, :96]
pixels = np.stack(((xx * (2 + index) + 60) % 256, (yy * (3 + index) + 40) % 256, ((xx + yy) * 2 + 25 * index) % 256), axis=-1).astype(np.uint8)
Image.fromarray(pixels).save(clip_root / name)
print("Prepared three generated cat images")### تصنيف الصور: التصنيف من غير أمثلة تدريبية
أهم شي يسويه CLIP إنه يطابق صورة مع موجّه نصي (text prompt). مثلًا، لو أخذنا صورة قط وحاولنا نطابقها مع الموجّهات "a cat" و"a penguin" و"a bear"، غالبًا بياخذ الموجّه الأول أعلى احتمال. ومن هالنتيجة نستنتج إن الصورة لقط. ما نحتاج ندرّب نموذج جديد؛ لأن CLIP متدرّب مسبقًا على مجموعة البيانات الضخمة، وعشان كذا نسمّي هالأسلوب **من غير أمثلة تدريبية (zero-shot)**.
image = preprocess(Image.open("oxcats/Maine_Coon_1.jpg")).unsqueeze(0).to(device)
text = clip_tokenize(["a penguin", "a bear", "a cat"]).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()
print("Label probs:", probs)### البحث الذكي في الصور
في المثال اللي فات، كان عندنا صورة وحدة و 3 موجّهات نصية. ونقدر نستخدم CLIP بالعكس: نعطيه صور قطط كثيرة، ثم نختار الصورة اللي تناسب الوصف النصي أكثر:
cats_img = [ Image.open(os.path.join("oxcats",x)) for x in os.listdir("oxcats") ]
cats = torch.cat([ preprocess(i).unsqueeze(0) for i in cats_img ]).to(device)
text = clip_tokenize(["a very fat gray cat"]).to(device)
with torch.no_grad():
logits_per_image, logits_per_text = model(cats, text)
res = logits_per_text.softmax(dim=-1).argmax().cpu().numpy()
print("Img Index:", res)
plt.imshow(cats_img[res])## خلاصة
نموذج CLIP المدرّب مسبقًا يقدر ينفّذ مهام مثل تصنيف الصور للأجسام الشائعة من غير تدريب خاص بالمجال. ويخلّي التصنيف والبحث في الصور أكثر مرونة؛ لأنه ياخذ بالاعتبار ترتيب الأجسام ومواقعها داخل الصورة.
ولاستخدام ثاني ممتع لـ CLIP، شوفوا **VQGAN+CLIP**.
حذفنا المخرجات وعدّادات التشغيل والودجات والمحتوى النشط وقت الاستيراد. شغّل الدفاتر بس في بيئة خارجية تثق فيها.
سجّل تطبيقك
التسجيل اختياري، يفيدك تتذكر وش طبّقت، ولا يمنع إكمال الدورة.